写书的时候书中的代码之前需要加上行号,手工写起来比较麻烦,为了处理方便编写了一段代码进行处理。文件如下:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Scanner;
public class AddLineNumber {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("请输入原文件(完整路径,例如f://source.txt):");
String fileName = in.nextLine();
try{
AddLineNumber.addLineNumber(fileName);
System.out.println("已经处理完毕,文件为:"+fileName.substring(0,fileName.lastIndexOf("."))+"New"+fileName.substring(fileName.lastIndexOf(".")));
}catch(Exception e){
System.out.println(e.toString());
}
}
/*
* 为源文件添加行号
*/
public static void addLineNumber(String fileName) throws Exception{
File originalFile = new File(fileName);
Scanner in = new Scanner(new FileInputStream(originalFile));
File newFile = new File(fileName.substring(0,fileName.lastIndexOf("."))+"New"+fileName.substring(fileName.lastIndexOf(".")));
PrintWriter out = new PrintWriter(new FileOutputStream(newFile));
int index=1;
while(in.hasNextLine()){
String temp = in.nextLine();
out.println(index+"/t"+temp);
index++;
}
out.close();
in.close();
}
}
运行效果:
源文件内容:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("default");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(user);
em.getTransaction().commit();
添加行号之后的代码:
1 EntityManagerFactory emf = Persistence.createEntityManagerFactory("default");
2 EntityManager em = emf.createEntityManager();
3 em.getTransaction().begin();
4 em.persist(user);
5 em.getTransaction().commit();
没有添加注释,自己看看吧。
李绪成 CSDN Blog:http://blog.csdn.net/javaeeteacher
CSDN学生大本营:http://student.csdn.net/space.php?uid=124362
如果喜欢我的文章,就加我为好友:http://student.csdn.net/invite.php?u=124362&c=7be8ba2b6f3b6cc5