问题描述:

I have created a method with BufferedReader that opens a text file created previously by the program and extracts some characters. My problem is that it extracts the whole line and I want to extract only after a specified character, the :.

Here is my try/catch block:

try {

InputStream ips = new FileInputStream("file.txt");

InputStreamReader ipsr = new InputStreamReader(ips);

BufferedReader br1 = new BufferedReader(ipsr);

String ligne;

while((ligne = br1.readLine()) != null) {

if(ligne.startsWith("Identifiant: ")) {

System.out.println(ligne);

id = ligne;

}

if(ligne.startsWith("Pass: ")) {

System.out.println(ligne);

pass = ligne;

}

}

System.out.println(ligne);

System.out.println(id);

System.out.println(pass);

br1.close();

} catch (Exception ex) {

System.err.println("Error. "+ex.getMessage());

}

At the moment, I return to my String id the entire ligne, and same for pass – by the way, all the sysout are tests and are useless there.

If anybody knows how to send to id the line after the :and not the entire line, I probably searched bad, but google wasn't my friend.

网友答案:

Assuming there's only one : symbol in the string you can go with

 id = ligne.substring(ligne.lastIndexOf(':') + 1);
网友答案:

Use StringUtils

StringUtils.substringAfter(id ,":"),

网友答案:

Why don't you try to do a split() on ligne?

If you use String[] splittedLigne = ligne.split(":");, you will have the following in splittedLigne:

splittedLigne[0] -> What is before the :

splittedLigne[1] -> What is after the :

This will give you what you need for every line. Also, this will work for you if you have more than one :.

相关阅读:
Top