java中如何读写文件
时间: 2024-02-27 17:58:52 浏览: 16
Java中可以使用Java IO库来读写文件。下面是一些基本的读写文件的示例代码:
读取文件:
```java
try {
File file = new File("file.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
```
写入文件:
```java
try {
FileWriter writer = new FileWriter("file.txt");
writer.write("Hello World!\n");
writer.write("How are you?");
writer.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
```
当然,还有其他的读写文件的方式,比如使用BufferedReader和BufferedWriter等。需要根据实际情况选择最合适的方法。