arindrajit
arindrajit

Reputation: 76

How to ""save" the result in a text file in java

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

Answers (2)

Andrew Thompson
Andrew Thompson

Reputation: 168825

See new FileOutputStream(file, true); (or fileName as name instead of a file object) as documented in the constructors for the class.

Further tips

1. Reporting

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.

2. GUI

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:

  1. read(Reader, Object)
  2. write(Writer)

Upvotes: 0

vikingsteve
vikingsteve

Reputation: 40378

try this:

out = new FileOutputStream("myfile.txt", true);

Javadoc: FileOutputStream.append(String name, boolean append)

Upvotes: 4

Related Questions