0

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...

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. My problem is easily solved by subtracting one from y, but I am not satisfied with that. This problem drives me crazy since I have no clue where the newline comes from.

halfer
  • 19,824
  • 17
  • 99
  • 186
Donkey King
  • 87
  • 1
  • 8
  • Are you sure about the contents of the file? How did you generate it? Does it have length 3 or 4? – Henry Apr 16 '17 at 10:54
  • The files was created this way. 1. Pressing "ABC". 2. Saving. 3. Exiting. – Donkey King Apr 16 '17 at 10:55
  • With which editor? Most editors will put a line end after each line. On which OS are you? can you make a hexdump of the file and check? – Henry Apr 16 '17 at 10:57
  • I am using gedit on ubuntu 16.04. – Donkey King Apr 16 '17 at 11:55
  • Thank you, the editor was adding invisible newlines after the eof. I disabled it with the following command for gedit: gsettings set org.gnome.gedit.preferences.editor ensure-trailing-newline false – Donkey King Apr 16 '17 at 12:09
  • Side note: don' use ready(). It doesn't do what you think it does. Just read until read() returns -1. – JB Nizet Apr 16 '17 at 13:00

1 Answers1

0

(Posted on behalf of the OP).

My editor (and several else) was adding a newline after eof in the file. 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

Gedit adds line at end of file

Community
  • 1
  • 1
halfer
  • 19,824
  • 17
  • 99
  • 186