-1

Basically I am trying to take information from a text file and turn it into a string. The code I have is:

FileInputStream inputStream = new FileInputStream("filename.txt");
try 
{
  String everything = IOUtils.toString(inputStream);
} 
finally 
{
  inputStream.close();
}

the error message I get is -->

java:53: cannot find symbol
symbol  : class IOUtils
location: class CheckSystem

I assumed this was because of my imports, but I have io and util and even text imported (just as below)

import java.util.*;

import java.text.*;

import java.io.*;

Why can't I access the IOUtils class and its methods? If that cannot be answered, an alternative but very simple means of reading a text file into a string would be fine.

Etaoin
  • 7,678
  • 2
  • 24
  • 43
  • IOUtils is part of Apache IO Commons, not part of the standard JDK. You can get it here: https://commons.apache.org/proper/commons-io/. Entire first page of Google results for "IOUtils" explicitly mentions Apache Commons... [sigh] – kryger Jan 11 '14 at 21:31
  • possible duplicate of [Best way to read a text file](http://stackoverflow.com/questions/4716503/best-way-to-read-a-text-file) – kryger Jan 11 '14 at 21:38
  • Down-vote : lack of research; – e.doroskevic Jan 11 '14 at 21:40
  • hey sorry i actually did look all this up but im kind of new to programming so i honestly am not sure how to work with apache commons. – martinmaster43 Jan 11 '14 at 21:47
  • IOUtils is org.apache.commons.io.IOUtils, which you don't have an import for, and probably don't have on your classpath. – David Conrad Jan 11 '14 at 21:48

1 Answers1

2

You don't need anything outside of standard JDK to read from a text file easily and efficiently. For example you can do so like this:

BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
    }
    String everything = sb.toString();
} catch(IOException e) {
  }
  finally {
    br.close();
}

taken from: Reading a plain text file in Java

The everything String contains the contents of the file.txt, which must be located in the same directory as where the java class file is being run from.

Community
  • 1
  • 1
Martin Dinov
  • 8,190
  • 2
  • 26
  • 37
  • Thanks for the answer, but I tried this from the other question as well and I kept getting the error message --> unreported exception java.io.IOException; must be caught or declared to be thrown.Do you know whats wrong here? – martinmaster43 Jan 11 '14 at 21:52
  • Probably because of the missing catch statement. I've added it in there. This shouldn't give you that problem anymore. – Martin Dinov Jan 11 '14 at 22:09