Reputation: 76
I want to save the output result to a text file and retrieve it whenever I want to. For writing the output to .txt, I have used the following code.
import java.io.*;
class FileOutputDemo {
public static void main(String args[])
{
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object
try
{
// Create a new file output stream
// connected to "myfile.txt"
out = new FileOutputStream("myfile.txt");
// Connect print stream to the output stream
p = new PrintStream( out );
p.append ("This is written to a file");
p.close();
}
catch (Exception e)
{
System.err.println ("Error writing to file");
}
}
}
It is working fine and the intended text file is written. But whenever I re-compile the program, the new output is written whereas the previous output is deleted. Is there a way to save the output of the previously written file and to pick up from where the previous text file left off (After re-compiling it).
Upvotes: 0
Views: 4961
Reputation: 168825
See new FileOutputStream(file, true);
(or fileName
as name instead of a file
object) as documented in the constructors for the class.
Change:
catch (Exception e)
{
System.err.println ("Error writing to file");
}
To:
catch (Exception e)
{
e.printStackTrace();
}
The latter provides more information with less typing.
If this app. is to have a GUI, the text would typically be input by the user in a JTextArea
. That component extends from JTextComponent
which offers almost a 'one-liner' for saving and loading text:
Upvotes: 0
Reputation: 40378
try this:
out = new FileOutputStream("myfile.txt", true);
Javadoc: FileOutputStream.append(String name, boolean append)
Upvotes: 4