Java 从.txt文件获取文本
我正试图从Java 从.txt文件获取文本,java,output,bufferedreader,Java,Output,Bufferedreader,我正试图从.txt文件中获取文本,并将其写入系统,但它不起作用。 我的User.txt文件的格式为 user:pass user2:pass2 etc 我想获取用户并一次传递一个,然后在系统中显示它 “详细信息”的当前系统显示.txt文件的路径 “用户名”显示“C” “密码”显示“C” 我假设C启动路径文件。我不知道为什么它不能从.txt文件中获取文本 我做错了什么 此外,它在第一次迭代后清除整个.txt String username; String password; String det
.txt
文件中获取文本,并将其写入系统
,但它不起作用。
我的User.txt
文件的格式为
user:pass
user2:pass2
etc
我想获取用户并一次传递一个,然后在系统中显示它
“详细信息”的当前系统显示.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();
}
因此,您遇到的问题是,扫描仪读取字符串的方式是getDirectoryData()+“User.txt”
,而不是读取您想要读取的文件。这就是为什么您得到的是文件名而不是文件内容
以下是如何修改代码以修复此问题:
File file = new File(getDirectoryData() + "User.txt");
Scanner fileScanner = new Scanner(file);
details = fileScanner.nextLine();
System.out.println(details);
如果您想读取文件中的所有条目,可能您应该这样做,并请根据您的要求更改文件目录
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();
}
}
顺便说一句,Stack Overflow不是一个论坛,它是一个问答网站,与讨论论坛有着非常不同的约定。请阅读该网站以了解更多信息。