Reading File by line instead of word by word

2019-06-26 03:01发布

问题:

I'm trying to write some code that scans for palindromes in an input file, but it gets strings from each word instead of each line. An example would be racecar would show up as racecar= palindrome or too hot to hoot = palindrome but instead it will go too= not a palindrome, hot= not a palindrome etc.

Here is what I am doing to read the file currently

File inputFile = new File( "c:/temp/palindromes.txt" );
Scanner inputScanner = new Scanner( inputFile );
while (inputScanner.hasNext())
{
    dirtyString = inputScanner.next();

    String cleanString = dirtyString.replaceAll("[^a-zA-Z]+", "");

    int length  = cleanString.length();
    int i, begin, end, middle;

    begin  = 0;
    end    = length - 1;
    middle = (begin + end)/2;

    for (i = begin; i <= middle; i++) {
        if (cleanString.charAt(begin) == cleanString.charAt(end)) {
            begin++;
            end--;
        }
        else {
            break;
        }
    }
}

回答1:

You need to do the following changes

change

while (inputScanner.hasNext()) // This will check the next token.

and 

dirtyString  = inputScanner.next(); // This will read the next token value.

to

while (inputScanner.hasNextLine()) // This will check the next line.

and dirtyString = inputScanner.nextLine(); // This will read the next line value.

inputScanner.next() will read the next token

inputScanner.nextLine() will read a single line.



回答2:

To read a line from a file you should use the nextLine() methond rather than the next() method.

The difference between the two is

nextLine() - Advances this scanner past the current line and returns the input that was skipped.

While

next() - Finds and returns the next complete token from this scanner.

So you'll have to change your while statement to include nextLine() so it would look like this.

while (inputScanner.hasNextLine()) and dirtyString = inputScanner.nextLine();


回答3:

FileReader f = new FileReader(file);
BufferedReader bufferReader = new BufferedReader(f);
String line;
//Read file line by line and print on the console
while ((line = bufferReader.readLine()) != null)   {
        System.out.println(line);
}

The above code segment reads input from file line by line, if it is not clear, please see this for complete program code