Java File cookbook

By Maurizio Farina | Posted on August 2017

How to create a String from a File?

The following code is built for ListFeeds.com. To avoid to use CharSet in the methods parameter is possible to use the Java VM CharSet default with the following method:

1
Charset.defaultCharset()

The simplest way:

1
2
3
4
public static String getStringFromFile(String path, Charset encoding) throws IOException {
    byte[] encoded = Files.readAllBytes(Paths.get(path));
    return new String(encoded, encoding);
}

Read file saving memory avoiding to allocate (and encoding) all content of file

1
2
3
public static List<String> getLinesFromFile(String path, Charset encoding) throws IOException {
    return Files.readAllLines(Paths.get(path), encoding);
}

How to create a String from a File using Apache Commons IO?

One of reasons for using Apache Commons is due to the best use of memory; the library internally uses the streams classes so avoiding to allocate large amounts of memory. If there was no the Apache Commons IO we should use streams directly in the methods seen before (reinventing the wheel):

Before we need to add Apache Commons IO libraries to our pom file:

1
2
3
4
5
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>

The simplest way is to use FileUtils:

1
FileUtils.readFileToString(file, encoding)

FileUtils.readFileToString internally uses IOUtils so we will base our methods directly on this class:

1
2
3
4
5
6
7
8
public static String getStringFromLargeFile(String path, Charset encoding) throws IOException
{
    InputStream is = new FileInputStream(path);
    String txt = IOUtils.toString(is, encoding);
    is.close();

    return txt;
}

Read file from relative path

All methods above uses abssoulte path. Sometimes is useful to read file from local path. Be careful about "path" parameter:

./yourpath : this means local path starting from your namespace /yourpath: this means local path starting from the root of your namespace

1
2
3
4
5
6
7
8
public static String getStringFromRelativeFilePath(String path, Charset encoding) throws IOException
{
    InputStream is = FileHelper.class.getResourceAsStream(path);
    String txt = IOUtils.toString(is, encoding);
    is.close();

    return txt;
}

How to create a file from String?

1
2
3
4
5
public static void  writeFileFromString(String path, String content) throws IOException
{
    File tikaFile = new File(path);
    FileUtils.writeStringToFile(tikaFile, content);
}

Check if file exists

1
2
3
4
5
public static Boolean fileExists(String fullPathFile)
{
    File f = new File(fullPathFile);
    return f.exists() && !f.isDirectory();
}

Get extension from the file path

The following example uses org.apache.commons.io.FilenameUtils

1
FilenameUtils.getExtension(targetFile)