Results 1 to 2 of 2
- 06-05-2014, 07:17 AM #1Member
- Join Date
- May 2014
- Rep Power
best method to write to a file in Java 8
After reading the Oracle documentation, I noticed there are quite a few ways to write to a file. In Java 8, you can reference the Paths class and use Files.write to write to the specified file:
String msg = "hello"; Files.write(Paths.get("./file.txt"), msg.getBytes());
PrintWriter out = new PrintWriter("file.txt"); out.println(msg);
writer = new BufferedWriter( new FileWriter( file.txt)); writer.write( msg);
- 06-05-2014, 07:39 AM #2Senior Member
- Join Date
- Feb 2014
- Rep Power
Re: best method to write to a file in Java 8
The preferred way always depends on your requirements and your preferences.
So my suggestion is, that you read in full detail about each possibility and try to find out the main differences.
Just let us take the first version:
This version writes the bytes. So you can define the encoding. So you can change the code that gets the bytes in any way so you could write ASCII, UTF-8, UTF-16, UTF-32, ...... There are so many possibilities.
Something like that might also be possible with other solutions but might be more complex or simply different (So you have to decide which solution fits better in your project).
And your list is far from complete. You can also use streams to write to a file. Either direct or with a Writer.
One pattern that we use in our job is also a separation of "Producer" and "Consumer" (These words do not fit 100%). So you have code that produces a message. This producer simply produces its output on a given stream. Then you can use that without any trouble to get the output wherever you want. All you need is a stream. So it could be a stream to a file, a stream on a network socket, a stream to a buffer, ....
So to find your prefered way, you should try to read about all solutions. Check the methods and properties of all classes. What are the differences? What can you do with the methods? If you need a method of one class which the other classes does not have, then you have a reason for a specific class.
- By Amar in forum Apache POIReplies: 0Last Post: 01-28-2014, 06:50 AM
- By sanjeev4343 in forum New To JavaReplies: 1Last Post: 07-08-2012, 10:12 PM
- By Anagha in forum New To JavaReplies: 7Last Post: 04-06-2011, 07:50 AM
- By njoymirror in forum New To JavaReplies: 2Last Post: 03-21-2009, 02:19 AM
- By mathias in forum New To JavaReplies: 1Last Post: 07-31-2007, 07:51 PM