-1

I am working on an app for android that will create a new .txt file on the SDcard mounted to the phone. I am new to android programming but I wrote this code. And then I tested the app on a real phone(not emulator). I navigated to My Files>All files>SD memory card and the file that is supposed to be created is not there. What am I doing wrong and how to fix my error? Thanks in advance !

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String filename = "filename.txt";
    File file = new File(Environment.getExternalStorageDirectory(), filename);
    FileOutputStream fos;
    byte[] data = new String("data to write to file").getBytes();
    try {
        fos = new FileOutputStream(file);
        fos.write(data);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        // handle exception
    } catch (IOException e) {
        // handle exception
    }

UPDATE !!!

I found the files created in the phone's memory for some reason. Why this happened and how to create them in the memory card instead?

omar saab
  • 31
  • 3

3 Answers3

0
File extDir = getExternalFilesDir(null);
String path = extDir.getAbsolutePath();
File file = new File(extDir, "filename.txt");
if(checkExternalStorage()){
  String text ="writing into externanal storage";
  FileOutputStream fos;
        try {
            fos = new FileOutputStream(file);
            fos.write(text.getBytes());
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
}
public boolean checkExternalStorage() {
    String state = Environment.getExternalStorageState();
    if (state.equals(Environment.MEDIA_MOUNTED)) {
        return true;
    }
    return false;
}
Sai Phani
  • 462
  • 3
  • 6
0

Ok, I think that this code do you want...

File sd = Environment.getExternalStorageDirectory();
File f = new File(sd.getAbsolutePath(), filename);

OutputStreamWriter fout = new OutputStreamWriter(new FileOutputStream(f));

fout.write("this is a test.");
fout.close();

I hope it works!

Alejandro Lora
  • 7,203
  • 3
  • 18
  • 34
0

To access the actual SD card use:

String path = Syst.env("SECONDARY_STORAGE");
J Richard Snape
  • 20,116
  • 5
  • 51
  • 79
Kat
  • 11
  • 2