首先,我已经有了以下代码:
public class TextTest {
public static void main(String[] args) {
try {
List<Text> v = new ArrayList<Text>();
v.add(new Text(args[0]));
v.add(new Text(args[1]));
v.add(new Text(args[2]));
System.out.println(v);
Collections.sort(v);
System.out.println(v);
}
catch ( ArrayIndexOutOfBoundsException e) {
System.err.println("Enter three files for comparation");
}
}
我需要创建一个名为的类,Text
其中包含将打开并读取TXT文件的代码。但是,如何构建构造函数以接收包含3个TXT文件的目录,同时创建档案并读取它们?这些文件将存储在这里:
v.add(new Text(args[0]));
v.add(new Text(args[1]));
v.add(new Text(args[2]));
假设你有3个文本文件text1.txt
,text2.txt
和text3.txt
包含以下内容:
text1.txt:
A B C D E F G H I J
text2.txt:
A B C D E F G H I J K L M N O
text3.txt:
A B C D E F G H I J K L
你可以制作Text
工具Comparable<Text>
:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Text implements Comparable<Text> {
private final String fileName;
private String fileData;
private int wordCount;
public Text(String filePath) {
File file = new File(filePath);
this.fileName = file.getName();
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
StringBuilder sb = new StringBuilder();
String line = bufferedReader.readLine();
int wordCount = 0;
while (line != null) {
wordCount += line.split(" ").length;
sb.append(line);
sb.append(System.lineSeparator());
line = bufferedReader.readLine();
}
this.fileData = sb.toString().strip();
this.wordCount = wordCount;
} catch (IOException e) {
e.printStackTrace();
}
}
public String getFileData() {
return this.fileData;
}
@Override
public String toString() {
return String.format("%s [%d]", this.fileName, this.wordCount);
}
@Override
public int compareTo(Text t) {
if (this.wordCount == t.wordCount) {
return this.fileData.compareTo(t.getFileData());
}
return this.wordCount - t.wordCount;
}
}
用法示例:
$ javac TestText.java Test.java
$ java TextText text1.txt text2.txt text3.txt
[text1.txt [10], text2.txt [15], text3.txt [12]]
[text1.txt [10], text3.txt [12], text2.txt [15]]
真的谢谢您,澄清了我所有的疑问!但是,还有一个问题,我该如何仅打印插入了档案内容的档案名称?
因此,您希望列表包含文件名吗?但是仍然对内容进行排序吗?
@LucianoBalestrinCorrea添加了基于单词数的排序,如果单词数相等,则按文件内容排序:)同样,仅供参考,您将获得接受答案的分数。
哦,再次感谢!!我设法做到了,有点困难,但是我做到了。我是Java的初学者:)
更新的答案。祝你好运!