简体   繁体   中英

Read tab-delimited file in Java one “line” at a time

I have written code to read a tab-delimited file one line (row) at a time. I created he file from an Excel spreadsheet by saving it as a tab-delimited text file. Each row in the spreadsheet has 39 columns, which means 38 tabs. The purpose of this is to be able to wrap each of the 39 bits of data, including empty bits, in XML tags. However, this code a. prints every single piece of data in the spreadsheet one line at a time, I am having trouble with trying to access a specific item of data, which is essential. The first column is a user id, the twelfth column is a primary address line 1 and the 36 column is a patron note, for example. However, if I change the code below to get(55) I get an IndexOutOfBounds exception. If I ask for the first piece of data, get(0), the program lists every single piece of data in the entire file.

boolean resultFlag = false;
  try
   {   
     theScanner = new Scanner(new FileReader("C:\\WMS\\GGBTS_Patron_Data_20160317_V1-0.txt"));
   while (theScanner.hasNextLine())
   {
    patronRow = theScanner.next();
    itemArray = new ArrayList(Arrays.asList(patronRow.split("\t")));   
    for(int i=0; i<itemArray.size(); i++)
       {
        System.out.println(" -->"+itemArray.get(i));
       }        
   }
   resultFlag = true;
 }

What do I need to do to get the 39 elements of a single row and be able to refer to them by index number before going on to the next logical line? I do not know if Excel saves tab-delimited files with \\n\\r or the like or not. Help please. I'm somewhat hampered here because, although I was a programmer for many years, in my current situation, I am an academic reference librarian in a small library and there's no way to get IT support. i know programming better than our two IT guys anyway, who deal with operations, not coding. Thanks.

Ken

This line:

patronRow = theScanner.next();

Should be:

patronRow = theScanner.nextLine();

You want to get the whole line then split on \\t ...

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