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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With