java—接收txt文件以读取和存储它们的构造函数

ybzsozfc  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(323)

首先我已经有了这个代码:

  1. public class TextTest {
  2. public static void main(String[] args) {
  3. try {
  4. List<Text> v = new ArrayList<Text>();
  5. v.add(new Text(args[0]));
  6. v.add(new Text(args[1]));
  7. v.add(new Text(args[2]));
  8. System.out.println(v);
  9. Collections.sort(v);
  10. System.out.println(v);
  11. }
  12. catch ( ArrayIndexOutOfBoundsException e) {
  13. System.err.println("Enter three files for comparation");
  14. }
  15. }

我需要创建一个名为 Text 包含打开和读取txt文件的代码。但是,如何构建构造函数来接收包含3个txt文件的目录,同时创建并读取这些文件?文件将存储在此处:

  1. v.add(new Text(args[0]));
  2. v.add(new Text(args[1]));
  3. v.add(new Text(args[2]));
s71maibg

s71maibg1#

假设你有3个文本文件 text1.txt , text2.txt ,和 text3.txt 包括以下内容:
文本1.txt:

  1. A B C D E F G H I J

文本2.txt:

  1. A B C D E F G H I J K L M N O

文本3.txt:

  1. A B C D E F G H I J K L

你可以让 Text 实施 Comparable<Text> :

  1. import java.io.BufferedReader;
  2. import java.io.File;
  3. import java.io.FileReader;
  4. import java.io.IOException;
  5. public class Text implements Comparable<Text> {
  6. private final String fileName;
  7. private String fileData;
  8. private int wordCount;
  9. public Text(String filePath) {
  10. File file = new File(filePath);
  11. this.fileName = file.getName();
  12. try {
  13. BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
  14. StringBuilder sb = new StringBuilder();
  15. String line = bufferedReader.readLine();
  16. int wordCount = 0;
  17. while (line != null) {
  18. wordCount += line.split(" ").length;
  19. sb.append(line);
  20. sb.append(System.lineSeparator());
  21. line = bufferedReader.readLine();
  22. }
  23. this.fileData = sb.toString().strip();
  24. this.wordCount = wordCount;
  25. } catch (IOException e) {
  26. e.printStackTrace();
  27. }
  28. }
  29. public String getFileData() {
  30. return this.fileData;
  31. }
  32. @Override
  33. public String toString() {
  34. return String.format("%s [%d]", this.fileName, this.wordCount);
  35. }
  36. @Override
  37. public int compareTo(Text t) {
  38. if (this.wordCount == t.wordCount) {
  39. return this.fileData.compareTo(t.getFileData());
  40. }
  41. return this.wordCount - t.wordCount;
  42. }
  43. }

用法示例:

  1. $ javac TestText.java Test.java
  2. $ java TextText text1.txt text2.txt text3.txt
  3. [text1.txt [10], text2.txt [15], text3.txt [12]]
  4. [text1.txt [10], text3.txt [12], text2.txt [15]]
展开查看全部

相关问题