共計 1350 個字符,預(yù)計需要花費 4 分鐘才能閱讀完成。
Java 中讀取和寫入文件的方法有很多,以下是其中幾種常用的方法:
- 使用 File 類:可以使用 File 類來創(chuàng)建、刪除、重命名文件,以及檢查文件是否存在等操作??梢酝ㄟ^ FileInputStream 和 FileOutputStream 來讀取和寫入文件內(nèi)容。
示例代碼:
// 讀取文件
File file = new File("path/to/file.txt");
try (FileInputStream fis = new FileInputStream(file)) {int content;
while ((content = fis.read()) != -1) {System.out.print((char) content);
}
} catch (IOException e) {e.printStackTrace();
}
// 寫入文件
try (FileOutputStream fos = new FileOutputStream(file)) {String content = "Hello, World!";
fos.write(content.getBytes());
} catch (IOException e) {e.printStackTrace();
}
- 使用 BufferedReader 和 BufferedWriter 類:這兩個類提供了帶緩沖區(qū)的讀取和寫入文件內(nèi)容的方法,可以提高讀寫效率。
示例代碼:
// 讀取文件
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {System.out.println(line);
}
} catch (IOException e) {e.printStackTrace();
}
// 寫入文件
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {String content = "Hello, World!";
bw.write(content);
} catch (IOException e) {e.printStackTrace();
}
- 使用 Scanner 類:Scanner 類可以用來讀取文件中的各種類型的數(shù)據(jù),如整數(shù)、浮點數(shù)、字符串等。
示例代碼:
// 讀取文件
try (Scanner scanner = new Scanner(file)) {while (scanner.hasNextLine()) {String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {e.printStackTrace();
}
// 寫入文件
try (PrintWriter writer = new PrintWriter(file)) {String content = "Hello, World!";
writer.println(content);
} catch (FileNotFoundException e) {e.printStackTrace();
}
以上是幾種常用的文件讀取和寫入的方法,根據(jù)具體的需求選擇合適的方法來操作文件。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完