在Java中,可以使用File類和FileInputStream、FileOutputStream、BufferedReader、BufferedWriter等類來讀寫文件。
讀取文件的步驟如下:
示例代碼如下:
File file = new File("file.txt");
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
fis.close();
寫入文件的步驟如下:
示例代碼如下:
File file = new File("output.txt");
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write("Hello, world!");
bw.newLine();
bw.write("This is a test!");
bw.flush();
bw.close();
fos.close();