簡體   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