Warm tip: This article is reproduced from serverfault.com, please click

java-接收TXT文件以读取和存储它们的构造方法

(java - Constructor that receives TXT files to read and store them)

发布于 2020-11-28 01:14:36

首先,我已经有了以下代码:

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]));
Questioner
Luciano Balestrin Correa
Viewed
23
Sash Sinha 2020-11-28 11:48:52

假设你有3个文本文件text1.txttext2.txttext3.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]]