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 aboutPrintWriter– my problem withPrintWriteris that it swallows exceptions.It’s worth understanding why
FileInputStreamandFileOutputStreamdon’t have any methods relating to lines though: the*Streamclasses are about streams of binary data. There’s no such thing as a “line” in terms of binary data. The*Readerand*Writerclasses are about text, where the concept of a line makes a lot more sense… although a generalReaderdoesn’t have enough smarts to read a line (just a block of characters) so that’s whereBufferedReadercomes in.InputStreamReaderandOutputStreamWriterare 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
BufferedReaderwrapping anInputStreamReaderwrapping aFileInputStreamfor reading – then callreadLine(). For writing, use aBufferedWriterwrapping anOutputStreamWriterwrapping aFileOutputStream– then callwrite(String)andnewLine(). (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
FileReaderclass which sort of combinesFileInputStreamandInputStreamReader(andFileWriterdoes the equivalent) but these always use the platform default encoding, which is almost never what you want. That makes them all but useless IMO.