Elad Benda2
Elad Benda2

Reputation: 15502

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

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?

Upvotes: 0

Views: 201

Answers (2)

Bruno Franco
Bruno Franco

Reputation: 2037

I don't know how to modify the file you are reading at the moment, one idea is using a temporary file to do it, and when reading it to the old one, you can change it and save in the new one.

If you want to write it line by line, running some algorithm in the meantime, i think you should use this way:

public static void writeFile1() throws IOException {
    File fout = new File("out.txt");
    FileOutputStream fos = new FileOutputStream(fout);

    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));

    for (int i = 0; i < 10; i++) {
        // Use your algorithm
        bw.write("something");
        bw.newLine();
    }

    bw.close();
}

Upvotes: 1

Braj
Braj

Reputation: 46871

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.

Upvotes: 1

Related Questions