Java2024/src/chapter7/FileOperationHomework.java
2024-12-11 14:09:38 +08:00

51 lines
1.6 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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());
}
}
}