0
import java.io.*;

public class Main {

    public static void main(String[] args) 
    {
        PrintWriter pw = null;
        //case 1:
        try
        {   
            pw = new PrintWriter(new BufferedWriter(new FileWriter(new File("case1.txt"),false)),true);
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }

        for(int i=0;i<100;i++)
            pw.write("Hello " + String.valueOf(i));

        pw.close();

        //case 2:
        try
        {
            pw = new PrintWriter(new FileWriter(new File("case2.txt"),false),true);
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }

        for(int i=0;i<100;i++)
            pw.write("Hello " + String.valueOf(i));

        pw.close();
    }
}

In both cases, the pw.write(...) appends to file so that the output contains one hundred messages,whilst only the last is desired. What is the best(I mean most graceful or efficient) method to do what I want?

UPDATE

Answers like "just print the last value" are unacceptable as this example is only SSCCE from larger problem.

0x6B6F77616C74
  • 2,559
  • 7
  • 38
  • 65

1 Answers1

0

I'm unclear of what parts of this method you can control and what you can't. It's clear that if you could control the for loop this would be easy. It seems from your examples that what you can control, however, is the creation of the PrintWriter. If this is the case, rather than creating it directly from a FileWriter, create it from an in memory stream, and then you can mess with the in memory stream however you like.

Create an in-memory PrintWriter using a StringWriter. You can get the underlying buffer from the StringWriter and clear it if you need to.

StringWriter sr = new StringWriter();
PrintWriter w = new PrintWriter(sr);

// This is where you pass w into your process that does the actual printing of all the lines that you apparently can't control.
w.print("Some stuff");
// Flush writer to ensure that it's not buffering anything
w.flush();

// if you have access to the buffer during writing, you can reset the buffer like this:
sr.getBuffer().setLength(0);

w.print("New stuff");

// write to final output
w.flush();



// If you had access and were clearing the buffer you can just do this.
String result = sr.toString();

// If you didn't have access to the printWriter while writing the content
String[] lines = String.split("[\\r?\\n]+");
String result = lines[lines.length-1];

try
{
    // This part writes only the content you want to the actual output file.
    pw = new PrintWriter(new FileWriter(new File("case2.txt"),false),true);
    pw.Print(result);
}
catch(IOException e)
{
    e.printStackTrace();
}

reference: how to clear contents of a PrintWriter after writing

Community
  • 1
  • 1
Ted
  • 3,212
  • 25
  • 20