重新格式化java源代码,将java的次行块风格转变为行尾块风格
如:
{
**{};
****;
}
转变为:
**{
***{};
*************8;
}
注意此处代码的前提条件是输入符合次行块风格的要求,对于异常情况的处理还需要添加代码:
比如:
**
{*
}
这种情况需要再做出考虑。(其实只要对下面的tem1的charAt(0)再讨论就行了。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
//将java次行块风格转变为行尾风格
public class Change_style {
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
//File filesource=new File(args[0]);
File filesource=new File("d:/test2.txt");
Scanner input=new Scanner(filesource);
StringBuffer temp=new StringBuffer();
while(input.hasNext())
{
String tem=input.nextLine();
String tem1=tem.trim();
if(tem1.equals("{"))
temp.insert(temp.length()-2,"{");
else {
temp.append(tem+"\r\n");
}
}
System.out.print(temp.toString());
PrintWriter output=new PrintWriter(filesource);
output.print(temp);
input.close();
output.close();
}
}
注意这个地方scanner的.nextline()方法与next方法的区别,next() 方法遇见第一个有效字符(非空格,非换行符)时,开始扫描,当遇见第一个分隔符或结束符(空格或换行符)时,结束扫描,获取扫描到的内容,即获得第一个扫描到的不含空格、换行符的单个字符串。
使用nextLine()时,则可以扫描到一行内容并作为一个字符串而被获取到(space之前的,包括前面的空格)。而字符串用trim方法可以将字符串前后的空格消除。