如果您的文件中每行都有单词或术语,则可能需要对其进行排序。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) {
///得到你想要的线条,在这里我不想要的东西开始-或者清空
if (!aLine.trim().startsWith("-") && aLine.trim().length() > 0) {
al.add(aLine);
i++;
}
}
Collections.sort(al);
//将排序后的内容输出到文件中,
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
-----------------------------------------