import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
*
* <b>Application name:</b><br>
* <b>Application describing:</b> 文本文件的读写<br>
*/
public class TextFileRead
{
/**
*
* {文件读取}
*
* @param srcFilePath
*/
public static List<FileContent> readFile(String srcFilePath)
{
BufferedReader br = null;//按行读取文本文件
List<FileContent> list = new ArrayList<FileContent>();
try
{
br = new BufferedReader(new FileReader(srcFilePath));
String line;
FileContent fileContent;
while ((line = br.readLine()) != null)
{
fileContent = new FileContent();
fileContent.setContent(line);//设置content
list.add(fileContent);
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
System.out.println("文件不存在");
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
System.out.println("读取文件失败");
e.printStackTrace();
}finally{
if(br!=null){
try
{
br.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return list;
}
/**
*
* {分配行号}
*
* @param list
*/
public static void giveRowNumber(List<FileContent> list)
{
if (list != null & !list.isEmpty())
{
for(int i=0,n=list.size();i<n;i++){
FileContent fileContent = list.get(i);
fileContent.setId(i+1);
}
}
}
/**
*
* {输出文本文件}
*
* @param list
* @param dstFilePath
*/
public static void writeFile(List<FileContent> list, String dstFilePath)
{
BufferedWriter bw = null;
try
{
bw = new BufferedWriter(new FileWriter(dstFilePath));
if(list!=null&&!list.isEmpty()){
for(FileContent fileContent :list){
bw.write(fileContent.getId()+" "+fileContent.getContent());
bw.newLine();//换行
}
bw.flush();
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(bw!=null){
try
{
bw.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
*
* {主函数}
*
* @param args
*/
public static void main(String[] args)
{
List<FileContent>list = readFile("c:"+File.separator+"source.txt");
giveRowNumber(list);
writeFile(list, "d:"+File.separator+"source.txt");
}
}