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