Question

I'm trying to create a method that replaces every line in my file with a given. Instead it just makes the file empty. Care to take a look and see what is up? Thanks.

try {

            FileReader fr = new FileReader(chooser.getSelectedFile());
            BufferedReader reader = new BufferedReader(fr);
            FileWriter fw = new FileWriter(chooser.getSelectedFile());
            BufferedWriter bw = new BufferedWriter(fw);
            String line = reader.readLine();
            Scanner scan = null;
            int i=0;
            while (line != null) {
                scan = new Scanner(line);
                ln = scan.toString() + add;
                bw.write(ln);
                bw.newLine();
                i++;
                System.out.println(i + " pass");
                line = reader.readLine();
            }
            reader.close();
            bw.close();
        } catch (FileNotFoundException e) {
            System.out.println("Can't find the file");
        } catch (IOException e) {
            System.out.println("Dude, it's impossibru to read.");
        }

The i in this method is too see how many passes the programme goes through a while loop, in this case 0, it doesn't initiate a while loop at all.

Was it helpful?

Solution

If you want to overwrite the same file with your new lines you should do first all the reading, and then all the writing.

ArrayList<String> lines = new ArrayList<String>();

//start reader, go over each line

while (line != null) {
    String newLine = //make changes to line
    lines.add(newLine);
}

//close reader
//start writer
//write each line to file

OTHER TIPS

You opened file in replace mode, your FileWriter will empty file before first line will be written. Use FileWriter(file,true) if you want to append.

Second problem is you are reading and writing at the same time. Try next sequence:

  1. read whole file
  2. replace all lines
  3. write (replace old file)

Thus you will minimize problems count

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top