Java 文本文件的读写

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"); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值