0
假設我們有兩個文件f1 and f2.
同時從兩個文件中讀取
另外,假定有一個名爲comparision(File f1,File f2)
功能。 該函數將獲取兩個文件作爲參數,並從f1中取出第一個字符(word),並將其與f2中的所有字符進行比較,直到結束,然後選取第二個字符,直到第一個字符結束爲止。
我的問題是:我該如何執行此操作?我需要知道EOF嗎?如果是這樣,如何得到它?
假設文件是純文本(.txt)
並且每個單詞都在一行中。 爲例:
f1:
I
am
new
to
java
f2:
java
is
a
programing
language
下面的代碼:
static void comparision(File f, File g) throws Exception
{
Set<String> text = new LinkedHashSet<String>();
BufferedReader br = new BufferedReader(new FileReader(g));
for(String line;(line = br.readLine()) != null;)
text.add(line.trim().toString());
if(text==null)
return;
BufferedReader br = new BufferedReader(new FileReader(f));
String keyword = br.readLine();
if (keyword != null) {
Pattern p = Pattern.compile(keyword, Pattern.CASE_INSENSITIVE);
StringBuffer test = new StringBuffer(text.toString());
matcher = p.matcher(test);
if (!matcher.hitEnd()) {
total++;
if (matcher.find()) {
//do sth
}
}
}
}
編輯由jcolebrand
一些思考,我們需要看起來像這樣(僞碼)程序流
function(file1,file2) throws exceptions{
ArrayList<string> list1, list2; //somebody said we should use an ArrayList ;-)
string readinTempValue = null;
br = BufferedReader(file1) //we are already using a BufferredReader
readinTempValue = br.ReadLine();
//this is a loop structure
while (readinTempValue != null){ //trust me on this one
//we need to get the string into the array list....
//how can we ADD the value to list1
readinTempValue = br.ReadLine(); //trust me on this one
}
br = BufferedReader(file2) //we are already using a BufferredReader
readinTempValue = br.ReadLine();
//this is a loop structure
while (readinTempValue != null){ //trust me on this one
//we need to get the string into the array list....
//how can we ADD the value to list2
readinTempValue = br.ReadLine(); //trust me on this one
}
foreach(value in list1){
foreach(value in list2){
compare value from list 1 to value from list 2
}
}
}
看起來這可能是別人的啓發性的問題...但它需要澄清。剛發佈了一些編輯...你能添加預期的輸出嗎? – jayunit100 2011-12-15 03:39:17
@ user1064929到目前爲止你做得很好。但是您需要將其分解爲兩個任務:將兩個文件都讀入,將文件1中的每個單詞與文件2中的每個單詞相比較。看起來你正在將兩者混合在一起。 – jcolebrand 2011-12-15 03:49:57