Java中使用IO流读写文件主要涉及到以下几个类和接口:
下面是一些常用的读写文件的示例代码:
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();
}
}
}
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();
}
}
}
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();
}
}
}
这些示例代码只是基本的读写文件操作,具体使用时可能还需要处理异常、关闭流等。