将内容添加到文件中,如果已存在,则不要添加

时间:2016-05-17 04:56:39

标签: java file io

我想写入一个文件。但在写之前,我想检查文件中是否已存在该内容。如果内容存在则不要添加;如果没有,那么添加。我怎么能用Java做到这一点?

我的代码是这样的:

bufferedReader = new BufferedReader(new FileReader(filePath));

while (bufferedReader.readLine() != null) {
    System.out.println(bufferedReader.readLine() +":" + orphan);
    if(bufferedReader.readLine().equals(orphan)){
        System.out.println("Matched ==============");
        check = true ;
        break;
    }
}

if(check != true) {
    System.out.println("writting the value ");
    bufferedWriter = new BufferedWriter(new FileWriter(filePath, true));
    bufferedWriter.write(orphan);
    bufferedWriter.newLine();
    bufferedWriter.close();
}

1 个答案:

答案 0 :(得分:0)

问题在于您尝试阅读文件内容的方式。

while (bufferedReader.readLine() != null) { // read line n
    System.out.println(bufferedReader.readLine() +":" + orphan); // read line n + 1
    if(bufferedReader.readLine().equals(orphan)){ // read line n + 2
        System.out.println("Matched ==============");
        check = true ;
        break;
    }
}

每次调用bufferedReader.readLine()时,它都会读取下一行。 你的代码看起来像这样(未经测试!):

String input = bufferedReader.readLine(); // read line n
while (input != null) { 
    System.out.println(input +":" + orphan);
    if(input.equals(orphan)){
        System.out.println("Matched ==============");
        check = true ;
        break;
    }
    input = bufferedReader.readLine(); // read line n+1
}