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();
}
}
}
這些示例代碼只是基本的讀寫文件操作,具體使用時可能還需要處理異常、關閉流等。