brain storm
brain storm

Reputation: 31252

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

Upvotes: 0

Views: 937

Answers (2)

William Gaul
William Gaul

Reputation: 3181

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.

Upvotes: 1

Moritz Petersen
Moritz Petersen

Reputation: 13057

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.

Upvotes: 1

Related Questions