简体   繁体   中英

Impossibility to create CSV file in Android, always fails

I know there are a few topics on this around stackoverflow but I cannot find any that solves my problem.

I have successfuly implemented (it's tested) SharedPreferences to save my application data and my objective now is to export that data to a CSV file.

This is what I was trying to do:

public void saveCSVFile(List<PessoaClass> data) { 
    PrintWriter writer;
    String strFilePath = "C:\\users\\ricardo\\desktop\\testesCSV\\pessoas.csv";
    try {
        File file = new File(strFilePath);
        if(!file.exists())
            file = new File(strFilePath);

        writer = new  PrintWriter(new FileWriter(file,true));

        for(int i = 0; i < data.size(); i++ ){
            writer.print(data.get(i).getAge());
            writer.print(data.get(i).getSex());             
            writer.print(data.get(i).getName());
            writer.print(data.get(i).getEmail());
            writer.print("\r\n");
        }
        writer.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

The error I keep running into its "java.io.FileNotFoundException: C:\\users\\ricardo\\desktop\\testesCSV\\pessoas.csv (Read-only file system)"

In order to test with CSVWriter library, I also tried the following sample code:

public void saveCSVFile() {
    String csv = "C:\\users\\ricardo\\desktop\\testesCSV\\pessoas.csv";
    try {
        CSVWriter writer = new CSVWriter(new FileWriter(csv));
        List<String[]> imprimir = new ArrayList<>();

        imprimir.add(new String[]{"India", "New Delhi"});
        imprimir.add(new String[]{"United States", "Washington D.C"});
        imprimir.add(new String[]{"Germany", "Berlin"});

        writer.writeAll(imprimir);
        writer.close();
    }

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

The error was the same. I have tried to run Android Studio as Administrator - no success.

I don't understand what the error is because I am trying to write to my personal computer Desktop, not to app/app without root permissions as some other users in the website.

This app is meant to run in a non-rooted device.

Any help is appreciated!

"java.io.FileNotFoundException:

C:\\users\\ricardo\\desktop\\testesCSV\\pessoas.csv (Read-only file system)"

That is a path on your windows computer. On the C: partition. But your app runs on an Android device and has no acces to files on your computer.

Instead use

File file = new File(getExternalFilesDir(null), "pessoas.csv");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM