How i can read specific data in java
New I write username and password in file text like that 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.
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:
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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.