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 Overflow
🌐
Kodejava
kodejava.org › how-do-i-read-text-file-content-line-by-line-using-commons-io
How do I read text file content line by line to a List of Strings using Commons IO? - Learn Java by Examples
October 2, 2023 - We use FileUtils.readLines() method to read the contents line by line and return the result as a List of Strings. package org.kodejava.commons.io; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import ...
🌐
Program Creek
programcreek.com › java-api-examples
org.apache.commons.io.FileUtils#readLines
public static List<HyperParameterScopeItem> read(final String configFilePath) { final File file = new File(configFilePath); List<String> lines; try { lines = FileUtils.readLines(file, Charsets.UTF_8); } catch (final IOException e) { throw new IllegalStateException(e); } final List<HyperParameterScopeItem> result = Lists.newArrayList(); for (final String line : lines) { final String[] segments = StringUtils.split(line, ','); final List<String> values = Lists.newArrayList(); for (int i = 1; i < segments.length; ++i) { values.add(segments[i]); } final HyperParameterScopeItem item = new HyperParameterScopeItem(segments[0], values); result.add(item); } return result; }
🌐
Java2s
java2s.com › example › java-api › org › apache › commons › io › fileutils › readlines-2-2.html
Example usage for org.apache.commons.io FileUtils readLines
From source file:com.yoncabt.abys.core.util.EBRConf.java · private void reload() { // 2 defa almasn buras synchronized (reloadLock) { File confFile = getConfFile(); Map<String, String> tmp = new HashMap<>(); if (confFile.exists() && confFile.isFile() && confFile.canRead()) { lastModified = confFile.lastModified(); try { List<String> lines = FileUtils.readLines(confFile, "utf-8"); for (String line : lines) { if (StringUtils.isBlank(line) || line.trim().charAt(0) == '#') { continue; }/*from w w w.
🌐
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
🌐
ZetCode
zetcode.com › java › fileutils
Apache FileUtils - managing files in Java with Apache FileUtils
January 27, 2024 - A file can be read into a string with FileUtils.readFileToString or into a collection of strings with FileUtils.readLines. ... blue, tank, robot, planet, wisdom, cherry, chair, pen, keyboard, tree, forest, plant sky, movie, white, colour, music, dog, cat · We have this text file located in src/main/resources directory. ... package com.zetcode; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.List; import org.apache.commons.io.FileUtils; public class ReadFileEx { public static void main(String[] args) throws IOException { File myfile =
🌐
RoseIndia
roseindia.net › java › apache-commons-io-library-read-file-line-by-line.shtml
Example code of reading file line by line in Java with Apache Commons IO library
package net.roseindia; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.List; import org.apache.commons.io.FileUtils; public class ApacheCommonsReadFile { public static void main(String[] args) { try { File f = new File("data.txt"); BufferedReader b = new BufferedReader(new FileReader(f)); System.out.println("Apache commons read file line by line example"); List<String> lines = FileUtils.readLines(f, "UTF-8"); for (String line : lines) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } }
Find elsewhere
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › java read a file line by line
Java Read a File Line by Line
August 22, 2023 - // With LineProcessor ... Apache Commons IO library has FileUtils class that provides a single statement solution for reading the file content in lines....
🌐
Xing's Blog
xinghua24.github.io › Java › Java-Read-Files
Reading a File in Java | Xing's Blog
April 18, 2021 - ... To use FileUtils or IOUtils ... of a file into a string using the specified charset. We can also use FileUtils.readLines method to read lines and then concatenate all the lines together....
🌐
Javadevcentral
javadevcentral.com › apache commons fileutils – file operations
Apache Commons FileUtils – File Operations | Java Developer Central
August 10, 2020 - Now we will learn how to read file contents using Apache Commons FileUtils. The readLines method reads the file contents and returns a list of string. Each string is a line in the file.
🌐
Javadoc.io
javadoc.io › static › org.apache.commons › commons-io › 1.3.2 › org › apache › commons › io › FileUtils.html
FileUtils (Commons IO 1.3.2 API)
public static java.util.List readLines(java.io.File file) throws java.io.IOException · Reads the contents of a file line by line to a List of Strings using the default encoding for the VM. The file is always closed. Parameters: file - the file to read, must not be null ·
Top answer
1 of 3
12

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"));
2 of 3
2

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().

🌐
Javadoc.io
javadoc.io › static › commons-io › commons-io › 1.2 › org › apache › commons › io › FileUtils.html
FileUtils
public static java.util.List readLines(java.io.File file, java.lang.String encoding) throws java.io.IOException · Reads the contents of a file line by line to a List of Strings. The file is always closed. There is no readLines method without encoding parameter because the default encoding ...
🌐
Eduardo Figueiredo
homepages.dcc.ufmg.br › ~andrehora › examples › org.apache.commons.io.IOUtils.readLines.4.html
org.apache.commons.io.IOUtils.readLines
File file1; File file2; InputStream inputStream; OutputStream outputStream; // copy one file into another FileUtils.copyFile(file1, file2); IOUtils.copy(inputStream, outputStream); // read a file into a String String s1 = FileUtils.readFileToString(file1); String s2 = IOUtils.toString(inputStream); // read a file into a list of Strings, one item per line List<String> l1 = FileUtils.readLines(file1); List<String> l2 = IOUtils.readLines(inputStream); // put this in your finally() clause after manipulating streams IOUtils.closeQuietly(inputStream); // return the list of xml and text files in the specified folder and any subfolders Collection<File> c1 = FileUtils.listFiles(file1, { "xml", "txt" }, true); // copy one folder and its contents into another FileUtils.copyDirectoryToDirectory(file1, file2); // delete one folder and its contents FileUtils.deleteDirectory(file1); main
🌐
Java Tips
javatips.net › api › org.apache.commons.io.fileutils
Java Examples for org.apache.commons.io.FileUtils
private static String findVersion() { File appLayerBuildGradleFile = new File(new FoldersLocator().getConstellioWebappFolder(), "build.gradle"); try { List<String> appLayerBuildGradleFileLines = FileUtils.readLines(appLayerBuildGradleFile); for (int i = 0; i < appLayerBuildGradleFileLines.size(); i++) { String line = appLayerBuildGradleFileLines.get(i); if (line.contains("version = ")) { int firstQuote = line.indexOf("'"); int secondQuote; if (firstQuote == -1) { firstQuote = line.indexOf("\""); secondQuote = line.indexOf("\"", firstQuote + 1); } else { secondQuote = line.indexOf("'", firstQuote + 1); } return line.substring(firstQuote + 1, secondQuote); } } return null; } catch (IOException e) { throw new RuntimeException(e); } }
Top answer
1 of 9
378

Yes, you can do this in one line (though for robust IOException handling you wouldn't want to).

String content = new Scanner(new File("filename")).useDelimiter("\\Z").next();
System.out.println(content);

This uses a java.util.Scanner, telling it to delimit the input with \Z, which is the end of the string anchor. This ultimately makes the input have one actual token, which is the entire file, so it can be read with one call to next().

There is a constructor that takes a File and a String charSetName (among many other overloads). These two constructor may throw FileNotFoundException, but like all Scanner methods, no IOException can be thrown beyond these constructors.

You can query the Scanner itself through the ioException() method if an IOException occurred or not. You may also want to explicitly close() the Scanner after you read the content, so perhaps storing the Scanner reference in a local variable is best.

See also

  • Java Tutorials - I/O Essentials - Scanning and formatting

Related questions

  • Validating input using java.util.Scanner - has many examples of more typical usage

Third-party library options

For completeness, these are some really good options if you have these very reputable and highly useful third party libraries:

Guava

com.google.common.io.Files contains many useful methods. The pertinent ones here are:

  • String toString(File, Charset)
    • Using the given character set, reads all characters from a file into a String
  • List<String> readLines(File, Charset)
    • ... reads all of the lines from a file into a List<String>, one entry per line

Apache Commons/IO

org.apache.commons.io.IOUtils also offer similar functionality:

  • String toString(InputStream, String encoding)
    • Using the specified character encoding, gets the contents of an InputStream as a String
  • List readLines(InputStream, String encoding)
    • ... as a (raw) List of String, one entry per line

Related questions

  • Most useful free third party Java libraries (deleted)?
2 of 9
227

From Java 7 (API Description) onwards you can do:

new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);

Where filePath is a String representing the file you want to load.