繁体   English   中英

使用java.util.Scanner从文件中读取字符串并使用换行符作为分隔符时,字符串的行为异常

[英]Strings act weirdly when reading them from a file with the java.util.Scanner and using linebreaks as delimiter

我尝试使用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:2
三:3

我得到以下输出:

0ero:
1NE:
2wo:
三:3

当使用\\n作为分隔符时,为什么不能获得预期的输出?

test.txt最有可能使用Windows 行尾表示法 \\r\\n ,导致读取后在String仍存在回车符\\r

确保test.txt使用\\n作为行delimtier或在Scanner.useDelimiter()使用Windows \\r\\n

分隔符错误很可能是问题所在。 如果使用Windows 10,则新的行分隔符为\\r\\n

只是要与平台无关,请使用System.getProperty("line.separator")而不是硬编码\\n

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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