2017-01-09 348 views
-1

我正在java中製作一些非常簡單的程序,以查看I/O如何工作,但是我遇到了問題。我創建了「test.txt」文件,現在我試圖(通過掃描器)每次啓動程序時都輸入用戶名和密碼,這並不是什麼大問題。我讓我的程序從文件中讀取內容並寫入控制檯。但是,我的問題是,我希望每次運行程序並輸入新的用戶名時,我的程序都會通過該文件,讀取每個用戶名並在用戶名已存在時給我一個警告。從java中的文件讀取用戶名和密碼

+5

的可能的複製【JAVA:如何讀取文本文件(http://stackoverflow.com/questions/2788080/java-how-to-read-a-text-file) – byxor

+0

請走[Tour](http://stackoverflow.com/tour)並閱讀[Help Center](http://stackoverflow.com/help)中的文檔。特別是,你應該閱讀[如何提出一個好問題](http://stackoverflow.com/help/how-to-ask)和什麼樣的問題[關於主題](http://stackoverflow.com /幫助/話題)。 – azurefrog

+0

具體而言,如果您在詢問代碼的幫助時,需要在代碼中包含代碼以及輸入,期望與實際輸出,任何錯誤等。理想情況下包括[mcve]。 – azurefrog

回答

0

不知道這是你在找什麼,但這應該做的工作。這是一個快速簡單的解決方案。

import java.io.BufferedReader; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.Scanner; 

public class Test { 

    public static void main(String[] args) { 

     String filePath = "{YOUR_FILEPATH_TO_TEST.TXT}"; 
     Scanner scanner = new Scanner(System.in); 
     System.out.println("Enter your username: "); 
     String username = scanner.nextLine(); 
     System.out.println("Checking to see if username exists..."); 
     BufferedReader bufferedReader; 
     try { 
      bufferedReader = new BufferedReader(new FileReader(filePath)); 
      String line; 
      boolean usernameExists = false; 
      while((line = bufferedReader.readLine()) != null) { 
       if (line.equals(username)) { 
        usernameExists = true; 
        break; 
       } 
      } 
      if (usernameExists) { 
       System.out.println("Username exists! Please try again."); 
      } else { 
       System.out.println("Username accepted"); 
      } 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

    } 

} 
相關問題