逐行比较文本文件和动态变量

时间:2013-06-19 14:15:12

标签: java string file search text

我有一个文本文件sample.txt,其中包含以下行

sample1.txt
test.ppt
example.doc
content.pdf

我有一个名为field的动态变量(例如phpcookbook.pdfsample1.txt)它应该与sample.txt文件中的每一行进行比较,如果文本文件不包含field它应附加到sample.txt。我尝试了以下代码,但它不起作用:

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();
    }
}

我应该得到以下输出

sample1.txt
test.ppt
example.doc
content.pdf
phpcookbook.pdf

如何逐行比较文本文件和动态变量?

4 个答案:

答案 0 :(得分:3)

如果我正确理解了这个问题,那就是你需要的:

File insert = new File("sample.txt");
BufferedReader br = new BufferedReader(new FileReader(insert));
String strLine;
Boolean hasLine = false;

while ((strLine = br.readLine()) != null) {
    if(strLine.equals(field)) {
        hasLine = true;
        break;
    }
}

br.close();

if (!hasLine) {
    FileWriter fw = new FileWriter(insert, true);
    BufferedWriter bw = new BufferedWriter(fw);
    bw.append(field + "\n"); // assumes field does not already have a newline
    bw.flush();
    bw.close();
}

注意break;。这将停止while循环,因为您已经找到了所需内容的答案。

Your original code was doing:
for every line:
  Do I equal field?
    Yes: goto next line
    No: append field to file and goto next line

但您想知道的是field是否出现在文件中,而不是每一行。

答案 1 :(得分:1)

你应该这样做:

    File insert = new File("sample.txt");
    boolean isStringPresent = false;
    BufferedReader br = new BufferedReader(new FileReader(insert));
    String strLine;
    while ((strLine = br.readLine()) != null) {
        if (strLine.equals(field)) {
            isStringPresent = true;
        } 

    }
    if(!isStringPresent) {
        FileWriter fw = new FileWriter(insert, true);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.append(field);
        bw.close();
    }

答案 2 :(得分:1)

你应该使用Commons IO。

参见此工作示例

package training;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.FileUtils;

public class TestFile {

    /**
     * @param args
     * @throws IOException
     */
    private static String field = "phpcookbook.pdf";
    private static String fileContent;

    public static void main(String[] args) throws IOException {
        boolean found = false;
        File file = new File("test.txt");
        List<String> lines = FileUtils.readLines(file);
        for (String line : lines) {
            if (line.equals(field)) {
                found = true;
                break;

            }
        }
        if (!found) {
            fileContent = FileUtils.readFileToString(file);
            fileContent += "\n" + field;
        }
        FileUtils.write(file, fileContent);
    }
}

答案 3 :(得分:0)

因为你要求使用Java而没有答案,只是为了说明Unix shell工具的强大功能:

v=phpcookbook.pdf
grep $v in.txt
[[ $? -eq 1 ]] && echo $v >> in.txt