简体   繁体   English

FileReader总是读取至少一个换行符,即使Java中没有任何换行符

[英]FileReader always read at least one newline despite none in file in Java

I have this code... 我有这个代码...

try{
    FileReader fread = new FileReader(new File("testfile"));
    int y = 0;
    while (fread.ready()){
        char path = (char)fread.read();
        System.out.println(path);
        if (path == '\n'){
            y++;
        }
    }
    System.out.println("Newlines: " + y);
}
catch (Exception e){
    System.out.println(e.getMessage());
}

...and a file called testfile containing the following information... ...以及一个名为testfile的文件,其中包含以下信息...

ABC

...and when I run the program it prints out that the file contains one newline. ...当我运行程序时,它会打印出该文件包含一个换行符。 Why is that? 这是为什么? I simply cannot find the reason why, having read the Oracle documentation. 阅读Oracle文档后,我根本找不到原因。 My problem is easily solved by subtracting one from y, but I am not satisfied with that. 我的问题很容易解决,方法是从y中减去1,但是我对此并不满意。 This problem drives me crazy since I have no clue where the newline comes from. 这个问题使我发疯,因为我不知道换行符的来源。

(Posted on behalf of the OP) . (代表OP张贴)

My editor (and several else) was adding a newline after eof in the file. 我的编辑器(和其他几个编辑器)在文件中的eof之后添加了换行符。 Here are pages that list different solutions for different editors: 以下页面列出了针对不同编辑者的不同解决方案:

https://askubuntu.com/questions/13317/how-to-stop-gedit-gvim-vim-nano-from-adding-end-of-file-newline-char https://askubuntu.com/questions/13317/how-to-stop-gedit-gvim-vim-nano-from-adding-end-of-file-newline-char

Gedit adds line at end of file Gedit在文件末尾添加行

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

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