Search code examples
javafilefilewriter

Filewriter creates a file that is read-only


I use a filewriter to write an arraylist of objects to a file, as strings, in a kind- of CSV like format. Anyway I had problems getting it to work, but now I get a FileNotFound exception and it says the file created is read-only in the exception. The file is created, as I checked, but apparently cannot be written to. However I actually want to overwrite the contents anyway, but get this error.

        ///Like a CSV file. 
        try{
            FileWriter writer_file = new FileWriter("PeopleDetailsFile");

            String filestring = ""; ///initializes filestring, which is written to the file.
            for(PeopleDetails person : peopledetails_file){
                String person_detail_string = "";
                person_detail_string = person.name + "," + person.number;
                filestring = filestring + person_detail_string + ";";

            }
            writer_file.write(filestring);
            writer_file.close();
        }
            catch (IOException e) {
                Log.e("ERROR", e.toString());

        }finally{
            ///Hopefully won't get an error here.
            Intent switch_menu = new Intent(this, MenuList.class);
            startActivity(switch_menu);
        }

Solution

  • Call this method with fileName and the List as Argument.

    public void fileWrite(String fileName,ArrayList<PeopleDetails> person){
            File           f ;
            FileWriter     fw = null;
            BufferedWriter bw = null;
            try {
                f  = new File(fileName);
                fw = new FileWriter(f.getAbsoluteFile());
                bw = new BufferedWriter(fw);
                for(PeopleDetails i:person){
                    bw.write(i.name+","+i.number+";");
                    bw.newLine();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                try {
                    if(bw!=null)
                        bw.close();
                    if(fw!=null)
                        fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }   
        }