Reading data into array from file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • SkyGenius
    New Member
    • Dec 2006
    • 13

    Reading data into array from file

    Hello, I am a new Java learner. I would like to develop one model by using Java. In that model, there are many files to read. I want to write a method in Java to read a file and store the data in array(s). Later, I just only call that method to read other files. Would you please help me to write a code to read the data in the following formats:

    First format (for example, separated by lines): store one column of the data in one array

    11.1
    22.2
    33.3
    ...

    Second format (for example, separated by spaces): store one column of the data in one array, so there are three arrays

    1.1 11.1 111.1
    2.2 22.2 222.2
    3.3 33.3 333.3
    ... ... ...
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    Originally posted by SkyGenius
    Hello, I am a new Java learner. I would like to develop one model by using Java. In that model, there are many files to read. I want to write a method in Java to read a file and store the data in array(s). Later, I just only call that method to read other files. Would you please help me to write a code to read the data in the following formats:

    First format (for example, separated by lines): store one column of the data in one array

    11.1
    22.2
    33.3
    ...

    Second format (for example, separated by spaces): store one column of the data in one array, so there are three arrays

    1.1 11.1 111.1
    2.2 22.2 222.2
    3.3 33.3 333.3
    ... ... ...
    Do you want to use one method to read both types of files?
    Store the values in ArrayList rather than an Array so you don't have to find the number of lines in the files first.

    Code:
     
    public static ArrayList readFile(String fileName) {
      String line = "";
      ArrayList data = new ArrayList();//consider using ArrayList<int>
      try {
       FileReader fr = new FileReader(fileName);
       BufferedReader br = new BufferedReader(fr);//Can also use a Scanner to read the file
       while((line = br.readLine()) != null) {
    	
    	data.add(line);
       }
      }
      catch(FileNotFoundException fN) {
       fN.printStackTrace();
      }
      catch(IOException e) {
       System.out.println(e);
      }
      return data;
     }
    For the second file you can make an ArrayList of ArrayList if you want to use the same method or an array of ArrayLists

    Comment

    • SkyGenius
      New Member
      • Dec 2006
      • 13

      #3
      Thanks for your help and comments. If possible, I would like to use two different methods to read the two different formats of the data files.

      Comment

      • r035198x
        MVP
        • Sep 2006
        • 13225

        #4
        Originally posted by SkyGenius
        Thanks for your help and comments. If possible, I would like to use two different methods to read the two different formats of the data files.
        You could write the second one along the lines of

        Code:
         
        public static ArrayList[] readFile2(String fileName) {
          String line = "";
          ArrayList[] data = new ArrayList[3];//consider using ArrayList<int>
          try {
           FileReader fr = new FileReader(fileName);
           BufferedReader br = new BufferedReader(fr);//Can also use a Scanner to read the file
           while((line = br.readLine()) != null) {
        	String[] theline = line.split(" ");
        	data[0].add(theline[0]);
        	data[1].add(theline[1]);
        	data[2].add(theline[2]);
           }
          }
          catch(FileNotFoundException fN) {
           fN.printStackTrace();
          }
          catch(IOException e) {
           System.out.println(e);
          }
          return data;
         }

        Comment

        • SkyGenius
          New Member
          • Dec 2006
          • 13

          #5
          Could you make it in a complete class that is ready to run? For example, there is two files for the first format (so there are two arrays) and one file for second format (so there are three arrays). I would like to get those arrays in double type and it is ready to use for computation. Then I would like to write the two arrays from the first format to one file with two columns (first column for first array and second column for second array) . The arrays from the second format are written in two files. First file is for the first array and second file is for the three arrays (I would like to reproduce the second format file).

          Comment

          • r035198x
            MVP
            • Sep 2006
            • 13225

            #6
            Originally posted by SkyGenius
            Could you make it in a complete class that is ready to run? For example, there is two files for the first format (so there are two arrays) and one file for second format (so there are three arrays). I would like to get those arrays in double type and it is ready to use for computation. Then I would like to write the two arrays from the first format to one file with two columns (first column for first array and second column for second array) . The arrays from the second format are written in two files. First file is for the first array and second file is for the three arrays (I would like to reproduce the second format file).
            Sorry I had gone out for a while.

            Have a go at it first and post some code then I can see if you need help

            Code:
             
            import java.io.*;
            import java.util.*;
            public class ReadFile {
             public static void main(String args[]) {
              // You put your logic here
             }
             public static ArrayList[] readFile2(String fileName) {
              String line = "";
              ArrayList[] data = new ArrayList[3];
              try {
               FileReader fr = new FileReader(fileName);
               BufferedReader br = new BufferedReader(fr);
               while((line = br.readLine()) != null) {
            	String[] theline = line.split(" ");
            	data[0].add(Double.parseDouble(theline[0]));
            	data[1].add(Double.parseDouble(theline[1]));
            	data[2].add(Double.parseDouble(theline[2]));
               }
              }
              catch(FileNotFoundException fN) {
               fN.printStackTrace();
              }
              catch(IOException e) {
               System.out.println(e);
              }
              return data;
             }
             public static ArrayList<Double> readFile(String fileName) {
              String line = "";
              ArrayList<Double> data = new ArrayList<Double>();
              try {
               FileReader fr = new FileReader(fileName);
               BufferedReader br = new BufferedReader(fr);
               while((line = br.readLine()) != null) {
            	data.add(Double.parseDouble(line));
               }
              }
              catch(FileNotFoundException fN) {
               fN.printStackTrace();
              }
              catch(IOException e) {
               System.out.println(e);
              }
              return data;
             }
            }

            Comment

            • SkyGenius
              New Member
              • Dec 2006
              • 13

              #7
              Please help to fix this code.

              Code:
              import java.io.*;
              import java.util.*;
              
              public class ReadingFile {
              
              public static void main(String args[]) {
              	// You put your logic here
              	int i,j;
              	int count1,count2;		// number of the array elements
              	
              	int maxSize1 = 100;		// max number of array elements
              	double[] dataArray1 = new double[maxSize1];
              	double[] dataArray2 = new double[maxSize1];
              	
              	int maxSize2 = 50;
              	double[] dataArray3 = new double[maxSize2];
              	double[] dataArray4 = new double[maxSize2];
              	double[] dataArray5 = new double[maxSize2];
              	
              	String fn1 = "file1.txt";
              	String fn2 = "file2.txt";
              	String fn3 = "file3.txt";
              	/* first format: file1.txt and file2.txt
              	   11.1
              	   22.2
              	   33.3
              	   ...
              	   
              	   second format: file3.txt
              	   1.1	11.1	111.1
              	   2.2	22.2	222.2
              	   3.3	33.3	333.3
              	   ...	...		...
              	   
              	 */
              	
              	
              	dataArray1 = readFile(fn1);	// I want to store the data from the first file
              	dataArray2 = readFile(fn2);	// I want to store the data from the second file
              		
              	dataArray3 = readFile(fn3);	// I want to store the data of first colunm of the third file
              	dataArray4 = readFile(fn3);	// I want to store the data of second colunm of the third file
              	dataArray5 = readFile(fn3);	// I want to store the data of third colunm of the third file
              	
              	// I want to write the data that I read to a file
              	FileWriter fout1 = new FileWriter("output1.txt");
              	FileWriter fout2 = new FileWriter("output2.txt");
              	
              	for (i=0; (i<count1); i++){
              		fout1.write(dataArray1[i]+" "+dataArray2[i]);	// I want to write to a file with two colonms
              		
              	}
              	fout1.close();
              	
              	for (j=0; (j<count2); j++){
              		fout2.write(dataArray3[j]+" "+dataArray4[j]+" "+dataArray4[j]);	// I want to write to reproduce the third file
              		
              	}
              	fout2.close();
              		
              }
              // I want to get count2(number of elements in each array) 
              public static ArrayList[] readFile2(String fileName) {
                String line = "";
                ArrayList[] data = new ArrayList[3];
                try {
                 FileReader fr = new FileReader(fileName);
                 BufferedReader br = new BufferedReader(fr);
                 while((line = br.readLine()) != null) {
              	String[] theline = line.split(" ");
              	data[0].add(Double.parseDouble(theline[0]));
              	data[1].add(Double.parseDouble(theline[1]));
              	data[2].add(Double.parseDouble(theline[2]));
                 }
                }
                catch(FileNotFoundException fN) {
                 fN.printStackTrace();
                }
                catch(IOException e) {
                 System.out.println(e);
                }
                return data;
               }
              //I want to get count1(number of elements of the array) 
               public static ArrayList<Double> readFile(String fileName) {
                String line = "";
                ArrayList<Double> data = new ArrayList<Double>();
                try {
                 FileReader fr = new FileReader(fileName);
                 BufferedReader br = new BufferedReader(fr);
                 while((line = br.readLine()) != null) {
              	data.add(Double.parseDouble(line));
                 }
                }
                catch(FileNotFoundException fN) {
                 fN.printStackTrace();
                }
                catch(IOException e) {
                 System.out.println(e);
                }
                return data;
               }
              }

              Comment

              • r035198x
                MVP
                • Sep 2006
                • 13225

                #8
                Code:
                 
                import java.io.*;
                import java.util.*; 
                public class ReadingFile1 {
                
                public static void main(String args[]) {
                 // You put your logic here
                
                 //Simply use ArrayList.size()
                 //int i,j;
                 //int count1,count2;  // number of the array elements
                
                 //int maxSize1 = 100;  not neccessary
                
                 //The methods are returning ArrayLists not arrays
                 ArrayList<Double> dataArray1 = new ArrayList<Double>();
                 ArrayList<Double> dataArray2 = new ArrayList<Double>();
                
                 //only one array is required here
                 ArrayList[] dataArray3 = new ArrayList[3];
                
                
                 //int maxSize2 = 50;
                 //double[] dataArray3 = new double[maxSize2];
                 //double[] dataArray4 = new double[maxSize2];
                 //double[] dataArray5 = new double[maxSize2];
                
                 String fn1 = "file1.txt";
                 String fn2 = "file2.txt";
                 String fn3 = "file3.txt";
                 /* first format: file1.txt and file2.txt
                	11.1
                	22.2
                	33.3
                	...
                
                	second format: file3.txt
                	1.1 11.1 111.1
                	2.2 22.2 222.2
                	3.3 33.3 333.3
                	... ...  ...
                
                  */
                
                
                 dataArray1 = readFile(fn1); // I want to store the data from the first file
                 dataArray2 = readFile(fn2); // I want to store the data from the second file
                 // call the other method here
                 dataArray3 = readFile2(fn3);
                
                
                 //dataArray3 = readFile(fn3); // I want to store the data of first colunm of the third file
                 //dataArray4 = readFile(fn3); // I want to store the data of second colunm of the third file
                 //dataArray5 = readFile(fn3); // I want to store the data of third colunm of the third file
                
                 // I want to write the data that I read to a file
                 //You must handle the possible IOEeceptions
                 try {
                  FileWriter fout1 = new FileWriter("output1.txt");
                  FileWriter fout2 = new FileWriter("output2.txt");
                  for (int i = 0; i < dataArray1.size(); i++){
                   fout1.write(dataArray1.get(i) + " " + dataArray2.get(i)); // I want to write to a file with two colonms
                  }
                  fout1.close();
                 }
                 catch(IOException iO) {
                  iO.printStackTrace();
                 }
                
                 //Make sure the first one is working first
                 //for (j=0; (j<count2); j++){
                 // fout2.write(dataArray3[j]+" "+dataArray4[j]+" "+dataArray4[j]); // I want to write to reproduce the third file
                
                 //}
                 //fout2.close();
                
                }
                // I want to get count2(number of elements in each array)
                public static ArrayList[] readFile2(String fileName) {
                  String line = "";
                  ArrayList[] data = new ArrayList[3];
                  try {
                   FileReader fr = new FileReader(fileName);
                   BufferedReader br = new BufferedReader(fr);
                   while((line = br.readLine()) != null) {
                 String[] theline = line.split(" ");
                 data[0].add(Double.parseDouble(theline[0]));
                 data[1].add(Double.parseDouble(theline[1]));
                 data[2].add(Double.parseDouble(theline[2]));
                   }
                  }
                  catch(FileNotFoundException fN) {
                   fN.printStackTrace();
                  }
                  catch(IOException e) {
                   System.out.println(e);
                  }
                  return data;
                 }
                //I want to get count1(number of elements of the array)
                 public static ArrayList<Double> readFile(String fileName) {
                  String line = "";
                  ArrayList<Double> data = new ArrayList<Double>();
                  try {
                   FileReader fr = new FileReader(fileName);
                   BufferedReader br = new BufferedReader(fr);
                   while((line = br.readLine()) != null) {
                 data.add(Double.parseDouble(line));
                   }
                  }
                  catch(FileNotFoundException fN) {
                   fN.printStackTrace();
                  }
                  catch(IOException e) {
                   System.out.println(e);
                  }
                  return data;
                 }
                }
                Have a look at the corrections and try and see if it works.
                If there's any line you don't ubderstand there you might as well ask

                Comment

                • SkyGenius
                  New Member
                  • Dec 2006
                  • 13

                  #9
                  Thanks so much for your help. I can successfully run the first method (readFile). But I still cannot run the second method (readFile2). It seems there are problems in declaration of dataArray3, calling method readFile2 and in the method itself.

                  Comment

                  • r035198x
                    MVP
                    • Sep 2006
                    • 13225

                    #10
                    Originally posted by SkyGenius
                    Thanks so much for your help. I can successfully run the first method (readFile). But I still cannot run the second method (readFile2). It seems there are problems in declaration of dataArray3, calling method readFile2 and in the method itself.
                    You'll have to be more specific. What problems are these compile time errors?

                    Comment

                    • SkyGenius
                      New Member
                      • Dec 2006
                      • 13

                      #11
                      It shows this in console:
                      Exception in thread "main" java.lang.NullP ointerException
                      at fileReading.rea dFile2(fileRead ing.java:95)
                      at fileReading.mai n(fileReading.j ava:49)

                      Comment

                      • r035198x
                        MVP
                        • Sep 2006
                        • 13225

                        #12
                        Originally posted by SkyGenius
                        It shows this in console:
                        Exception in thread "main" java.lang.NullP ointerException
                        at fileReading.rea dFile2(fileRead ing.java:95)
                        at fileReading.mai n(fileReading.j ava:49)
                        Yep I had not initialised the array elements. Change the method to


                        Code:
                         
                        public static ArrayList[] readFile2(String fileName) {
                          String line = "";
                          ArrayList[] data = new ArrayList[3];
                          for(int i = 0; i < 3; i++) {
                           data[i] = new ArrayList<Double>();
                          }
                          try {
                           FileReader fr = new FileReader(fileName);
                           BufferedReader br = new BufferedReader(fr);
                           while((line = br.readLine()) != null) {
                         String[] theline = line.split(" ");
                         data[0].add(Double.parseDouble(theline[0]));
                         data[1].add(Double.parseDouble(theline[1]));
                         data[2].add(Double.parseDouble(theline[2]));
                           }
                          }
                          catch(FileNotFoundException fN) {
                           fN.printStackTrace();
                          }
                          catch(IOException e) {
                           System.out.println(e);
                          }
                          return data;
                         }
                        and test it.

                        May I add that you could have realised that yourself.

                        Comment

                        • SkyGenius
                          New Member
                          • Dec 2006
                          • 13

                          #13
                          Thanks so much. It is running!

                          Comment

                          • r035198x
                            MVP
                            • Sep 2006
                            • 13225

                            #14
                            Originally posted by SkyGenius
                            Thanks so much. It is running!
                            Anytime Sky.

                            Comment

                            • SkyGenius
                              New Member
                              • Dec 2006
                              • 13

                              #15
                              I can run the class. But when I use "space delimited format" for an input file, I could not write all read data to a file. The read data are displayed normally when I write it to the console.

                              Code:
                              for (int i = 0; i < inWL[0].size(); i++) {
                              	System.out.println(inWL[0].get(i) + " " + inWL[1].get(i));
                              	fout1.write(inWL[0].get(i) + " " + inWL[1].get(i) + "\n");
                              }
                              By the way, how could I modify my code to read a file with "tab delimited format"?

                              Code:
                              public static ArrayList[] readFile2(String fileName) {
                              	       / * File Structure:
                              		 * 	1.1 11.1
                              		 * 	2.2 22.2
                              		 *  3.3 33.3
                              		 * 	... ... 
                              		 */	
                              			String line = " ";
                              			ArrayList[] data = new ArrayList[2];
                              			
                              			//for(int i = 0; i < 2; i++) {
                              			data[0] = new ArrayList<String>();
                              			data[1] = new ArrayList<Double>();
                              			//}
                              			
                              			try {
                              				FileReader fr = new FileReader(fileName);
                              				BufferedReader br = new BufferedReader(fr);
                              				while((line = br.readLine()) != null) {
                              					String[] theline = line.split(" ");
                              					data[0].add(theline[0]);
                              					data[1].add(Double.parseDouble(theline[1]));
                              					
                              					//System.out.println(data[0] + "   " + data[1]);
                              				}
                              			}
                              			catch(FileNotFoundException fN) {
                              				fN.printStackTrace();
                              			}
                              			
                              			catch(IOException e) {
                              				System.out.println(e);
                              			}
                              			
                              			return data;
                              
                              		} //end readFile2 method

                              Comment

                              Working...