将文本文件拆分为两个文件(java)

时间:2016-09-11 09:01:45

标签: java algorithm

我需要一些帮助来弄清楚如何将文本文件拆分为java中的两个文件。

我有一个文本文件,其中每一行按字母顺序包含一个空格及其索引,即

...

stand 345

stand 498

stare 894

...

我想要做的是读取此文件,然后写两个单独的文件。一个文件应仅包含该单词的一个实例,另一个文件应包含文档中单词的位置。 该文件非常大,我想知道在创建文件之前是否可以使用数组或列表来存储单词和索引,或者是否有更好的方法。 我真的不知道如何思考。

3 个答案:

答案 0 :(得分:2)

我建议您使用单词as key和索引列表作为值创建HashMap,例如 HashMap< String,ArrayList<字符串>> 。这样,您可以轻松检查已经放在地图中的单词,并更新其索引列表。

List<String> list = map.get(word);
if (list == null)
{
    list = new ArrayList<String>();
    map.put(word, list);
}
list.add(index);

在读取并存储所有值之后,您只需要遍历地图并将其密钥写入一个文件,将值写入另一个文件中。

for (Map.Entry<String, Object> entry : map.entrySet()) {
  String key = entry.getKey();
  ArrayList value = (ArrayList) entry.getValue();
  // writing code here
}

答案 1 :(得分:1)

您可以使用它来保存单词和索引。您只需要为文件的每一行调用addLine

Map<String, Set<Integer>> entries = new LinkedHashMap<>();

public void addLine(String word, Integer index) {
    Set<Integer> indicesOfWord = entries.get(word);

    if (indicesOfWord == null) {
        entries.put(word, indicesOfWord = new TreeSet<>());
    }

    indicesOfWord.add(index);
}

要将它们存储在单独的文件中,您可以使用此方法:

public void storeInSeparateFiles(){
    for (Entry<String, Set<Integer>> entry : entries.entrySet()) {
        String word = entry.getKey();
        Set<Integer> indices = entry.getValue();

        // TODO: Save in separate files.
    }
}

答案 2 :(得分:1)

如果您的文件很长,那么您应该考虑使用数据库。如果您的文件不是太大,那么您可以使用HashMap。您也可以使用这样的类,它要求对文件进行排序,并将单词写入一个文件,将索引写入另一个文件中:

public class Split {
private String fileName;
private PrintWriter fileWords;
private PrintWriter fileIndices;

public Split(String fname) {
    fileName = fname;
    if (initFiles()) {
        writeList();
    }
    closeFiles();
}

private boolean initFiles() {
    boolean retval = false;
    try {
        fileWords = new PrintWriter("words-" + fileName, "UTF-8");
        fileIndices = new PrintWriter("indices-" + fileName, "UTF-8");
        retval = true;
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
    return retval;
}

private void closeFiles() {
    if (null != fileWords) {
        fileWords.close();
    }
    if (null != fileIndices) {
        fileIndices.close();
    }
}

private void writeList() {
    String lastWord = null;
    List<String> wordIndices = new ArrayList<String>();
    Path file = Paths.get(fileName);
    Charset charset = Charset.forName("UTF-8");
    try (BufferedReader reader = Files.newBufferedReader(file, charset)) {
        String line = null;
        while ((line = reader.readLine()) != null) {
            int len = line.length();
            if (len > 0) {
                int ind = line.indexOf(' ');
                if (ind > 0 && ind < (len - 1)) {
                    String word = line.substring(0, ind);
                    String indice = line.substring(ind + 1, len);
                    if (!word.equals(lastWord)) {
                        if (null != lastWord) {
                            writeToFiles(lastWord, wordIndices);
                        }
                        lastWord = word;
                        wordIndices = new ArrayList<String>();
                        wordIndices.add(indice);
                    } else {
                        wordIndices.add(indice);
                    }
                }
            }
        }
        if (null != lastWord) {
            writeToFiles(lastWord, wordIndices);                    
        }
    } catch (IOException x) {
        System.err.format("IOException: %s%n", x);
    }
}

private void writeToFiles(String word, List<String> list) {

    boolean first = true;
    fileWords.println(word);
    for (String elem : list) {
        if (first) {
            first = false;
        }
        else {
            fileIndices.print(" ");
        }
        fileIndices.print(elem);

    }
    fileIndices.println();
}

}

请注意文件名处理不是很强大,您可以这样使用:

Split split = new Split("data.txt") ;