题目:将java源代码的次行块风格转换为行尾块风格
如下图示:
import java.util.*;
import java.io.*;
public class Exercise12_12 {
public static void main(String[] args) throws Exception {
//判断命令行参数是否只有一个
if (args.length != 1) {
System.out.println(
"Usage: java Exercise12_12 filename");
System.exit(1);
//0正常退出,非0异常退出
}
//检查源文件是否存在
File sourceFile = new File(args[0]);
if (!sourceFile.exists()) {
System.out.println("Source file " + args[0] + " not exist");
System.exit(2);
}
//StringBuilder:生成一个字符序列可变的字符串
StringBuilder buffer = new StringBuilder();
Scanner input = new Scanner(sourceFile);
//boolean hasNext():判断是否还有元素可以遍历。
while (input.hasNext()) {
String s = input.nextLine();
//去掉字符串左右的空格
String s1 = s.trim();
//如果第一个字符就是'{',则添加到buffer中
//注意:需考虑原代码中是否有空行的情况(否则charAt(0)可能越界)
if (s1.length()> 0 && s1.charAt(0) == '{') {
buffer.append(" {");
//'{'后面还有字符:换行并将s拼接上,把'{'换为空格
if (s1.length() > 1)
buffer.append("\r\n" + s.replace('{', ' '));
}
else
buffer.append("\r\n" + s);
}
input.close();
// 把buffer写到文件中
PrintWriter output = new PrintWriter(sourceFile);
//把buffer转换为String对象
output.print(buffer.toString());
output.close();
}
}