本文解析一個 Java 程序:讀取源文件,將每行開頭的 { 移至單獨一行並縮進,其餘行保持換行,最後覆蓋原文件。涉及 Scanner、StringBuilder、PrintWriter 等核心 IO 類。
輸入文件示例:
public void method() {
if (condition) {
doSomething();
}
}
處理後:
public void method()
{
if (condition)
{
doSomething();
}
}
if (args.length != 1) {
System.out.println("Usage: java Exercise9_16 filename");
System.exit(0);
}
要求命令行傳入一個文件路徑參數。
File sourceFile = new File(args[0]);
if (!sourceFile.exists()) {
System.out.println("Source file " + args[0] + " not exist");
System.exit(0);
}
StringBuilder buffer = new StringBuilder();
Scanner input = new Scanner(sourceFile);
while (input.hasNext()) {
String s = input.nextLine(); // 讀取一行(不含換行符)
String s1 = s.trim(); // 去除首尾空白
System.out.println(s1); // 控制台輸出處理後的行
if (s1.charAt(0) == '{') { // 若行首非空字符為 {
buffer.append(" {"); // 輸出空格+{
if (s1.length() > 1) {
// 原行除首字符外的內容換行輸出,並將 { 替換為空格
buffer.append("\r\n" + s.replace('{', ' '));
}
} else {
buffer.append("\r\n" + s); // 正常換行輸出原行
}
}
input.close();
關鍵邏輯:
trim() 去除縮進空格,判斷邏輯字符{ 時:輸出 {,若行有其他內容則換行並將 { 替換為空格\r\n 保證 Windows 風格換行
PrintWriter output = new PrintWriter(sourceFile);
output.print(buffer.toString());
output.close();
注意: 直接覆蓋源文件,建議生產環境先備份或寫入臨時文件再替換。
try (Scanner input = new Scanner(sourceFile, StandardCharsets.UTF_8);
PrintWriter output = new PrintWriter(sourceFile, StandardCharsets.UTF_8)) {
StringBuilder buffer = new StringBuilder();
while (input.hasNextLine()) {
String line = input.nextLine();
// ... 處理邏輯
}
output.print(buffer.toString());
}
new Scanner(sourceFile, "UTF-8")
new PrintWriter(sourceFile, "UTF-8")
File tempFile = File.createTempFile("fmt-", ".tmp", sourceFile.getParentFile());
try (PrintWriter out = new PrintWriter(tempFile, "UTF-8")) {
out.print(buffer.toString());
}
Files.move(tempFile.toPath(), sourceFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
| 類 | 用途 | 特點 |
|---|---|---|
Scanner | 文本掃描/解析 | 支持正則分隔符,nextLine() 讀整行 |
StringBuilder | 字符串構建 | 線程不安全,高性能,適用單線程拼接 |
PrintWriter | 格式化文本輸出 | 不拋 IOException,需 checkError() 檢查 |
Files | 現代文件操作 | NIO.2,支持原子移動、屬性讀取、流式處理 |
該程序演示了 Java 傳統 IO(java.io)讀取、處理、覆寫文件的完整流程。實際項目中建議:
Files/Paths)簡化代碼