24 September 2009

Read files in Java

The source code below searches for all XML files in the specified folder and recursively searches in subfolders. The files are read as bytes and transformed to String. In this specific example the main goal is to read the entire file and transform it in a String to be processed, so there is not need to read the file line by line, what is probably more time consuming.


       /**
        * Main method used to test this class to read message in XML format from the
        * specified folder and to process it.
        * When launching this method a parameter can be used to specify the folder where
        * to search the files.
        *
        * @param args The folder name can be specified, otherwise the current folder is used.
        */
       public static void main(String[] args) {
              String folder = ".";
              if (args.length > 0 && args[0] != null && args[0].length() > 0) {
                     folder = args[0];
              }

              System.out.println("Searching in folder " + folder);
              findFiles(new File(folder));
       }


       /**
        * Finds all XML messages in the specified path, including sub-folders,
        *and process the file.
        *
        * @param file File to be read and transform in String.
        */
       private static void findFiles(File file) {
              File listFiles[] = file.listFiles();

              String type = "xml"; // Searches only for XML files
              int fileIndex = 0;

              while (fileIndex < listFiles.length) {
                     File currentFile = listFiles[fileIndex];
                     if (currentFile.isDirectory()) {
                           findFiles(currentFile); // Recursively find files in subfolders
                     } else if (currentFile.isFile() && currentFile.getName().endsWith(type)) {
                           try {
                                  System.out.println(currentFile.getPath()
                                                     + "length" + currentFile.length());
                                  SendMesg(getFileAsBytes(currentFile)); // Process file
                           } catch (IOException e) {
                                  e.printStackTrace();
                           }
                     }
                     fileIndex++;
              }

       }


       /**
        * Reads the specified file as an array of bytes and transforms it in a String.
        *
        * @param file File to be read and transform in String.
        * @return The message in String format.
        */
       private final static String getFileAsBytes(File file) throws IOException {
              BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
              byte[] bytes = new byte[(int) file.length()];
              bis.read(bytes);
              bis.close();
              return new String(bytes);
       }

No comments:

Post a Comment