簡體   English   中英

逐行將字符串寫入文本文件時避免重復

[英]Avoid repetition when writing strings to text file line by line

我使用以下代碼將字符串寫入我的簡單文本文件:

編輯:

private String fileLocation="/mnt/sdcard/out.txt";

public void saveHisToFile()
{
    if (prefs.getBoolean("saveHis", true) && mWordHis != null && mWordHis.size() >= 1)
    {
        StringBuilder sbHis = new StringBuilder();          
        Set<String> wordSet= new HashSet<String>(mWordHis);
        for (String item : wordSet)
        {
            sbHis.append(item);
            sbHis.append("\n");
        }

        String strHis = sbHis.substring(0, sbHis.length()-1);  
        try {
             BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
                     fileLocation), true));
             bw.write(strHis);
             bw.newLine();
             bw.close();
        } catch (IOException e) {

        }
    }
}

這些字符串已成功寫入文本文件,但是很奇怪,某些字符串被覆蓋,例如:

apple
orange
grapes
grapes
grapes
apple 
kiwi

我的問題是:

  1. 如何停止多次寫入字符串?
  2. 如果文件中已經存在一個字符串(行),我該如何停止呢?

我已經咨詢了這篇文章,但未能將其應用於我的案例。 你能幫一點忙嗎? 非常感謝。

嘗試這個:

public void saveHisToFile(Set<String> existingWords)
{
    if (prefs.getBoolean("saveHis", true) && mWordHis != null && mWordHis.size() >= 1)
    {
        StringBuilder sbHis = new StringBuilder();
        for (String item : mWordHis)
        {
            if (!existingWords.contains(item)) {
                sbHis.append(item);
                sbHis.append("\n");
            }
        }

        String strHis = sbHis.substring(0, sbHis.length()-1);
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
                    fileLocation), true));
            bw.write(strHis);
            bw.newLine();
            bw.close();
        } catch (IOException e) {

        }
    }
}

我猜mWordHis是一個List ,可以包含重復的條目。 您可以先將其轉換為Set (不允許重復),然后僅打印Set的單詞。

    Set<String> wordSet= new HashSet<>(mWordHis);

    for (String item : wordSet)
    {
        sbHis.append(item);
        sbHis.append("\n");
    }

正如@fge所評論的,如果插入順序很重要,也可以使用LinkedHashSet

如果您需要對同一文件多次運行同一代碼,則必須將已經寫入該文件的所有記錄保存在內存中,或者在寫入文件之前先讀取並獲取所有數據。

編輯:

我只能考慮修剪單詞,因為有些單詞可能包含不需要的空格:

    Set<String> wordSet= new HashSet<>();
    for (String item : mWordHis){
        wordSet.add(item.trim());
    }

您可以將所有字符串添加到HashMap中,並檢查每個新字符串是否已經在其中。

例:

    HashMap<String,String> test = new HashMap<String,String>();
    if(!test.containsKey(item)) {
      test.put(item,"");
      // your processing: example
      System.out.println(item);
    } else {
      // Your processing of duplicates, example:
      System.out.println("Found duplicate of: " + item);
    }

編輯:或使用其他解決方案所示的HashSet ...

    HashSet<String> test = new HashSet<String>();
    if(!test.contains(item)) {
      test.add(item);
      // your processing: example
      System.out.println(item);
    } else {
      // Your processing of duplicates, example:
      System.out.println("Found duplicate of: " + item);
    }

編輯2:

    private String fileLocation="/mnt/sdcard/out.txt";

    public void saveHisToFile()
    {
        if (prefs.getBoolean("saveHis", true) && mWordHis != null && mWordHis.size() >= 1)
        {
            StringBuilder sbHis = new StringBuilder();  
            HashSet<String> test = new HashSet<String>();

            Set<String> wordSet= new HashSet<String>(mWordHis);
            for (String item : wordSet)
            {
                if(!test.contains(item)) {
                    test.add(item);
                    // your processing: example
                    sbHis.append(item+System.lineSeparator());
                } else {
                    // Your processing of duplicates, example:
                    //System.out.println("Found duplicate of: " + item);
                }
            }

            String strHis = sbHis.toString();  
            try {
                 BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
                         fileLocation), true));
                 bw.write(strHis);
                 bw.newLine();
                 bw.close();
            } catch (IOException e) {

            }
        }
    }

這是有關如何解決問題的完整示例:

      import java.io.BufferedReader;
      import java.io.BufferedWriter;
      import java.io.File;
      import java.io.FileReader;
      import java.io.FileWriter;
      import java.io.IOException;
      import java.util.HashSet;

      public class HisSaver {
        private HashSet<String> uniqueTester = new HashSet<String>();

        private String fileLocation="/mnt/sdcard/out.txt";

        private static HisSaver instance = null;


        private HisSaver() {
            readWordsFromFile();
        }

        public static HisSaver getInstance() {
            if(instance == null)
                instance = new HisSaver();
            return instance;
        }

        public void saveWord(String word) {
            if(!uniqueTester.contains(word)) {
                uniqueTester.add(word);
                writeWordToFile(word);
            }
        }

        private void writeWordToFile(String word) {
          try {
               BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
                       fileLocation), true));
               bw.write(word);
               bw.newLine();
               bw.close();
          } catch (IOException e) {

          }
        }

        private void readWordsFromFile() {
          try {
            BufferedReader br = new BufferedReader(new FileReader(new File(
                fileLocation)));
            String line;
            while((line = br.readLine()) != null) {
                if(!uniqueTester.contains(line)) {
                    uniqueTester.add(line);
                }
            }
          } catch (IOException e) {

          }
        }
      }

現在使用它,您只需在代碼中執行以下操作:

    HisSaver hs = HisSaver.getInstance();
    hs.saveWord("newWord");

當且僅當文件中還沒有“ newWord”時,這將插入“ newWord”,前提是您的代碼中沒有其他函數可以訪問該文件。 請注意:此解決方案不是線程安全的!!!

編輯:代碼做什么的解釋:我們創建一個類HisSaver,它是一個單例。 這是通過將其構造函數設為私有並提供靜態方法getInstance()來返回已初始化的HisSaver來實現的。 該HisSaver將已經包含文件中所有先前存在的單詞,因此只能在其中附加新單詞。 從另一個類中調用getInstance()方法將為您提供此單例的句柄,並允許您調用saveWord而不必擔心手中是否有正確的對象,因為只能實例化該對象的一個​​實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM