java 行 写文件_java实现以某种格式按行读取写入文件

(1) 之前习惯性不考虑文件格式,一般都用简单的FileReader和BufferedReader标配,代码如下:

FileReader fr=new FileReader("D://haha.txt");

BufferedReader br=new BufferedReader(fr);

String line=null;

while((line=br.readLine())!=null){

一系列操作balabala~~;

}

br.close();

fr.close();

(2)后来遇到很多时候需要按照一定的格式进行文件的读写操作,修改后代码如下:

File f=new File("D://haha.txt');

FileInputStream in;

in = new FileInputStream(f);

BufferedReader br=new BufferedReader(new InputStreamReader(in,"UTF-8"));

String line=null;

Maptc=new HashMap();

while((line=br.readLine())!=null){

String elem[]=line.split("");

String data[]=elem[9].split("-");

for(int i=1;i

if(tc.containsKey(data[i])){

tc.put(data[i], tc.get(data[i])+1);

}else{

tc.put(data[i], 1);

}

}

}

br.close();

in.close();

//排序

ArrayList>list=new ArrayList>(tc.entrySet());

Collections.sort(list, new Comparator>(){

public int compare(Entryo1,Entryo2){

int v1=o1.getValue().intValue();

int v2=o2.getValue().intValue();

return v2-v1; //降序排列

}

});

//写入

File f2=new File("D://sortedTags.txt");

FileOutputStream out=new FileOutputStream(f2);

BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(out,"UTF-8"));

for(Entry e:list){

bw.write(e.getKey()+"\t"+e.getValue()+"\n");

}

bw.close();

out.close();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值