java按行读取txt文件内容_对txt文件中的内容进行排序

4ddc3fe32e277cca7f48d90f335f35e8.png

如果您的文件中每行都有单词或术语,则可能需要对其进行排序。Java Arrays.sort是执行此操作的常用功能。Collections.sort()是另一个不错的说法。这是一个示例和代码。
在文件EG中,您具有以下txt。

dog

cat

--windows

--kankan

pps

game

--annot be guaranteed

as it is, generally speaking,

--impossible to make any hard gu

arantees in the p

--resence of unsynchr

这是对行进行排序的代码,不包括以“-”开头的行。

import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;

public class SortFileContent {

public static void sortObserve() throws IOException {

File fin = new File("c:input.txt");

File fout = new File("c:sorted.txt");

FileInputStream fis = new FileInputStream(fin);

FileOutputStream fos = new FileOutputStream(fout);

BufferedReader in = new BufferedReader(new InputStreamReader(fis));

BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));

String aLine;

ArrayList<String> al = new ArrayList<String> ();

int i = 0;

while ((aLine = in.readLine()) != null) {

//get the lines you want, here I don't want something starting with - or empty

if (!aLine.trim().startsWith("-") && aLine.trim().length() > 0) {

al.add(aLine);

i++;

}

}

Collections.sort(al);

//output sorted content to a file

for (String s : al) {

System.out.println(s);

out.write(s);

out.newLine();

out.write("-----------------------------------------");

out.newLine();

}

in.close();

out.close();

}}

最后,您在sorted.txt文件中获得以下内容。

arantees in the p

-----------------------------------------

as it is, generally speaking,

-----------------------------------------

cat

-----------------------------------------

dog

-----------------------------------------

game

-----------------------------------------

pps

-----------------------------------------

最后,开发这么多年我也总结了一套学习Java的资料与面试题,如果你在技术上面想提升自己的话,可以关注我,私信发送领取资料或者在评论区留下自己的联系方式,有时间记得帮我点下转发让跟多的人看到哦。

c07ae8f1ba249328281fadf4d3f75e78.png

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值