有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从文件中获取文本。txt文件

我试图从.txt文件中获取文本,并将其写入System中,但它不起作用。 我的User.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();
}

共 (2) 个答案

  1. # 1 楼答案

    因此,您遇到的问题是,扫描器读取字符串的字面意思是getDirectoryData() + "User.txt",而不是读取您想要读取的文件。这就是为什么您得到的是文件名而不是文件内容

    以下是如何修改代码以修复此问题:

        File file = new File(getDirectoryData() + "User.txt");
        Scanner fileScanner = new Scanner(file);
        details = fileScanner.nextLine();
        System.out.println(details);
    
  2. # 2 楼答案

    如果您想读取文件中的所有条目,可能您应该这样做,并请根据您的要求更改文件目录

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