題一:寫入 1-100 到 a.txt
package demo1;
import java.io.*;
public class Question1 {
public static void main(String[] args) {
try (FileWriter fw = new FileWriter("./src/a.txt")) {
for (int i = 1; i <= 100; i++) {
fw.write(i + "\r\n"); // 每行一個數字,便於讀取
}
System.out.println("寫入文件成功");
} catch (IOException e) {
e.printStackTrace();
}
}
}
題二:讀取 a.txt,計算平方與平方根寫入 b.txt
package demo1;
import java.io.*;
public class Question2 {
public static void main(String[] args) {
try (FileWriter fw = new FileWriter("./src/b.txt");
BufferedReader br = new BufferedReader(new FileReader("./src/a.txt"))) {
String line;
System.out.println("讀取文件內容如下:");
while ((line = br.readLine()) != null) {
System.out.println(line);
int val = Integer.parseInt(line.trim());
fw.write(val * val + "\t" + Math.sqrt(val) + "\r\n");
}
System.out.println("寫入文件成功");
} catch (IOException e) {
e.printStackTrace();
}
}
}
關鍵修正點
- 題一:每行一個數字 (
\r\n),方便題二按行讀取解析。
- 題二:使用
BufferedReader.readLine() 按行讀取,Integer.parseInt 轉換,直接使用讀取的數據計算,**不可重新循環 1-100**。
- 資源管理:try-with-resources 自動關閉流,異常安全。
- 編碼:生產環境指定
StandardCharsets.UTF_8。
常見錯誤對比