Skipping in my File Reader

半城伤御伤魂 提交于 2019-12-14 04:02:45

问题


 public void file(){
        String fileName = "hello.txt";
        fileName = FileBrowser.chooseFile(true);


        //Open a file and store the information into the OurList
        try
        {
            String s = "";
            File file = new File(fileName);
            FileReader inputFile = new FileReader(file);
            while( inputFile.read() != -1)
            {
                System.out.println(inputFile.read());
                System.out.println();
            }
        }
        catch(Exception exception)
        {
            System.out.println("Not a real file. List is already built");
        }

    }

So i am having trouble with this piece of code. I want to just read in character by character from the file, but right now its skipping every other one. I know why its skipping, its in the while loop and when I try to print it, but as far as I can tell there isn't another way to stop FileReader then to make it != to -1. How can I get it to not skip?


回答1:


You're calling read() twice in the loop, so you're not seeing every odd character. You need to store the result of read() in a variable, test it for -1, break if so, otherwise print the variable.




回答2:


int nextChar;
while( (nextChar = inputFile.read()) != -1)
  {
        System.out.println(nextChar);
        System.out.println();
    }



回答3:


Use this pattern:

        int value = inputFile.read();
        while(value  != -1)
        {
            System.out.println(value);
            System.out.println();
            value = inputFile.Read();
        }



回答4:


As you have already aware, you are calling read() twice per loop, which caused the problem.

Here is some common ways to properly loop-and-read:

A verbose-but-working way that I believe most people can figure out by themselves is:

boolean continueToRead = true;
while(continueToRead) {
    int nextChar = file.read();
    if (nextChar != -1) {
        ....
    } else {  // nextChar == -1
        continueToRead = false;
    }
}

or using break:

while(true) {
    int nextChar = file.read();
    if (nextChar == -1) {
        break;
    }

    ....
}

A cleaner pattern:

int nextChar = file.read();
while (nextChar != -1) {
    ....
    nextChar = file.read();
}

or

while ((nextChar = file.read()) != -1) {
    ....
}

I am more into using for loop:

for (int nextChar = file.read(); nextChar != 1; nextChar = file.read()) {
    ....
}


来源:https://stackoverflow.com/questions/23232951/skipping-in-my-file-reader

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!