package exercise_9;
import java.util.*;
import java.io.*;
public class Exercise9_16 {
/**Main method*/
public static void main(String[] args) throws Exception {
// Check command line parameter usage
if (args.length != 1) //判断输入的参数是否是一个, 如果不是,则打印下面信息
System.out.println(
"Usage: java Exercise9_16 filename");
System.exit(0); //然后退出程序
}
// Check if source file exists
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();//一行行输入 //把文件内容读入 s 字符串中
String s1 = s.trim();//把多出来的空格都删掉 //把s字符串中的空格去掉
System.out.println(s1); // 打印s1
if (s1.charAt(0) == '{') { // 判断字符串s1中第一个字符是否为‘{’
buffer.append(" {"); // 如果是 ,则向字符串容器中添加 ‘{’
if (s1.length() > 1) buffer.append("\r\n" + s.replace('{', ' ')); // 如果s1的长度大于1, 则向字符串容器中添加换行及下行首位置,把s里‘ 用‘{换
}
else
buffer.append("\r\n" + s); // 否则buffer字符串容器添加换行 及首位置, s字符串
}
// Write buffer into the file
PrintWriter output = new PrintWriter(sourceFile); // 输出流 把先前的文件 连接一条管道 即输出流
output.print(buffer.toString()); // 输出buffer容器里的字符
output.close();
}
}
希望对你有帮助 ,谢谢