Java中讀取和寫入文件的方法有很多,以下是其中幾種常用的方法:
示例代碼:
// 讀取文件
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();
}
示例代碼:
// 讀取文件
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();
}
示例代碼:
// 讀取文件
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();
}
以上是幾種常用的文件讀取和寫入的方法,根據具體的需求選擇合適的方法來操作文件。