tags:

views:

1217

answers:

9

What ist most concise way to read the contents of a file or input stream in Java? Do I always have to create a buffer, read (at most) line by line and so on or is there a more concise way? I wish I could do just

String content = new File("test.txt").readFully();
A: 
String content = (new RandomAccessFile(new File("test.txt"))).readUTF();

Unfortunately Java is very picky about the source file being valid UTF8 though, or you will get an EOFException or UTFDataFormatException.

Lars Westergren
You're missing a closing quote there...
itsadok
I don't think it's a matter a Java being "picky" about the text you read with readUTF(), it's just that you're using it wrong. Read this: http://java.sun.com/javase/6/docs/api/java/io/DataInput.html#modified-utf-8
Alan Moore
A: 

You have to create your own function, I suppose. The problem is that Java's read routines (those I know, at least) usually take a buffer argument with a given length.

A solution I saw is to get the size of the file, create a buffer of this size and read the file at once. Hoping the file isn't a gigabyte log or XML file...

The usual way is to have a fixed size buffer or to use readLine and concatenate the results in a StringBuffer/StringBuilder.

PhiLho
+3  A: 

Helper functions. I basically use a few of them, depending on the situation

  • cat method that pipes an InputStream to an OutputStream
  • method that calls cat to a ByteArrayOutputStream and extracts the byte array, enabling quick read of an entire file to a byte array
  • Implementation of Iterator<String> that is constructed using a Reader; it wraps it in a BufferedReader and readLine's on next()
  • ...

Either roll your own or use something out of commons-io or your preferred utility library.

alex
A: 

To give an example of such an helper function:

String[] lines = NioUtils.readInFile(componentxml);

The key is to try to close the BufferedReader even if an IOException is thrown.

/**
 * Read lines in a file. <br />
 * File must exist
 * @param f file to be read
 * @return array of lines, empty if file empty
 * @throws IOException if prb during access or closing of the file
 */
public static String[] readInFile(final File f) throws IOException
{
    final ArrayList lines = new ArrayList();
    IOException anioe = null;
    BufferedReader br = null; 
    try 
    {
     br = new BufferedReader(new FileReader(f));
     String line;
     line = br.readLine();
     while(line != null)
     {
      lines.add(line);
      line = br.readLine();
     }
     br.close();
     br = null;
    } 
    catch (final IOException e) 
    {
     anioe = e;
    }
    finally
    {
     if(br != null)
     {
      try {
       br.close();
      } catch (final IOException e) {
       anioe = e;
      }
     }
     if(anioe != null)
     {
      throw anioe;
     }
    }
    final String[] myStrings = new String[lines.size()];
    //myStrings = lines.toArray(myStrings);
    System.arraycopy(lines.toArray(), 0, myStrings, 0, lines.size());
    return myStrings;
}

(if you just want a String, change the function to append each lines to a StringBuffer (or StringBuilder in java5 or 6)

VonC
A: 

I don't think reading using BufferedReader is a good idea because BufferedReader will return just the content of line without the delimeter. When the line contains nothing but newline character, BR will return a null although it still doesn't reach the end of the stream.

No. When the BufferedReader sees two consecutive line separators, readLine() returns an empty string. It only returns null when it reaches the end of the file.
Alan Moore
A: 

String org.apache.commons.io.FileUtils.readFileToString(File file)

jonathan.cone
+1  A: 

I think using a Scanner is quite OK with regards to conciseness of Java on-board tools:

Scanner s = new Scanner(new File("file"));
StringBuilder builder = new StringBuilder();
while(s.hasNextLine()) builder.append(s.nextLine());

Also, it's quite flexible, too (e.g. regular expressions support, number parsing).

Fabian Steeg
nice solution. way cleaner then everything else
Janusz
A: 

Pick one from here.

http://stackoverflow.com/questions/326390/how-to-create-a-java-string-from-the-contents-of-a-file

The favorite was:

private static String readFile(String path) throws IOException {
  FileInputStream stream = new FileInputStream(new File(path));
  try {
    FileChannel fc = stream.getChannel();
    MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
    /* Instead of using default, pass in a decoder. */
    return CharSet.defaultCharset().decode(bb).toString();
  }
  finally {
    stream.close();
  }
}

Posted by erickson

OscarRyz
+2  A: 

Use the Apache Commons IOUtils package. In particular the IOUtils class provides a set of methods to read from streams, readers etc. and handle all the exceptions etc.

e.g.

InputStream is = ...
String contents = IOUtils.toString(is);
// or
List lines = IOUtils.readLines(is)
Brian Agnew