1

I am trying to add a new line to an existing text file, which works but sometimes adds a blank line in between the old data and the new data

So I have a file with the data:

mouse
keyboard

And when adding, it adds it like this:

mouse
keyboard

printer

but I don't want an empty line in between the old and new text. This is the code I have used:

String filename= "Stock.txt"
FileWriter fw = new FileWriter(filename,true);
fw.write(System.lineSeparator() + data);
fw.close();
ahsirk83
  • 23
  • 4

1 Answers1

-1

Buffer reader and Buffer writer are the preferred classes to use when reading and writing too and from files.

You can achieve this a few ways.

Example 1 - Using File, FileWriter and BufferWriter classes with manual close :

    File file = new File("Stock.txt");
    FileWriter fr = new FileWriter(file, true);
    BufferedWriter br = new BufferedWriter(fr);
    br.write(data + "\n");

    br.close();
    fr.close();

Example 2 - Using File, FileWriter and BufferWriter classes with try-with-resource, which will auto-close the resource when processing has ceased :

    File file = new File("Stock.txt");

    try (FileWriter fileWriter = new FileWriter(file, true);
         BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {

        bufferedWriter.write(data + "\n");

    } catch (FileNotFoundException e) {
        System.out.println("Unable to open file, file not found.");
    } catch (IOException e) {
        System.out.println("Unable to write to file." + file.getName());

    }

See: https://stackabuse.com/reading-and-writing-files-in-java/ for some really useful info on reading and writing files!

See: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html for info on try-with-resource.

Bradley
  • 327
  • 2
  • 11