Read files using these classes:
FileReader for text files in systems default encoding
FileInputStream for binary files and text files that contain weird characters
FileReader (for text files) should be wrapped in a BufferedReader. This saves up data, deal with a line
at a time instead of character by character.
Write files using these classes:
FileWriter for text files.
FileOutputStream for binary files and weird texts
FileWriter should be wrapped in a BufferedWriter.
Reading ordinary text files
If Im supposed to read an ordinary text file in systems default encoding, I need to use FileReader and
wrap it in a BufferedReader.
Example (how to read a file):
try{
FileReader fileReader = new FileReader(fileName);
// Always need to wrap this in BufferedFileReader
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine())!=null) {
System.out.println(line);
}
bufferedReader.close();// Always close the file
} catch(FileNotFoundException e){
} catch(IOExcetpion e) {
Reading binary files
If Im supposed to read a binary file, or a text file containg weird characters, I should use
FileInputStream instead of FileReader. Instead of wrapping FileInputStream in a buffer,
FileInputStream defines a method called read(put some buffer here) that lets me fill a buffer with a
data, automatically reading just enough bytes to fill the buffer.
Example(how to read a binary file):
try{
byte[] buffer = new byte[100];
FileInputStream inputStream = new FileInputStream(fileName);
/* read fills buffer with data and returns the number of bytes read(which may be less that the
buffer size but it will never be more! */
int total = 0;
int nRead = 0;
while((nRead = inputStream.read(buffer))!=-1) {
System.out.println(new String(buffer)); total +=nRead;
}
Writing text files
To write a text file in Java, use FileWriter instead of fileReader and BufferedWriter instead of
BufferedInputReader.
Example:
try{
FileWriter fileWriter = new FileWriter(fileName);
BufferedWriter bOW= new BufferedWriter(fileWriter);
// write() does not automatically append a newline character
bOW.write(HI BRO);
} catch().
Writing binary files
Almost same as reading, except we use fileOutputStream
// write() writes as many bytes from the buffer
// as the length of the buffer. You can also
// use
// write(buffer, offset, length)
// if you want to write a specific number of
// bytes, or only part of the buffer.
outputStream.write(buffer)