简体   繁体   中英

Check if a new line exists at end of file

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.

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.

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();
    }
}

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

    if (readByte == 0xA || readByte == 0xD) {
        return true;
    }
    return false;
}

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