IDE can't guess what your null is. Whether it is String or Charset. You can try something like:
String encoding=null;
FileUtils.readLines(file, encoding);
But I think that wouldn't work since readLines method needs to know what encoding your file uses. So if for example your file uses UTF-8, you can write this
FileUtils.readLines(file, StandardCharsets.UTF_8);
Or you can try to use default charset, see this: How to Find the Default Charset/Encoding in Java?
And as Apache docs say, deprecated version readLines(File file) used default charset. You can write this to get an equivalent:
FileUtils.readLines(file, Charset.defaultCharset());
Answer from funbiscuit on Stack OverflowHere's how to do it with Guava:
List<String> lines = Files.readLines(new File("myfile.txt"), Charsets.UTF_8);
Reference:
Files.readLines(File, Charset)
Using Apache Commons IO, you can use FileUtils#readLines method. It is as simple as:
List<String> lines = FileUtils.readLines(new File("..."));
for (String line : lines) {
System.out.println(line);
}
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().