'What to import to use IOUtils.toString()?

I am trying to use IOUtils.toString() to read from a file. However, I am getting an error saying "IOUtils cannot be resolved."

What am I supposed to be importing to allow me to use this function?

String everything = IOUtils.toString(inputStream);

Thanks



Solution 1:[1]

import org.apache.commons.io.IOUtils;

If you still can't import add to pom.xml:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>

or for direct jar/gradle etc visit: http://mvnrepository.com/artifact/commons-io/commons-io/2.5

Also since version 2.5 of commons-io method IOUtils.toString(inputStream) has been deprecated. You should use method with Encoding i.e.

IOUtils.toString(is, "UTF-8");

Solution 2:[2]

import org.apache.commons.io.IOUtils;

Solution 3:[3]

Fryta's answer outline how to actually use IOUtils and snj's answer is good for files.

If you're on java 9 or later and you have an input stream to read you can use InputStream#readAllBytes(). Just create a string from there and don't forget to specify charset.

String s = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);

Solution 4:[4]

Alternatively you can try following way. It worked for me for reading public key for resource server

        final Resource resource = new ClassPathResource("public.key");
        String publicKey = null;
        try {
            publicKey = new String(Files.readAllBytes(resource.getFile().toPath()), StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }

Solution 5:[5]

Here is code for How to convert InputStream to String in Java using Apache IOUtils

Reference : https://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/IOUtils.html

FileInputStream fis = new FileInputStream(FILE_LOCATION);
String StringFromInputStream = IOUtils.toString(fis, "UTF-8");
System.out.println(StringFromInputStream);

Let me know if you need more help.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 SMR
Solution 3 thoredge
Solution 4 Sanjay Sharma
Solution 5 Himanshu Arora