Search code examples
javafileinputstreamfileinputstream

Loading an int and an encrypted String from txt file


I am working on the password login portion of a class project. Nothing fancy. User, or role will be an int and password is a String. I am just using a simple encryption for now. The problem I am having is while reading the file I am getting an input mismatch. I have done something similar in the past that required me to read ints and Strings and did not have any problems. But I just cannot figure out what is going wrong in this case. Any help as to why I am getting this error would be greatly appreciated. I am using while(inputStream.hasNextLine()) then read the int and then the String I have tried hasNextInt and hasNext and keep getting the same error.

public void readFile(){
    Scanner inputStream = null;
    try {
        inputStream = new Scanner (new FileInputStream("login.txt"));
    }catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    if(inputStream != null){
    while (inputStream.hasNextLine()){
        int luser = inputStream.nextInt();
        String lpass = inputStream.nextLine();
        newFile[count] = new accessNode(luser, lpass);
        count ++;
    }
    inputStream.close();
    }    
}

Solution

  • Try reading it as a String and converting the string to an int

    while (inputStream.hasNextLine()) {
    
        Integer luser = Integer.parseInt(inputStream.nextLine());
        String lpass = inputStream.nextLine();
        newFile[count] = new accessNode(luser, lpass);
        count++;
    }
    

    But you need to make sure your file has your data in the exact format as below

    12342
    password