I have a text file sample.txt
which have following lines
sample1.txt
test.ppt
example.doc
content.pdf
I have a dynamic variable called field
(example phpcookbook.pdf
,sample1.txt
) it should compare with each line in sample.txt
file and if the text file does not contain the field
it should append to sample.txt
. I have tried the following code but it's not working:
File insert=new File(sample.txt);
BufferedReader br = new BufferedReader(new FileReader(insert));
String strLine;
while ((strLine = br.readLine()) != null) {
if(!strLine.equals(field)) {
FileWriter fw = new FileWriter(insert, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(field);
bw.close();
}
}
I should get the following output
sample1.txt
test.ppt
example.doc
content.pdf
phpcookbook.pdf
How to compare a text file line by line with a dynamic variable?
If I understand the question correctly, this is what you need:
Notice the
break;
. This will discontinue the while loop, since you already have the answer to what you are looking for.But what you WANTED to know was whether or not
field
appeared in the file at all, not in each line.You should do something like this:
You should use Commons IO.
See this working example
No answer since you ask for Java, but just to illustrate the power of Unix shell tools: