问题
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