簡體   English   中英

java文件中字符串的路徑

[英]Path to string in java files

在我的程序中,我有一個 .txt 文件,其中包含一些配置值。

我的 config.txt 布局如下:

Users:
  Jeff: 14
  Jimmy: 23
  Jack: 532

我的代碼由掃描儀、一些變量和一些打印線命令組成。

我希望程序的用戶輸入一個名稱,如果他們輸入的名稱存在於配置中,則返回該值,如果該名稱不存在,則將該名稱添加到列表中並為其分配一個值。

我知道如何創建和讀取和寫入文件,但如何在“用戶:”鍵下寫入和讀取?

我已經做了很多研究,但我還沒有弄清楚。

編輯:我一直在處理一些代碼,我得到了這個。

      //Code used to get the username to read.
      Scanner sc = new Scanner(System.in);
      String user = new String();
      String pass = new String();

      //Username Detection
      System.out.println("Please enter your username.");
      user = sc.nextLine();
      System.out.println("User name is: "+user);
      try {
        readSSDB(user);
        
      } catch (FileNotFoundException e) {
        // Do something with `e`
      }
    //Code used to check the file.
    public static void readSSDB(String user) throws FileNotFoundException{
      File SSDB = new File("SSDB.txt");

      System.out.println("File Reader Loaded Successfully.");

      Scanner read = new Scanner(SSDB);

      String userRead = read.nextLine();

      boolean userFound = false;

      while(userFound == false){
        if(read.nextLine().contains(user)){
          
          System.out.println("Found user: "+userFound);
        }else{
          System.out.println("No user '"+user+"' found!");
          read.nextLine();
        }
      }
    }

編輯 2:意識到我說的是 while(userFound = false) 而不是 while(userFound == false)。

我得到的輸出是:“找不到用戶‘吉米’!找到了:‘吉米:23’”

不應該if(read.nextLine().contains(user)){返回 true 因為 read.nextLine() 是“Jimmy: 23”而用戶是“Jimmy”所以從邏輯上講“Jimmy: 23”確實包含“Jimmy” ?

您可以使用nextLine()

if(scannedLine.contains(name)) {
    //return data to the user
} else {
    //add user to he config file
}

你有沒有嘗試過這樣的事情?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM