繁体   English   中英

将文本文件分成两个文件(java)

[英]Splitting up a text file into two files (java)

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

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

...

stand 345

stand 498

stare 894

...

我想做的是读入此文件,然后编写两个单独的文件。 一个文件应仅包含该单词的一个实例,而另一个应在文档中包含该单词的位置。 该文件确实很大,我想知道是否可以在创建文件之前使用数组或列表存储单词和索引,或者是否有更好的方法。 我真的不知道该怎么想。

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

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
}

您可以使用它来保存单词和索引。 您只需要为文件的每一行调用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.
    }
}

如果文件确实很长,则应考虑使用数据库。 如果文件不是太大,则可以使用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") ;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM