0

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).

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
arindrajit
  • 76
  • 1
  • 7

2 Answers2

4

try this:

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

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

vikingsteve
  • 38,481
  • 23
  • 112
  • 156
0

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)
Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433