2017-08-30 127 views
-1

我試圖從.txt文件中獲取文本並將其寫入System,但它不起作用。 我User.txt文件有從.txt文件獲取文本

user:pass 
user2:pass2 
etc 

我想獲得用戶,並通過一次一個,並顯示在System格式。

當前的系統「詳細信息」顯示路徑.txt文件 「用戶名」顯示「C」 「密碼」顯示「C」 我假設C提供啓動路徑文件。我不知道爲什麼它沒有從.txt文件中獲取文本。

我在做什麼錯?

此外,它在第一次迭代後清除整個.txt

String username; 
String password; 
String details; 

try { 
    Scanner fileScanner = new Scanner(getDirectoryData() + "User.txt"); 
    details = fileScanner.nextLine(); 
    System.out.println(details); 
    username = details.split(":")[0].split("@")[0]; 
    password = details.split(":")[0]; 

    System.out.println(username); 
    System.out.println(password); 

    FileWriter fileStream = new FileWriter(getDirectoryData() + "User.txt"); 
    BufferedWriter out = new BufferedWriter(fileStream); 

    // sendMessage("INFO:BOT:" + username); 

    while(fileScanner.hasNextLine()) { 
    String next = fileScanner.nextLine(); 
    if(next.equals("\n")) { 
     out.newLine(); 
    } else { 
     out.write(next); 
     out.newLine(); 
    } 
    } 

    out.close(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
+0

順便說一下,堆棧溢出不是論壇,它是一個問答網站,它與論壇有着非常不同的約定。請閱讀該網站[旅遊]瞭解更多信息。 – EJoshuaS

回答

1

所以你遇到的問題是,掃描儀從字面上讀String作爲getDirectoryData() + "User.txt",而不是讀要讀文件。這就是爲什麼你要獲取文件的名稱而不是文件的內容。

這裏是你如何可以修改代碼以解決此問題:

File file = new File(getDirectoryData() + "User.txt"); 
    Scanner fileScanner = new Scanner(file); 
    details = fileScanner.nextLine(); 
    System.out.println(details); 
0

如果你是想從文件中讀取所有條目,也許你應該這樣做,請更改文件目錄按您的要求。

public static void reader(){ 
     String details; 

     try{ 
      File file = new File("file/User.txt"); 
      Scanner input = new Scanner(file); 

      while(input.hasNextLine()){ 
       details = input.nextLine(); 
       System.out.println(" read file details : "+details); 
      } 
      input.close(); 

     }catch(Exception e){ 
      e.printStackTrace(); 
     } 
    }