Java: Error when reading a file

isames
isames used Ask the Experts™
on
All,

I'm trying to read and output the contents of a file called credentials.txt. The code is below and attached is the error I'm getting.

package testingrandommethods;
import java.util.Scanner;
import java.io.*;

public class TestingRandomMethods {

   
    public static void main(String[] args) throws IOException {    //I had an error until I added "throws IOException" when trying to open the file.
         
        FileInputStream fileByteStream = null;
        Scanner credFile = null;
        String credData = "";

        //Attempt to open file
        fileByteStream = new FileInputStream("credentials.txt");
        credFile = new Scanner(fileByteStream); //credFile now contains what's in credentials.txt.
        System.out.println("Reading and printing data.");
        credData = credFile.next(); //credData now contains what's in credentials.txt as well. It allows me to read through the file.
       
        while (credData.charAt(0)){
            System.out.println(credData);
           
            credData = credFile.next();
        }
        System.out.println(credData);
       
        //Close the file
        System.out.println("Closing the credential.txt file.");
        fileByteStream.close();
        return;
    }
   
}

ErrorMessage.png
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2016
Commented:
No need to post a new question. This would have come out from your last one
You need to look at examples of using a Scanner.

while(credData.charAt(0))

Open in new window

won't compile because the method of String that you're calling returns char, not boolean. Unlike other languages, conversion to  boolean is not possible

while(credFile.hasNext())

Open in new window

is the sort of thing you should be using
Top Expert 2016

Commented:
:)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial