By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,800 Members | 1,300 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,800 IT Pros & Developers. It's quick & easy.

Read a multiple file textfile with strings and doubles and input info to database

P: 1
I have a textfile that I need to read each line separated by \n

Every 3 lines I need to reset the array

The textfile may contain 100-1000 lines and every 3rd line is a double while the rest are strings, then I need to take each cluster of 3 lines and input that into a database.

I have the database connection, I can read the entire file, I just can't figure out how to break the file into clusters of 3 lines

So something like
Array[0] = Cluster1 String1
Array[1] = Cluster1 String2
Array[2] = Cluster1 Double
Array[0] = Cluster2 String1
Array[1] = Cluster2 String2
Array[2] = Cluster2 Double

Here is what I have so far, which will output the whole file


Expand|Select|Wrap|Line Numbers
  1. public void test()
  2.     {try
  3.         {
  4.             // Open the file that is the first 
  5.             // command line parameter
  6.             FileInputStream fstream = new FileInputStream(file);
  7.             // Get the object of DataInputStream
  8.             BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
  9.             String strLine;                        
  10.  
  11.             ArrayList<String> lineList = new ArrayList<String>();    // create an arraylist populated by lines in the textfile
  12.             String thisLine = br.readLine();
  13.  
  14.             while (thisLine != null) {
  15.                 lineList.add(thisLine);
  16.                 thisLine = br.readLine();
  17.             }
  18.  
  19.             // used to output the method results as a test
  20.             // comment this out before finalizing
  21.             int w = 0;
  22.             for (String testLine : lineList) {    // enhanced for loop
  23.                 System.out.println("Line " + w + ": " + testLine);
  24.                 w++;
  25.             }
  26.                 fstream.close();
  27.             }catch (Exception e){//Catch exception if any
  28.             System.err.println("Error: " + e);
  29.         }
  30.     }
Mar 26 '13 #1
Share this Question
Share on Google+
1 Reply


10K+
P: 13,264
Use a FileReader instead of FileInputStream for reading character files.

Declare a variable before the loop and increment it for every read. Reset it to zero every time it reaches 3.
Mar 26 '13 #2

Post your reply

Sign in to post your reply or Sign up for a free account.