Search code examples
javafile-ioiofileoutputstream

what is the difference between these two ways of writing to a file in java?


I have two implementations below, where the PrintStream object wraps either FileOutputStream object or File object. I get the same thing done with both. Are there any difference between them where one method will not be applicable to write.

public class Varags {
        public static void main(String[] args) throws FileNotFoundException{

            OutputStream output = new FileOutputStream("Test.txt");
                         PrintStream p1=new PrintStream( output);
                         p1.println("trying");

            PrintStream p=new PrintStream( new File("test2.txt"));
            p.println("trying");
}
}

Are there other way of writing to file that is better than these?

Thanks


Solution

  • As far as I know there is no difference. According to the Javadocs the File version creates an OutputStreamWriter anyways, and is only included for convenience.

    In many cases, using a Writer is better for plain text input. If you're working with raw byte data then streams such as FileInputStream, FileOutputStream, etc. will be necessary.