[英]How i can read specific data in java
How i can read specific data in java 我如何在Java中读取特定数据
New I write username and password in file text like that ID:username:password 新的我在文件文本中输入用户名和密码,例如ID:username:password
How I can read this data please ? 请问我该如何读取这些数据? And my program knews this is username and that password 😁
我的程序知道这是用户名和密码😁
If I understand correctly, the easiest way is to read the text file and parse it into variables accordingly as follows: 如果我理解正确,最简单的方法是读取文本文件并将其相应地解析为变量,如下所示:
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String text= sb.toString();
String parts = text.split(":")
String id= parts[0]
String username = parts[1]
String pass = parts[2]
} finally {
br.close();
}
If there is only one entry, you can use the code below, which is quite similar to the first answer, but without the StringBuilder stuff. 如果只有一个条目,则可以使用下面的代码,该代码与第一个答案非常相似,但是没有StringBuilder。
try {
BufferedReader reader = new BufferedReader(new FileReader(new File("file.txt")));
String line = reader.readLine();
String[] parts = line.split(":");
String id = parts[0];
String username = parts[1];
String password = parts[2];
//Do stuff with it
}catch(IOException e){
e.printStackTrace();
}
However if there are multiple entries, you should use NIO: 但是,如果有多个条目,则应使用NIO:
try{
List<String> filecontents = Files.readAllLines(new File("file.txt"));
for(int i = 0; i < filecontents.size(); i++){
String line = filecontents.get(i);
String[] parts = line.split(":");
String id = parts[0];
String username = parts[1];
String password = parts[2];
//Do stuff with it
}
}catch(IOException e){
e.printStackTrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.