첫째로 이미이 코드가 있습니다.
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]]
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다