4

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();
cretzel
  • 19,864
  • 19
  • 58
  • 71

10 Answers10

7

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
  • 268,207
  • 37
  • 334
  • 440
5

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
  • 44,988
  • 7
  • 85
  • 112
2

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
  • 5,213
  • 1
  • 24
  • 33
1
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
  • 2,119
  • 15
  • 25
  • 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 Oct 22 '08 at 10:01
1

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
  • 1,262,500
  • 529
  • 4,410
  • 5,250
0

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
  • 40,535
  • 6
  • 96
  • 134
0

Or the Java 8 way:

try {
    String str = new String(Files.readAllBytes(Paths.get("myfile.txt")));
    ...
} catch (IOException ex) {
    Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}

One may pass an appropriate Charset to the String constructor.

Doc Brown
  • 422
  • 5
  • 9
0

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 Feb 23 '09 at 03:57
0

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

jonathan.cone
  • 6,592
  • 2
  • 30
  • 30
0

Pick one from here.

How do I 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

Community
  • 1
  • 1
OscarRyz
  • 196,001
  • 113
  • 385
  • 569