2015-11-05 100 views
-3

我正在處理類項目的密碼登錄部分。沒有什麼花哨。用戶或角色將是一個int並且密碼是一個String。我現在只是使用簡單的加密。我遇到的問題是在讀取文件時遇到輸入不匹配。過去我做了類似的事情,需要我閱讀整數和字符串,並沒有任何問題。但我無法弄清楚在這種情況下出了什麼問題。任何幫助,爲什麼我得到這個錯誤將不勝感激。我正在使用while(inputStream.hasNextLine()),然後閱讀int,然後String我試過hasNextInthasNext,並一直得到相同的錯誤。從txt文件加載int和加密的字符串

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

你需要上傳你要得到很好的幫助實際的錯誤 - I,E,實際的錯誤消息,說明該線失敗和堆棧跟蹤。 –

回答

1

嘗試閱讀它作爲一個字符串和字符串轉換爲一個int

while (inputStream.hasNextLine()) { 

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

但是,你需要確保你的文件有確切格式的數據如下

12342 
password 
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);