简体   繁体   中英

write string in file if not exist java

i try to write String to file only if String not exist, this is my code

File rule_file = new File("test_rules.rules");
Scanner scanner = new Scanner(rule_file);
PrintWriter writer = new PrintWriter(new FileWriter(rule_file,true));

        while (scanner.hasNextLine()) 
        {
            String lineFromFile = scanner.nextLine();
            if(!rule_write.equals(lineFromFile))
            {
               if(unique.get(nilai_besar).getCount()>10)
               {
                        writer.write(rule_write);
                        writer.close();
                        break;
               }
            }
        }

but, the program keep write String to file even the String already exist in file. Please help, thanks...

You could be writing the extra line after checking just one line of the file.

I suggest you read the file to the end, without attempting to write to it, until you know the line does appear anywhere in the file.

ie I would use a PrintWriter.println() and I would move all the code for writing to after the search loop.

For every line that is not equal you (potentially) try to write to the file.

What you want is to write to the file if all lines are not equal:

    boolean found = false;
    while (scanner.hasNextLine()) 
    {
        String lineFromFile = scanner.nextLine();
        if (rule_write.equals(lineFromFile))
        {
           found = true;
           break;
        }
    }

    if (!found) {
        // append rule_write to the file
        ...
    }

Go with indexOf() or contains() instead of equals() and equalsIgnoreCase(),

I am sure that the line you read may contain

  • Empty spaces (before or after)
  • Next line problem may occur

If you use indexOf() or contains() , it will check ,whether the line have the string ( rule_write )

Make sure the the values are coming in while()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM