Shehlina
Shehlina

Reputation: 19

Parse Text file in Java

I am trying to read input from a text file(read only numbers in arraylist). My text file looks like this containing numbers(146,7,-1,-2,3).It looks like this actually: HEADER 1467-1-23

Now,when I put HEADER string in the file,my code would not read the first number which is 146 in my case and starts with the second number "7".However,when the string HEADER is not there,146 is also read which is obviously what I want.My code is this:

String pathToWrite="C:\\Users\\User\\Desktop\\Hello.txt";

 FileReader fr=new FileReader(pathToWrite);
     BufferedReader bufferedReader=new BufferedReader(fr);

     String aLine=null;
     int numberOfLine=0;
    List<Integer> list = new ArrayList<Integer>();
    List<Integer> list2 = new ArrayList<Integer>();


    while((aLine=bufferedReader.readLine()) != null )
     {
            if(numberOfLine > 1) //since header lies in first line,I want to skip that line
            {
             list.add(Integer.parseInt(aLine));
            }
             numberOfLine++;


     }

Want suggestions about how I can change the code to read the first number too? Thanks in advance

Upvotes: 1

Views: 148

Answers (5)

Vishwajit R. Shinde
Vishwajit R. Shinde

Reputation: 475

Change your if statment or numberOfLine=0; variable. You can do one of the following

Case 1:

int numberOfLine=0;

while((aLine=bufferedReader.readLine()) != null )
     {
            if(numberOfLine >= 1) //since header lies in first line,I want to skip that line
            {
             list.add(Integer.parseInt(aLine));
            }
             numberOfLine++;


     }

============================================================
Case 2:

int numberOfLine=1;

while((aLine=bufferedReader.readLine()) != null )
     {
            if(numberOfLine > 1) //since header lies in first line,I want to skip that line
            {
             list.add(Integer.parseInt(aLine));
            }
             numberOfLine++;


     }

Upvotes: 0

Gwalk
Gwalk

Reputation: 209

The file looks like this?

HEADER 1467-1-23

if like this, give an example of second line. Because this is one line which id = 0; or like this?

HEADER
1467-1-23
...

Upvotes: 0

botchniaque
botchniaque

Reputation: 5084

Typical > vs. >= typo. Just change if(numberOfLine > 1) to if(numberOfLine >= 1).

Upvotes: 0

SleepyX667
SleepyX667

Reputation: 690

The file looks like:

HEADER
146
7
1
23

? Then try if(numberOfLine > 0). It's because you are beginning counting from zero.

Upvotes: 1

DeepInJava
DeepInJava

Reputation: 1951

Split your line using String's split function

String [] numbers = aLine.split(",");

This will give you all numbers in an array.

I hope it resolves your query !!!

Upvotes: 0

Related Questions