Friday, 24 December 2010

Read a Text File from Resource JAR or Disk (Override resources with a custom file)

this sample shows how to implement a read text file in Java, the Program will first try to load file from resource jar (classes in path) and if it could not find it, then load it from given path on disk.
this is very useful if you want to implement a solution to override a resource with a customized one.

here is the program:



public class LoadFile {

    public void doLoadFile(final String fileNamethrows IOException {
        InputStream inputStream;


        //try to load file from disk
        try {
            inputStream = new FileInputStream(fileName);
        }
        catch (FileNotFoundException fe) {
            //failed, so try to load it from resources in class path
            inputStream = LoadFile.class.getClassLoader().getResourceAsStream(fileName);
            if (inputStream == null)
                throw new FileNotFoundException("could not find file: " + fileName);
        }

        // Get the object of InputStreamReader
        final InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        final BufferedReader bufferReader = new BufferedReader(inputStreamReader);

        String strLine;
        while ((strLine = bufferReader.readLine()) != null) {
            // Print the content on the console
            System.out.println(strLine);
        }

        // Close the input stream
        inputStreamReader.close();
    }
}


1 comment: