javaarraylistread-text

Star * delimiter txt file column is returning multiple times column value when stored in Array List


I have star * delimiter file that finally I need to store in the Array after splitting * delimiter where it is storing value in the array and printing column however it is continuously printing same column value again and again.

Note: There are 60 columns in the txt file.

Following is my code:

static String[] arraylist;

String st;
            BufferedReader Br = null;


            File objFile = new File("C://DATA//File.txt");

            Br = new BufferedReader(new FileReader(objFile));

            LineNumberReader lineNumberReader = new LineNumberReader(new FileReader(objFile));
            lineNumberReader.skip(Long.MAX_VALUE);
            int lines = lineNumberReader.getLineNumber();


            System.out.println("Total Rows in the File : " + lines);

            List<String> lis = new ArrayList<String>();

            while ((st = Br.readLine()) != null) {

                arraylist = st.split("\\*");

                for (int i = 0; i < arraylist.length; i++) {

                    lis.add(arraylist[1]);
                    lis.add("\n");

                    System.out.println("List value are " +lis);

                }

            }


            Br.close();

Following is column sample: (Similarly there are 60 columns in this file)

*ABC*08*31444*XYZ*1234*OLNBHJK*^TGJF54DFG908
*ABC*08*66657*XYZ*1234*OLNBHJK*^TGJF54DFG908
*ABC*08*33161*XYZ*1234*OLNBHJK*^TGJF54DFG908
*ABC*08*55771*XYZ*1234*OLNBHJK*^TGJF54DFG908
*ABC*08*20605*XYZ*1234*OLNBHJK*^TGJF54DFG908
*ABC*08*26471*XYZ*1234*OLNBHJK*^TGJF54DFG908
*ABC*08*85608*XYZ*1234*OLNBHJK*^TGJF54DFG908
*ABC*08*57735*XYZ*1234*OLNBHJK*^TGJF54DFG908
*ABC*08*46844*XYZ*1234*OLNBHJK*^TGJF54DFG908
*ABC*08*57823*XYZ*1234*OLNBHJK*^TGJF54DFG908
*ABC*08*31249*XYZ*1234*OLNBHJK*^TGJF54DFG908
*ABC*08*32394*XYZ*1234*OLNBHJK*^TGJF54DFG908
*ABC*08*46166*XYZ*1234*OLNBHJK*^TGJF54DFG908
*ABC*08*46167*XYZ*1234*OLNBHJK*^TGJF54DFG908
*ABC*08*43108*XYZ*1234*OLNBHJK*^TGJF54DFG908
*ABC*08*43110*XYZ*1234*OLNBHJK*^TGJF54DFG908

I want to print 2nd column only one time: For Example:

ABC
ABC
ABC
ABC
ABC
ABC
ABC
ABC
ABC
ABC
ABC
ABC
ABC
ABC
ABC
ABC

Solution

  • All you need to do is to print the second item in the array. Note that the array index start at 0.

    while ((st = Br.readLine()) != null) {
        arraylist = st.split("\\*");
        System.out.println("List value are " + arraylist[1]);
    }