user3742929
user3742929

Reputation: 400

FileOutputStream does nothing (Android Studio)

I have this method for writing some logged data to my sd card. However it doesn't even create a file.

 public void writeToFile(LinkedList<double[]> data, String name) throws IOException {
    String dataS = "";
    dataS += "x;y;z;size\n";
    for (int i = 0; i < data.size() - 1; i++) {
        dataS += data.get(i)[0] + ";" + data.get(i)[1] + ";" + data.get(i)[2] + ";" + data.get(i)[3] + "\n";
    }

    try {
        String filename = name + ".csv";

        File myFile = new File(Environment
                .getExternalStorageDirectory(), filename);

        if (!myFile.exists()) {
            myFile.createNewFile();
        }

        FileOutputStream fos;

        System.out.println(myFile.getAbsolutePath());
        byte[] dataByte = dataS.getBytes();
        try {
            fos = new FileOutputStream(myFile);
            fos.write(dataByte);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

I have added the right rights in the Manifest.xml:

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Upvotes: 1

Views: 193

Answers (1)

Jinesh Francis
Jinesh Francis

Reputation: 3655

Make file in the root directory like this.

File myFile = new File(Environment.getExternalStorageDirectory()+"/"+filename);

Remove this code

if (!myFile.exists()) {
   myFile.createNewFile();
}

Upvotes: 1

Related Questions