Re: [問題] 如不重覆便寫入一檔案?
※ 引述《ryan11 (我叫雷恩)》之銘言:
: 我從一個xml檔中定期抓取ip address
: (此xml檔會定期更新)
: 一次會抓200個,重覆非常多次
: 想要寫入另一個文字檔案中
: 且要此ip沒有重覆過再加入此檔案
: 要怎麼寫比較好呢?
: 我有想過在從原檔案抓的時候
: 就先存成array,然後比對沒重覆再加入這array
: 最後再寫入檔案
: 但這些ip可能會有數萬個以上
: 我覺得可能太大了
: 所以我還是想先抓的就先寫入文字檔案
: 然後再比對這檔案裡有沒有重覆的
: 沒有再加入
: 該怎麼寫比較好
: 謝謝
用 merge sort 的概念...
假設要寫入的文字檔中,每一行只有一組 IP,且是由小到大 sort 好的。開一個
BufferedReader brInput 來讀文字檔[檔案A]。
先把要存的 200 個 IP sort 好,假設為 String[] ipAddr
開另一個暫存檔[檔案T]的 FileOutputStream fOutput.
1: currentPos = 0;
2: String tmp = Readline from brInput;
3: if (tmp == null)
3a: write ipAddr[currentPos.. ipAddr.length-1] to fOutput
3b: goto 6
4: if (tmp != null) compare ipAddr[currentPos] with tmp
4a: if tmp is smaller,
4a1: write tmp to fOutput
4a2: goto 2
4b: if ipAddr[currentPos] is smaller,
4b1: write ipAddr[currentPos] to fOutput
4b2: currentPos++
4b3: if (currentPos >= ipAddr[currentPos]) goto 5
4b4: goto 4
4c: if they are equals,
4c1: write tmp to fOutput
4c2: currentPos++
4c3: if (currentPos >= ipAddr[currentPos]) goto 5
4c4: goto 2
5: read all lines left from brInput and write to fOutput
6: delete the original file [檔案A]
7: rename the temp file [檔案T] to [檔案A]
8: end
這樣就不用浪費大量的記憶體來先讀入檔案A,但前題是檔案A必須經常保持 sorted
PS. 當然這是比較笨的方法,你還可以用一招,就是使用 RandomAccessFile 來隨便
把新的 IP 值直接插入檔案中間,不過這要把上面的 pseudo code 改一改,就留
給你自己玩玩吧 XD
--
很多人以為 所以我要 其實我是個
我是大學生 告訴大家 三十一歲的怪叔叔
● ●/ ︿ ︿
/勁\ <勁 ●
ㄨ /\ ㄨ
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 218.102.77.165
※ 編輯: superlubu 來自: 218.102.77.165 (01/28 20:26)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 3 篇):