[英]String's content retrieved from file disappears during concatenation or equality check
我正在制作一個必須讀/寫純文本文件的程序。 我從文件中讀取文本,然后對其進行處理以將字符串分成幾個組件(即行,然后是變量/值)。 當我嘗試處理其中一些組件時,字符串的內容似乎會暫時更改或消失。 此代碼重現了該問題:
package spriteModder;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class ErrorThing {
public static void main(String[] args) throws IOException {
loadFile(new File("settings.config"));
}
public static void loadFile(File f) throws IOException {
FileInputStream fis=new FileInputStream(f);
int numread=1;
StringBuilder contentBuilder= new StringBuilder();
byte[] buffer=new byte[8];
while(numread>0) {
numread=fis.read(buffer);
if(numread==-1){break;}
contentBuilder.append(new String(buffer, 0, numread));
}
String source=contentBuilder.toString();
System.out.println(source);
String[] lines=source.split("\n");
for(String s:lines){
System.out.println(s);
String[] a=s.split("=");
for(String s2:a){
System.out.println(s2);
System.out.println(s2+"4");
System.out.println(s2.equals("true"));
}
}
}
}
這是 output:
//these three lines are to verify the contents of the settings.config file, which works as expected
outputDir=*here
lookInSubDirectories=true
inputDir=*here
outputDir=*here //the first line of the file
outputDir //the first component of the line
outputDir4 //the first component of the line after concatenation.
false //checks if the component (w/o concatenation) is equal to "true"
*here //second component of the line
4 //second component of the line after concatenation, which is missing the entire original component
false //checks if the second component of the line is equal to "true"
lookInSubDirectories=true
lookInSubDirectories //the first component of the second line
lookInSubDirectories4
false
true // the second component
4 //this component also disappears during concatenation
false // but also fails the equality check, even though the content is "true"
inputDir=*here
inputDir
inputDir4
false
*here
*here4 //you can see concatenation working on the third line's second component here for some reason
false
settings.config 的內容是:
outputDir=*here
lookInSubDirectories=true
inputDir=*here
我嘗試更改字節緩沖區的大小,使用 FileReader 而不是 FileInputStream,並使用臨時變量但沒有成功。 我還規避了讀取文件,只是將相同的內容硬編碼到一個字符串中,從而避免了這個問題。 但是,必須從文件中讀取內容。 當僅連接一個空字符串 ("") 時,連接始終有效,但其他任何內容都會導致原始內容在這兩行中消失。 無論使用 .equals 還是 ==,相等性檢查都會失敗。 使用 substring() 而不是 split() 來生成組件沒有效果。 到底是怎么回事? 為什么連接會導致原始字符串在結果中消失,但只是有時? 為什么平等檢查不起作用?
好的,所以這里沒有任何內容,並且您的程序可以正常工作,即使以不必要的繁瑣方式編寫也是如此。 離開這一行最容易檢查:
System.out.println(s2);
作為拆分String
迭代中唯一的 output 。 唯一的錯誤是得出的結論是某些東西“消失了”。 我會大膽猜測並說您在 Windows 上運行此代碼,或者將您的settings.config
文件的換行符設置為\r\n而不是\n 。 因此,僅在\n上拆分會留下懸掛的\r s,因此您有:
"*here\r" + "4"
這被打印為
*here
4
最好使用調試器或if語句檢查掛起的\r 。
因此,您的程序的工作原理就像將abc=123
拆分為"abc"
和"123"
(或者,更確切地說是拆分為"abc"
和"123\r"
)。 但是請考慮使用 Java 的內置方法從文件加載Properties
,或者至少使用BufferedReader
,我認為它的readLine
方法將同時消耗回車符和換行符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.