I have to read a file containing a list of strings. I'm trying to follow the advice in this post. Both solutions require using FileUtils.readLines
, but use a String
, not a File
as the parameter.
Set<String> lines = new HashSet<String>(FileUtils.readLines("foo.txt"));
I need a File
.
This post would be my question, except the OP was dissuaded from using files entirely. I need a file if I want to use the Apache method, which is the my preferred solution to my initial problem.
My file is small (a hundred lines or so) and a singleton per program instance, so I do not need to worry about having another copy of the file in memory. Therefore I could use more basic methods to read the file, but so far it looks like FileUtils.readLines
could be much cleaner. How do I go from resource to file.
The getResource() method of java. lang. Class class is used to get the resource with the specified resource of this class. The method returns the specified resource of this class in the form of URL object.
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().
Apache Commons-IO has an IOUtils class as well as a FileUtils, which includes a readLines
method similar to the one in FileUtils.
So you can use getResourceAsStream
or getSystemResourceAsStream
and pass the result of that to IOUtils.readLines
to get a List<String>
of the contents of your file:
List<String> myLines = IOUtils.readLines(ClassLoader.getSystemResourceAsStream("my_data_file.txt"));
I am assuming the file you want to read is a true resource on your classpath, and not simply some arbitrary file you could just access via new File("path_to_file");
.
Try the following using ClassLoader
, where resource
is a String
representation of the path to your resource file in your class path.
Valid String
values for resource
can include:
"foo.txt"
"com/company/bar.txt"
"com\\company\\bar.txt"
"\\com\\company\\bar.txt"
and path is not limited to com.company
Relevant code to get a File
not in a JAR:
File file = null;
try {
URL url = null;
ClassLoader classLoader = {YourClass}.class.getClassLoader();
if (classLoader != null) {
url = classLoader.getResource(resource);
}
if (url == null) {
url = ClassLoader.getSystemResource(resource);
}
if (url != null) {
try {
file = new File(url.toURI());
} catch (URISyntaxException e) {
file = new File(url.getPath());
}
}
} catch (Exception ex) { /* handle it */ }
// file may be null
Alternately, if your resource is in a JAR, you will have to use Class.getResourceAsStream(resource);
and cycle through the file using a BufferedReader
to simulate the call to readLines()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With