我尝试使用读取文件中的数据java.util.Scanner
。当我尝试\n
用作定界符时,当我尝试向它们添加更多文本时,生成的字符串会产生奇怪的反应。
我有一个名为“ test.txt”的文件,并尝试从中读取数据。然后,我想向每个String添加更多文本,类似于打印方式Hello World!
:
String helloWorld = "Hello "+"World!";
System.out.println(helloWorld);.
我尝试将与合并数据+
,+=
并且尝试了String.concat()
,这以前对我有用,通常仍然有效。
我也尝试使用不同的定界符,或者根本不使用定界符,正如我期望的那样,这两种方法都可以,但是我需要在换行符处将字符串分开。
test.txt
最小可复制示例的文件包含以下文本(每行末尾都有一个空格):
零:
一:
二:
三:
void minimalReproducibleExample() throws Exception { //May throw an exception if the test.txt file can't be found
String[] data = new String[4];
java.io.File file = new java.io.File("test.txt");
java.util.Scanner scanner = new java.util.Scanner(file).useDelimiter("\n");
for (int i=0;i<4;i++) {
data[i] = scanner.next(); //read the next line
data[i] += i; //add a number at the end of the String
System.out.println(data[i]); //print the String with the number
}
scanner.close();
}
我希望这段代码可以打印出以下几行:
零:0
一:1
二:2
三:3
我得到以下输出:
0ero:
1ne:
2wo:
3:3
\n
用作定界符时,为什么没有得到预期的输出?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句