【问题标题】:Loading an int and an encrypted String from txt file [closed]从 txt 文件加载一个 int 和一个加密的字符串 [关闭]
【发布时间】:2016-02-06 23:28:08
【问题描述】:

我正在处理一个班级项目的密码登录部分。没有什么花哨。用户或角色将是一个 int,密码是一个字符串。我现在只是使用简单的加密。我遇到的问题是在读取文件时出现输入不匹配。我过去做过类似的事情,需要我阅读整数和字符串并且没有任何问题。但我只是无法弄清楚在这种情况下出了什么问题。对于我为什么会收到此错误的任何帮助将不胜感激。我正在使用while(inputStream.hasNextLine()),然后阅读int,然后阅读String,我尝试过hasNextInt 和hasNext,并不断收到相同的错误。

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();
    }    
}

【问题讨论】:

  • 您需要发布实际错误以获得良好帮助 - 即显示哪一行失败和堆栈跟踪的实际错误消息。

标签: java file inputstream fileinputstream


【解决方案1】:

很难说不知道你得到了什么错误,但我猜这是因为你没有阅读整个文件。

您的文件可能如下所示:

1\r\n
password\r\n

当您调用 nextInt() 时,它会读取 int,但不会超过第一个 \r\n,因此当您调用 nextLine() 时,它会读取到行尾,因此您得到的只是 \r\n .你需要读完第一个\r\n,然后再读密码。

试试

int luser = inputStream.nextInt();
inputStream.nextLine();
String lpass = inputStream.nextLine();
newFile[count] = new accessNode(luser, lpass);

【讨论】:

    【解决方案2】:

    尝试将其读取为字符串并将字符串转换为 int

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

    但您需要确保您的文件中的数据格式与以下完全相同

    12342
    password
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-01
      • 2021-10-28
      • 1970-01-01
      • 2021-09-04
      • 1970-01-01
      • 2020-05-03
      • 1970-01-01
      • 2012-11-16
      相关资源
      最近更新 更多