Search

Tuesday, June 30, 2015

How to write to File in Java using BufferedWriter

You can use either OutputStream or Writer class in Java to write data to a file in Java. For example you can use combination of FileWriter and BufferedWriter to write text content into a text file in Java. If you want to write raw bytes consider using FileOutputStream class. Just remember that InputStream is used to read data and OutputStream is used to write data to file or socket. You can write anything to file e.g. String, integer, float values etc. Java provides DataOutputStream to write different data type directly into file e.g. writeInt() to write integer values, writeFloat() to write floating point values into file and writeUTF() to write String into File.  BufferedWriter, like its counterpart BufferedReader allows you to perform buffered IO, which can drastically improve performance while reading large files. Java provides many convenient wrapper classes for reading and writing data into files e.g. you can use PrintWriter to write data line by line into file. It's println() method automatically adds line separator after each line.  Java 7 has also introduced even a brand new API known as new File API, which provides powerful methods to read whole file in just one line. All in all, Java has got really good support to deal with files in Java and we will explore more of them in coming tutorials. By the way, if you are beginner and just started learning Java, I would recommend you to at-least read one Java book to get a complete overview, later you can fine tune your knowledge by reading tutorials. You can refer Java: A Beginner's Guide by Herbert Schildt to start with Java. This book contains very good example and comprehensive theory and most important its up-to-date and covers even Java 8.
Read more »

No comments:

Post a Comment