How to use I/O streams in Java to read and write files?
In Java, reading and writing files using IO streams mainly involves the following classes and interfaces:
- FileInputStream and FileOutputStream are used to read and write files as streams of bytes, operating on a byte-by-byte basis.
- FileReader and FileWriter: used for reading and writing files in character streams, reading and writing is done on a character-by-character basis.
- BufferedReader and BufferedWriter: used to provide a buffering mechanism that can enhance reading and writing efficiency.
- InputStreamReader and OutputStreamWriter: used to convert byte streams into character streams for reading and writing character streams.
Here are some common examples of code for reading and writing files:
- Reading and writing byte streams in files using FileInputStream and FileOutputStream.
import java.io.*;
public class FileIOExample {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("input.txt");
FileOutputStream fos = new FileOutputStream("output.txt");
int data;
while ((data = fis.read()) != -1) {
fos.write(data);
}
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
- Read and write character streams files using FileReader and FileWriter.
import java.io.*;
public class FileIOExample {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("input.txt");
FileWriter fw = new FileWriter("output.txt");
int data;
while ((data = fr.read()) != -1) {
fw.write(data);
}
fr.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
- Read and write files using BufferedReader and BufferedWriter.
import java.io.*;
public class FileIOExample {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine(); // 写入换行符
}
br.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
These sample codes only cover basic read and write file operations, additional steps such as handling exceptions and closing streams may be needed when using them.