简体   繁体   中英

Compare a string input using RandomAccessFile with another string

i have a small issue with my code in Java. The problem is that i can't check if a string is equal with a line of a file with RandomAccesFile. I need to check if the string is the same with the line and if its true, fill the line with some extra information. The method .equals() never returns true because the input line some extra hidden characters. Here is my method for writing inside the file with RandomAccessFile:

 public static void writeData(String DateTime, int cost) {
    try (RandomAccessFile raf = new RandomAccessFile("book.txt","rw")) {
        raf.seek(raf.length());
        if(raf.length() != 0) {
            raf.writeChars("\n");
        }
        raf.writeChars(""+DateTime+"|"+cost);
        raf.close();
    }
    catch (IOException ex) {
        System.out.println(ex);
    }
}

And here is my code to Read and Write from/to file:

 public static void addData () {
    try (RandomAccessFile raf = new RandomAccessFile("book.txt","rw")) {
        long current = 0;
        while (current < raf.length()) {

            String inputLine=raf.readLine();

            String tmp = "Something";

            if (inputLine.equals(tmp)) {

                raf.writeChars(inputLine+"Other Informations");
            }
            current = raf.getFilePointer(); 
        }
        raf.close();
    }
    catch (IOException ex) {
        System.out.println(ex);
    }
}

You can use the String.replaceAll() method with the RegularExpression "\\s+". This covers all whitespace characters and line breakers and so on. In your case this would be:

public static void addData () {
    try (RandomAccessFile raf = new RandomAccessFile("book.txt","rw")) {
        long current = 0;
        while (current < raf.length()) {

            String inputLine=raf.readLine();

            inputLine = inputLine.replaceAll("\\s+","");
    
            String tmp = "Something";

            if (inputLine.equals(tmp)) {

                raf.writeBytes(inputLine+"Other Informations");
            }
            current = raf.getFilePointer(); 
        }
        raf.close();
    }
    catch (IOException ex) {
        System.out.println(ex);
    }
}

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