0

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.

Sébastien Le Callonnec
  • 26,254
  • 8
  • 67
  • 80
fselva
  • 457
  • 1
  • 7
  • 18

3 Answers3

1

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

 id = ligne.substring(ligne.lastIndexOf(':') + 1);
Stugal
  • 850
  • 1
  • 8
  • 24
  • There is indeed only one `:`per line, It works great. Thanks for your answer, I discover the substring method, very powerfull. – fselva May 18 '15 at 08:46
  • or `id = id.substring(id.indexOf(':') + 1);` if you want to start after first `:` ... – Serge Ballesta May 18 '15 at 08:46
  • I just edited my answer, you should substring from ligne not id, sorry. – Stugal May 18 '15 at 08:47
  • 1
    No problem for the mistake Stugal, I adapted your answer to my code, like this: `pass = ligne.substring(ligne.lastIndexOf(':')+2);` :) – fselva May 18 '15 at 08:49
0

Use StringUtils

StringUtils.substringAfter(id ,":"),

mstfdz
  • 2,616
  • 3
  • 23
  • 27
0

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 :.

Tavo
  • 3,087
  • 5
  • 29
  • 44
  • split method, thank you for your answer, I'll try it too :) Maybe better if it works for more than une `:`per line. – fselva May 18 '15 at 08:51