Search code examples
javaarraysfilefile-iobufferedinputstream

Reading in files from array of files


I'm new to Java and am attempting to read in files from java, but I can't seem to figure out why this is happening. I'm getting IOExceptions and errors when I'm trying to read in the files. I just don't like how BufferedReader handles reading in files. I don't understand what it is attempting to do. I heard a friend mention BufferedInputStream to read in files and files from an array of files.

Question: How can I correctly, from the array of files, read in multiple files?

Comment: I realize there is no code which looks like no effort, but no matter how long I stare at java documentation, it just doesn't make sense to me. I was wondering if someone could make an example and I could study that code for BufferedStreams. From the little research I did do, I like the look of it better, and the description is better, but how do I actually do it?


Solution

  • Use my Generic readFile class. I modified it to read an array of files. It used BufferedInputStream, which needs a FileInputStream. DataInputStream takes a BufferedInputStream as a parameter, so you also need a DataInputStream. I'm not sure how to directly answer your question...its rather general but I hope this helps you.

    import java.io.*;
    
    public class Foo 
    {
    
        public void readFile(File[] myFile) 
        {
    
           FileInputStream fiStream = null;
           BufferedInputStream biStream = null;
           DataInputStream diStream = null;
           foreach(File file in myFile)
           {
    
               try 
               {
                   fiStream = new FileInputStream(file);
    
                   biStream = new BufferedInputStream(fiStream);
                   diStream = new DataInputStream(biStream);
    
                   while (dis.available() != 0) 
                   {
                    System.out.println(dis.readLine());
                   }
    
               } catch (IOException e)
               {
                   e.printStackTrace();
               } finally 
               {
                  try 
                  {
                      fiStream.close();
                      biStream.close();
                      diStream.close();
                  } catch (IOException ex)
                  {
                      ex.printStackTrace();
                  }
               }
           }
        }
    }