Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file from classpath with Java 7 NIO

I've googled around for quite a while for this, but all the results point to pre-Java 7 NIO solutions. I've used the NIO stuff to read in files from the a specific place on the file system, and it was so much easier than before (Files.readAllBytes(path)). Now, I'm wanting to read in a file that is packaged in my WAR and on the classpath. We currently do that with code similar to the following:

Input inputStream = this.getClass().getClassLoader().getResourceAsStream(fileName);
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

/* iterate through the input stream to get all the bytes (no way to reliably find the size of the 
 *     file behind the inputStream (see http://docs.oracle.com/javase/6/docs/api/java/io/InputStream.html#available()))
 */
int byteInt = -1;
try
{
    byteInt = inputStream.read();
    while (byteInt != -1)
    {
        byteStream.write(byteInt);
        byteInt = inputStream.read();
    }

    byteArray = byteStream.toByteArray();
    inputStream.close();
    return byteArray;
}
catch (IOException e)
{
    //...
}

While this works, I was hoping there was an easier/better way to do this with the NIO stuff in Java 7. I'm guessing I'll need to get a Path object that represents this path on the classpath, but I'm not sure how to do that.

I apologize if this is some super easy thing to do. I just cannot figure it out. Thanks for the help.

like image 441
dnc253 Avatar asked Feb 04 '13 17:02

dnc253


People also ask

How do you load properties file from resources folder in Java?

In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass(). getClassLoader().

How do I give path to ClassPathResource?

Map<String, Object> env = new HashMap<>(); try (FileSystem fs = FileSystems. newFileSystem(uri, env)) { Path path = fs. getPath("/path/myResource"); try (Stream<String> lines = Files. lines(path)) { .... } }


1 Answers

This works for me.

import java.nio.file.Files;
import java.nio.file.Paths;

// fileName: foo.txt which lives under src/main/resources
public String readFileFromClasspath(final String fileName) throws IOException, URISyntaxException {
    return new String(Files.readAllBytes(
                Paths.get(getClass().getClassLoader()
                        .getResource(fileName)
                        .toURI())));
}
like image 77
shreyas Avatar answered Oct 05 '22 17:10

shreyas