We help IT Professionals succeed at work.

Java: Error when reading a file

isames
isames asked
on
115 Views
Last Modified: 2019-02-21
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

CERTIFIED EXPERT
Top Expert 2016
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION
CERTIFIED EXPERT
Top Expert 2016

Commented:
:)