3

I created a simple method to append text to a file:

void writeFile(String fileName, String... values) {
    File file = new File(fileName);
    file.getParentFile().mkdirs();
    try(BufferedWriter bw = new BufferedWriter(new FileWriter(file, true))) {
        for (String value: values) {
            bw.write(value);
            bw.newLine();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

However, I am at a loss on how to check if a new line exists at the end of the file before writing to ensure that it is stored properly.

Also, it would have to be scalable for when working with larger files.

Jsilvermist
  • 491
  • 7
  • 16

1 Answers1

9

Thanks to SMA linking to Quickly read the last line of a text file?, I was able to create a method to check if a new line exists, and then create a new line if it doesn't.

static void writeFile(String fileName, String... values) {
    File file = new File(fileName);
    file.getParentFile().mkdirs();
    boolean fileExists = file.exists();
    try (BufferedWriter bw = new BufferedWriter(new FileWriter(file, true))) {
        if (fileExists && !newLineExists(file)) {
            bw.newLine();
        }
        for (String value : values) {
            bw.write(value);
            bw.newLine();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

static boolean newLineExists(File file) throws IOException {
  try (RandomAccessFile fileHandler = new RandomAccessFile(file, "r")) {
    long fileLength = fileHandler.length() - 1;
    if (fileLength < 0) {
      return true;
    }
    fileHandler.seek(fileLength);
    byte readByte = fileHandler.readByte();

    return readByte == 0xA || readByte == 0xD;
  }
}
Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
Jsilvermist
  • 491
  • 7
  • 16