简体   繁体   中英

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.

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); } 

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);
}

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);
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM