4

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

rover12
  • 2,806
  • 7
  • 27
  • 28

2 Answers2

15

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I agree PrintWriter has drawbacks, but it was the one closest to the question. I started out suggesting a Writer but it really doesn't do "line by line". Good point though (+1). – Fredrik Nov 20 '09 at 07:20
  • @Fredrik: It's not your fault that the Java library designers decided to give PrintWriter too many responsibilities :( – Jon Skeet Nov 20 '09 at 07:31
  • @Jon: Thank you :-) I know that, I just wanted to explain why I recommended it anyway. – Fredrik Nov 20 '09 at 11:56
7

I think what you are looking for is a BufferedReader and a PrintWriter.

Check out this one for a sample of the first: http://www.java2s.com/Tutorial/Java/0180__File/CreateBufferedReaderfromInputStreamReader.htm

Fredrik
  • 5,759
  • 2
  • 26
  • 32