JNJHJ
JNJHJ
One this page you can find a simple guide to reading and writing files in the Java
programming language. The code examples here give you everything you need to read
and write files right away, and if you’re in a hurry, you can use them without needing to
understanding in detail how they work.
File handling in Java is frankly a bit of a pig’s ear, but it’s not too complicated once you
understand a few basic ideas. The key things to remember are as follows.
FileReader for text files in your system’s default encoding (for example, files
containing Western European characters on a Western European computer).
FileInputStream for binary files and text files that contain ‘weird’ characters.
FileReader (for text files) should usually be wrapped in aBufferedFileReader. This
saves up data so you can deal with it a line at a time or whatever instead of character by
character (which usually isn’t much use).
If you want to write files, basically all the same stuff applies, except you’ll deal with
classes named FileWriter with BufferedFileWriter for text files,
orFileOutputStream for binary files.
import java.io.*;
public class Test {
try {
FileReader fileReader =
new FileReader(fileName);
BufferedReader bufferedReader =
new BufferedReader(fileReader);
System.out.println(line);
bufferedReader.close();
catch(FileNotFoundException ex) {
System.out.println(
fileName + "'");
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// ex.printStackTrace();
import java.io.*;
try {
FileInputStream inputStream =
new FileInputStream(fileName);
int total = 0;
int nRead = 0;
while((nRead = inputStream.read(buffer)) != -1) {
System.out.println(new String(buffer));
total += nRead;
inputStream.close();
catch(FileNotFoundException ex) {
System.out.println(
catch(IOException ex) {
System.out.println(
+ fileName + "'");
// ex.printStackTrace();
import java.io.*;
public class Test {
try {
FileWriter fileWriter =
new FileWriter(fileName);
BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);
bufferedWriter.write("Hello there,");
bufferedWriter.newLine();
bufferedWriter.close();
catch(IOException ex) {
System.out.println(
+ fileName + "'");
// ex.printStackTrace();
}
The output file now looks like this (after running the program):