how to write efficiently and not create a new file object too often?

advertisements

I saw this excellent post on how to write to file in java.

I have two questions:

1) how would you modify file content you're reading now?

i.e. I read a line, modify it based on algorithm result and I move to read next line.

2) how would you write to a file progressively?

i.e. I read a line, I write a new line to an output file based on algorithm result and I move to read next line.

I thought to use:

private static void writeUsingFiles(String data) {
        try {
            Files.write(Paths.get("/Users/pankaj/files.txt"), data.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

But then I thought if it's wasteful for many writes?

as new File object is created every time?


I read a line, I write a new line to an output file based on algorithm result and I move to read next line

Use Java 7 The try-with-resources Statement using BufferedWriter and BufferedReader for better performance with proper resources handling.

Sample code

String line = null;
try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
        BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
    while ((line = reader.readLine()) != null) { // read line
        String processedLine = getProcessedLine(line); // get processed line
        writer.write(processedLine); // writer the process line
        writer.newLine();  // writer new line if needed
    }
}

private String getProcessedLine(String line){...}

Finally delete input.txt file and rename the output.txt to input.txt.