Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a file from classpath without external dependencies?

Is there a one-liner in Scala to read a file from classpath without using external dependencies, e.g. commons-io?

IOUtils.toString(getClass.getClassLoader.getResourceAsStream("file.xml"), "UTF-8") 
like image 502
mbdev Avatar asked May 25 '11 08:05

mbdev


People also ask

What API method can be used to read a file in the classpath?

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 load resources from classpath?

We can either load the file(present in resources folder) as inputstream or URL format and then perform operations on them. So basically two methods named: getResource() and getResourceAsStream() are used to load the resources from the classpath. These methods generally return the URL's and input streams respectively.

What are classpath resources?

Classpath in Java is not only used to load . class files, but also can be used to load resources e.g. properties files, images, icons, thumbnails, or any binary content. Java provides API to read these resources as InputStream or URL.


1 Answers

val text = io.Source.fromInputStream(getClass.getResourceAsStream("file.xml")).mkString 

If you want to ensure that the file is closed:

val source = io.Source.fromInputStream(getClass.getResourceAsStream("file.xml")) val text = try source.mkString finally source.close() 
like image 187
dacwe Avatar answered Sep 23 '22 09:09

dacwe