Rukku
Rukku

Reputation: 81

Split or parse a string in java

I've a file sample.txt and its content will be

12345#ABCDEF#12345#ADCDE

12345#ABCDEF#12345#ADCDE

FHJI

KLMN

OPQ

12345#ABCDEF#12345#ADCDE

Now I want to split/parse the file based upon #

My output should be

Test1 : 12345

Test2 : ABCDEF

Test3 : 12345

Test4 : ADCDE

Test1 : 12345

Test2 : ABCDEF

Test3 : 12345

Test4 : ADCDE

        FHJI

        KLMN

        OPQ

Test1 : 12345

Test2 : ABCDEF

Test3 : 12345

Test4 : ADCDE

I wrote like below

String sCurrentLine;
String Test1, Test2, Test3, Test4 = "";

br = new BufferedReader(new FileReader("D:\\sample.txt"));

while ((sCurrentLine = br.readLine()) != null) {
    String line[] = sCurrentLine.split("#");
    Test1 = line[0];
    Test2 = line[1];
    Test3 = line[2]
    Test4 = line[3];
    System.out.println(Test1+"\n"+Test2+"\n"+Test3+"\n"+Test4);
    }

It is working if its only one line or sample.txt haslike below

12345#ABCDEF#12345#ADCDE

12345#ABCDEF#12345#ADCDE

It is not working for top declared example.

Please help me.

Thank you.

Upvotes: 0

Views: 116

Answers (3)

CloudPotato
CloudPotato

Reputation: 1275

You have to check if it is possible to split your string in the amount of parts you want

String sCurrentLine;
String Test1 = "";
String Test2= "";
String Test3= "";
String Test4 = "";

br = new BufferedReader(new FileReader("D:\\sample.txt"));

while ((sCurrentLine = br.readLine()) != null) {
    String line[] = sCurrentLine.split("#");
    if (line.length >= 4) {
        Test1 = line[0];
        Test2 = line[1];
        Test3 = line[2]
        Test4 = line[3];
    } else {
         Test4 = line[0] + "\n";
    }
    System.out.println(Test1+"\n"+Test2+"\n"+Test3+"\n"+Test4);
}

Upvotes: 1

joc
joc

Reputation: 1446

This line

String line[] = sCurrentLine.split("#");

Will split the string into n fragments, if there is no # present in the line you parse will crash. In order to fix the problem, you have 2 options:

  • Fix the file
  • Check array's lenght before assigning to avoid a AIOOBE

    while ((sCurrentLine = br.readLine()) != null) {
        String line[] = sCurrentLine.split("#");
    
        Test1 = line[0];
        Test2 = line.lenght > 1 ? line[1] : "";
        Test2 = line.lenght > 2 ? line[2] : "";
        Test2 = line.lenght > 3 ? line[3] : "";
    
        System.out.println(Test1+"\n"+Test2+"\n"+Test3+"\n"+Test4);
     }
    

Upvotes: 1

Hasson
Hasson

Reputation: 1914

Do something like this, to check that you have enough segments in your string.

String sCurrentLine;
String Test1, Test2, Test3, Test4 = "";

br = new BufferedReader(new FileReader("D:\\sample.txt"));

while ((sCurrentLine = br.readLine()) != null) {

  String line[] = sCurrentLine.split("#");
  if(line.length >= 4){
    Test1 = line[0];
    Test2 = line[1];
    Test3 = line[2]
    Test4 = line[3];
  }
    System.out.println(Test1+"\n"+Test2+"\n"+Test3+"\n"+Test4);
}

Upvotes: 0

Related Questions