作者superlubu (叔叔你人真好)
看板java
标题Re: [问题] 如不重覆便写入一档案?
时间Mon Jan 28 20:19:28 2008
※ 引述《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)