如果您的文件中每行都有单词或术语,则可能需要对其进行排序。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的资料与面试题,如果你在技术上面想提升自己的话,可以关注我,私信发送领取资料或者在评论区留下自己的联系方式,有时间记得帮我点下转发让跟多的人看到哦。