1

I have been trying to write to a file in Android. It is not working and it doesn't even create a file. It always executes the catch block. Here is the part of my program.

private void write(){
    try {
        FileWriter fileWriter  = new FileWriter("C:\\Users\\Administrator\\AndroidStudioProjects\\SunCalculator\\app\\src\\main\\res\\raw\\au_locations.txt");
        Log.e("Data","path detected");
        BufferedWriter bfWriter = new BufferedWriter(fileWriter);
        bfWriter.write("Text Data");
        bfWriter.close();
        Log.e("Data","worked");
    } catch (IOException e) {
        e.printStackTrace();
        Log.e("Data","not worked");
    }
}

I also tried to create a File object and passing it to the FileWriter constructor. None of these worked. I am using Android Studio 2.3.3

7
  • The questions are: from where do you execute this code, what is error message and is C:\Users\Administrator is write-enabled. Oct 16, 2017 at 1:13
  • 1
    Your Android device/emulator does not have a C: drive. Furthermore, you can't write to resources at runtime, if that's actually what you're attempting.
    – Mike M.
    Oct 16, 2017 at 1:13
  • You must be getting some exceptions and posting it here would surely help. Oct 16, 2017 at 1:15
  • I also tried to write to D:\. It also did not work. My project path is C:\Users\Administrator\AndroidStudioProjects\SunCalculator
    – migara
    Oct 16, 2017 at 1:16
  • Those drives/paths only exist on your development machine. They will not exist on an Android system.
    – Mike M.
    Oct 16, 2017 at 1:18

1 Answer 1

0

You are trying to write a file in location C:\\Users.... which is the directory structure of Windows OS.

But Android is built upon Linux OS. To get the user writeable directory in android, you should use Environment.getExternalStorageDirectory() as below:

File file = new File(Environment.getExternalStorageDirectory(), filename);
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.