简体   繁体   中英

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

The file looks like:

HEADER
146
7
1
23

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

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 !!!

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

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

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++;


     }

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