[英]Compare a string input using RandomAccessFile with another string
我的 Java 代碼有一個小問題。 問題是我無法檢查字符串是否與帶有 RandomAccesFile 的文件的一行相等。 我需要檢查字符串是否與該行相同,如果為真,則用一些額外的信息填充該行。 方法 .equals() 永遠不會返回 true,因為輸入行有一些額外的隱藏字符。 這是我使用 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);
}
}
這是我從/向文件讀取和寫入的代碼:
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);
}
}
您可以將 String.replaceAll() 方法與正則表達式“\\s+”一起使用。 這涵蓋了所有空白字符和換行符等。 在您的情況下,這將是:
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.