简体   繁体   中英

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

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 ie

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

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);

import org.apache.commons.io.IOUtils;

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();
        }

The following import statement would be required:

import org.apache.commons.io.IOUtils;

If the error " The import org.apache.commons.io cannot be resolved " shows up, add the commons-io-2.6.jar to the project Java buildpath and/or to the project lib folder .

Note: The suggestion to import "import org.apache.commons.io.IOUtils;" usually doesn't appear in Eclipse IDE at least in the context of this question.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM