0

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

brain storm
  • 30,124
  • 69
  • 225
  • 393
  • Helpful:http://stackoverflow.com/questions/5759925/printwriter-vs-filewriter-in-java – Suresh Atta Sep 05 '13 at 06:44
  • *"Are there other way of writing to file that is better than these?"* - Yes, but it depends what you mean by better, and what you are trying to write. (If you only want to write a single string to the file, "better" is irrelevant!) – Stephen C Dec 16 '20 at 04:01

2 Answers2

1

PrintStream provides some convenience methods for writing text to a file. To get more control about writing characters to a file, use PrintWriter.

OutputStream is used to write bytes (pure data, not just text) to a file.

Moritz Petersen
  • 12,902
  • 3
  • 38
  • 45
1

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.

M. Al Jumaily
  • 731
  • 1
  • 6
  • 21
William Gaul
  • 3,181
  • 2
  • 15
  • 21