Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileInputStream and FileOutputStream line by line

Tags:

java

FileInputStream reads all bytes of a file and FileOutputStream writes allbytes to a file

which class do i use if i want to read all bytes of a file but line by line

so that

if fileA contains two lines

line1 line2

then bytes of line1 and line2 are read seperately

same goes for FileOutputStream

like image 969
rover12 Avatar asked Nov 29 '22 19:11

rover12


1 Answers

Fredrik is right about BufferedReader, but I'd disagree about PrintWriter - my problem with PrintWriter is that it swallows exceptions.

It's worth understanding why FileInputStream and FileOutputStream don't have any methods relating to lines though: the *Stream classes are about streams of binary data. There's no such thing as a "line" in terms of binary data. The *Reader and *Writer classes are about text, where the concept of a line makes a lot more sense... although a general Reader doesn't have enough smarts to read a line (just a block of characters) so that's where BufferedReader comes in.

InputStreamReader and OutputStreamWriter are adapter classes, applying a character encoding to a stream of bytes to convert them into characters, or a stream of characters to turn them into bytes.

So, you probably want a BufferedReader wrapping an InputStreamReader wrapping a FileInputStream for reading - then call readLine(). For writing, use a BufferedWriter wrapping an OutputStreamWriter wrapping a FileOutputStream - then call write(String) and newLine(). (That will give you the platform default line separator - if you want a specific one, just write it as a string.)

There's also the FileReader class which sort of combines FileInputStream and InputStreamReader (and FileWriter does the equivalent) but these always use the platform default encoding, which is almost never what you want. That makes them all but useless IMO.

like image 172
Jon Skeet Avatar answered Dec 20 '22 03:12

Jon Skeet