读写文件文件

This commit is contained in:
seahi 2024-12-11 14:09:38 +08:00
parent fdaf7334c8
commit 4ba14576e7
5 changed files with 120 additions and 0 deletions

View File

@ -0,0 +1,19 @@
package chapter7;
import java.io.FileWriter;
import java.io.IOException;
public class Example08 {
public static void main(String[] args) {
// 使用try-with-resources自动关闭资源
try (FileWriter writer = new FileWriter("note.txt")) {
// 写入一些文本
writer.write("这是第一行\n"); // \n表示换行
writer.write("这是第二行\n");
System.out.println("文件写入成功!");
} catch (IOException e) {
System.out.println("写入文件出错:" + e.getMessage());
}
}
}

View File

@ -0,0 +1,28 @@
package chapter7;
import java.io.FileWriter;
import java.io.IOException;
public class Example09 {
public static void main(String[] args) {
FileWriter writer = null; // 在try外声明以便finally中可以访问
try {
writer = new FileWriter("note.txt");
writer.write("这是第一行\n");
writer.write("这是第二行\n");
System.out.println("文件写入成功!");
} catch (IOException e) {
System.out.println("写入文件出错:" + e.getMessage());
} finally {
// 在finally中确保关闭资源
if (writer != null) { // 防止writer未初始化就抛出异常
try {
writer.close(); // close()方法也可能抛出IOException
} catch (IOException e) {
System.out.println("关闭文件出错:" + e.getMessage());
}
}
}
}
}

View File

@ -0,0 +1,23 @@
package chapter7;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Example10 {
public static void main(String[] args) {
// 使用try-with-resources自动关闭资源
try (BufferedReader reader = new BufferedReader(
new FileReader("note.txt"))) {
String line;
// 逐行读取文件内容
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("读取文件出错:" + e.getMessage());
}
}
}

View File

@ -0,0 +1,50 @@
package chapter7;
import java.io.*;
import java.util.Scanner;
public class FileOperationHomework {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 1. 获取文件名
System.out.print("请输入文件名:");
String fileName = scanner.nextLine();
// 2. 获取要写入的行数
System.out.print("请输入要写入的行数:");
int lines = scanner.nextInt();
scanner.nextLine(); // 消除换行符
// 3. 写入文件
try (FileWriter writer = new FileWriter(fileName)) {
// 循环获取用户输入并写入
for (int i = 1; i <= lines; i++) {
System.out.print("请输入第" + i + "行内容:");
String content = scanner.nextLine();
writer.write(content + "\n");
}
System.out.println("文件写入成功!");
} catch (IOException e) {
System.out.println("写入文件出错:" + e.getMessage());
return; // 如果写入出错直接返回
}
// 4. 读取并显示文件内容
System.out.println("\n文件内容如下");
System.out.println("--------------------");
try (BufferedReader reader = new BufferedReader(
new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
System.out.println("--------------------");
} catch (IOException e) {
System.out.println("读取文件出错:" + e.getMessage());
}
}
}

0
test.txt Normal file
View File