The most concise way to read the contents of a file / input stream in Java?

What is the shortest way to read the contents of a file or input stream in Java? Should I always create a buffer, read (no more) line by line, etc. Or is there a more concise way? I wish I could just do

String content = new File("test.txt").readFully();
+4
source share
10 answers

Use the Apache Commons IOUtils package . In particular, the class IOUtilsprovides a set of methods for reading from streams, readers, etc. And handles all exceptions, etc.

eg.

InputStream is = ...
String contents = IOUtils.toString(is);
// or
List lines = IOUtils.readLines(is)
+7
source

I think the use of the scanner is quite satisfactory with respect to the brevity of the tools built into Java:

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

, (, , ).

+5

. , .

  • cat, InputStream OutputStream
  • cat ByteArrayOutputStream ,
  • Iterator <String> Reader; BufferedReader readLine next()
  • ...

- .

+2
String content = (new RandomAccessFile(new File("test.txt"))).readUTF();

, Java , UTF8, EOFException UTFDataFormatException.

+1

:

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

BufferedReader, IOException.

/**
 * 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;
}

( String, StringBuffer ( StringBuilder java5 6)

+1

, . , Java ( , ) buffer .

, , - , . , XML ...

- readLine StringBuffer/StringBuilder.

0

, BufferedReader - , BufferedReader . , , BR null, .

0

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

0

.

Java ?

:

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

erickson

0

Java 8:

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

Charset String.

0

All Articles