读取/转换一个InputStream为一个string

如果你有java.io.InputStream对象,你应该如何处理这个对象并产生一个String


假设我有一个包含文本数据的InputStream ,并且我想将其转换为一个String 。 例如,我可以将stream的内容写入日志文件。

采取InputStream并将其转换为String的最简单方法是什么?

 public String convertStreamToString(InputStream is) { // ??? } 

一个很好的方法是使用Apache commons IOUtilsInputStream复制到StringWriter

 StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer, encoding); String theString = writer.toString(); 

甚至

 // NB: does not close inputStream, you can use IOUtils.closeQuietly for that String theString = IOUtils.toString(inputStream, encoding); 

或者,如果您不想混合使用Streams和Writer,则可以使用ByteArrayOutputStream

这是一个只使用标准Java库的方法(注意stream不closures,YMMV)。

 static String convertStreamToString(java.io.InputStream is) { java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } 

我从“愚蠢的扫描器技巧”文章中学到了这个技巧。 它的工作原因是因为Scanner在stream中迭代了令牌,在这种情况下,我们使用“input边界的开始”(\ A)分离令牌,因此只给出stream的全部内容的一个令牌。

请注意,如果您需要特定于inputstream的编码,则可以向Scanner构造函数提供第二个参数,以指示要使用的字符集(例如“UTF-8”)。

帽子提示也去雅各,曾经指向我说的文章。

编辑:感谢来自Patrick的build议,使处理空inputstream时更强大的function。 多一个编辑:不要尝试/抓住,帕特里克的方式更简洁。

总结其他答案,我发现了11个主要的方法来做到这一点(见下文)。 我写了一些性能testing(见下面的结果):

将InputStream转换为string的方法:

  1. 使用IOUtils.toStringApache Utils

     String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8); 
  2. 使用CharStreamsguava

     String result = CharStreams.toString(new InputStreamReader( inputStream, Charsets.UTF_8)); 
  3. 使用ScannerJDK

     Scanner s = new Scanner(inputStream).useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; 
  4. 使用Stream ApiJava 8 )。 警告 :此解决scheme将不同的换行符(如\r\n )转换为\n

     String result = new BufferedReader(new InputStreamReader(inputStream)) .lines().collect(Collectors.joining("\n")); 
  5. 使用并行streamAPIJava 8 )。 警告 :此解决scheme将不同的换行符(如\r\n )转换为\n

     String result = new BufferedReader(new InputStreamReader(inputStream)).lines() .parallel().collect(Collectors.joining("\n")); 
  6. 使用InputStreamReaderStringBuilderJDK

     final int bufferSize = 1024; final char[] buffer = new char[bufferSize]; final StringBuilder out = new StringBuilder(); Reader in = new InputStreamReader(inputStream, "UTF-8"); for (; ; ) { int rsz = in.read(buffer, 0, buffer.length); if (rsz < 0) break; out.append(buffer, 0, rsz); } return out.toString(); 
  7. 使用StringWriterIOUtils.copyApache Commons

     StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer, "UTF-8"); return writer.toString(); 
  8. 使用ByteArrayOutputStreaminputStream.readJDK

     ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) != -1) { result.write(buffer, 0, length); } // StandardCharsets.UTF_8.name() > JDK 7 return result.toString("UTF-8"); 
  9. 使用BufferedReaderJDK )。 警告:此解决scheme将不同的换行符(如\n\r )转换为line.separator系统属性(例如,在Windows中为“\ r \ n”)。

     String newLine = System.getProperty("line.separator"); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder result = new StringBuilder(); String line; boolean flag = false; while ((line = reader.readLine()) != null) { result.append(flag? newLine: "").append(line); flag = true; } return result.toString(); 
  10. 使用BufferedInputStreamByteArrayOutputStreamJDK

     BufferedInputStream bis = new BufferedInputStream(inputStream); ByteArrayOutputStream buf = new ByteArrayOutputStream(); int result = bis.read(); while(result != -1) { buf.write((byte) result); result = bis.read(); } // StandardCharsets.UTF_8.name() > JDK 7 return buf.toString("UTF-8"); 
  11. 使用inputStream.read()StringBuilderJDK )。 警告 :此解决scheme有Unicode的问题,例如与俄语文本(正常工作只与非Unicode文本)

     int ch; StringBuilder sb = new StringBuilder(); while((ch = inputStream.read()) != -1) sb.append((char)ch); reset(); return sb.toString(); 

警告

  1. 解决scheme49将不同的换行符转换为一个。

  2. 解决scheme11不能正确使用Unicode文本

性能testing

对于小String (长度= 175),在github (模式=平均时间,系统= Linux,得分1343是最好的)的性能testing:

  Benchmark Mode Cnt Score Error Units 8. ByteArrayOutputStream and read (JDK) avgt 10 1,343 ± 0,028 us/op 6. InputStreamReader and StringBuilder (JDK) avgt 10 6,980 ± 0,404 us/op 10. BufferedInputStream, ByteArrayOutputStream avgt 10 7,437 ± 0,735 us/op 11. InputStream.read() and StringBuilder (JDK) avgt 10 8,977 ± 0,328 us/op 7. StringWriter and IOUtils.copy (Apache) avgt 10 10,613 ± 0,599 us/op 1. IOUtils.toString (Apache Utils) avgt 10 10,605 ± 0,527 us/op 3. Scanner (JDK) avgt 10 12,083 ± 0,293 us/op 2. CharStreams (guava) avgt 10 12,999 ± 0,514 us/op 4. Stream Api (Java 8) avgt 10 15,811 ± 0,605 us/op 9. BufferedReader (JDK) avgt 10 16,038 ± 0,711 us/op 5. parallel Stream Api (Java 8) avgt 10 21,544 ± 0,583 us/op 

性能testing的大String (长度= 50100), github中的url(模式=平均时间,系统= Linux,得分200,715是最好的):

  Benchmark Mode Cnt Score Error Units 8. ByteArrayOutputStream and read (JDK) avgt 10 200,715 ± 18,103 us/op 1. IOUtils.toString (Apache Utils) avgt 10 300,019 ± 8,751 us/op 6. InputStreamReader and StringBuilder (JDK) avgt 10 347,616 ± 130,348 us/op 7. StringWriter and IOUtils.copy (Apache) avgt 10 352,791 ± 105,337 us/op 2. CharStreams (guava) avgt 10 420,137 ± 59,877 us/op 9. BufferedReader (JDK) avgt 10 632,028 ± 17,002 us/op 5. parallel Stream Api (Java 8) avgt 10 662,999 ± 46,199 us/op 4. Stream Api (Java 8) avgt 10 701,269 ± 82,296 us/op 10. BufferedInputStream, ByteArrayOutputStream avgt 10 740,837 ± 5,613 us/op 3. Scanner (JDK) avgt 10 751,417 ± 62,026 us/op 11. InputStream.read() and StringBuilder (JDK) avgt 10 2919,350 ± 1101,942 us/op 

graphics(性能testing取决于Windows 7系统中的inputstream长度)
在这里输入图像描述

性能testing(平均时间)取决于Windows 7系统中的inputstream长度:

  length 182 546 1092 3276 9828 29484 58968 test8 0.38 0.938 1.868 4.448 13.412 36.459 72.708 test4 2.362 3.609 5.573 12.769 40.74 81.415 159.864 test5 3.881 5.075 6.904 14.123 50.258 129.937 166.162 test9 2.237 3.493 5.422 11.977 45.98 89.336 177.39 test6 1.261 2.12 4.38 10.698 31.821 86.106 186.636 test7 1.601 2.391 3.646 8.367 38.196 110.221 211.016 test1 1.529 2.381 3.527 8.411 40.551 105.16 212.573 test3 3.035 3.934 8.606 20.858 61.571 118.744 235.428 test2 3.136 6.238 10.508 33.48 43.532 118.044 239.481 test10 1.593 4.736 7.527 20.557 59.856 162.907 323.147 test11 3.913 11.506 23.26 68.644 207.591 600.444 1211.545 

Apache Commons允许:

 String myString = IOUtils.toString(myInputStream, "UTF-8"); 

当然,你也可以select除UTF-8之外的其他字符编码。

另请参阅:( 文档 )

考虑到文件之一应该首先得到一个java.io.Reader实例。 这可以被读取并添加到StringBuilder (如果我们不在multithreading中访问它,并且StringBuilder更快,我们不需要StringBuffer )。 这里的诀窍是我们在块中工作,因此不需要其他缓冲stream。 为了运行时性能优化,块大小被参数化。

 public static String slurp(final InputStream is, final int bufferSize) { final char[] buffer = new char[bufferSize]; final StringBuilder out = new StringBuilder(); try (Reader in = new InputStreamReader(is, "UTF-8")) { for (;;) { int rsz = in.read(buffer, 0, buffer.length); if (rsz < 0) break; out.append(buffer, 0, rsz); } } catch (UnsupportedEncodingException ex) { /* ... */ } catch (IOException ex) { /* ... */ } return out.toString(); } 

这个怎么样?

 InputStream in = /* your InputStream */ ; StringBuilder sb=new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String read; while((read=br.readLine()) != null) { //System.out.println(read); sb.append(read); } br.close(); return sb.toString(); 

如果您使用Google-Collections / Guava,则可以执行以下操作:

 InputStream stream = ... String content = CharStreams.toString(new InputStreamReader(stream, Charsets.UTF_8)); Closeables.closeQuietly(stream); 

请注意, InputStreamReader的第二个参数(即Charsets.UTF_8)是不必要的,但是如果你知道它(你应该这样做),指定编码通常是个好主意。

这是我的纯Java和Android解决scheme,效果很好…

 public String readFullyAsString(InputStream inputStream, String encoding) throws IOException { return readFully(inputStream).toString(encoding); } public byte[] readFullyAsBytes(InputStream inputStream) throws IOException { return readFully(inputStream).toByteArray(); } private ByteArrayOutputStream readFully(InputStream inputStream) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length = 0; while ((length = inputStream.read(buffer)) != -1) { baos.write(buffer, 0, length); } return baos; } 

下面是经过一些实验后提出的最优雅的纯Java(无库)解决scheme:

 public static String fromStream(InputStream in) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder out = new StringBuilder(); String newLine = System.getProperty("line.separator"); String line; while ((line = reader.readLine()) != null) { out.append(line); out.append(newLine); } return out.toString(); } 

怎么样:

 import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.IOException; public static String readInputStreamAsString(InputStream in) throws IOException { BufferedInputStream bis = new BufferedInputStream(in); ByteArrayOutputStream buf = new ByteArrayOutputStream(); int result = bis.read(); while(result != -1) { byte b = (byte)result; buf.write(b); result = bis.read(); } return buf.toString(); } 

为了完整起见,这里是Java 9解决scheme:

 public static String toString(InputStream input) throws IOException { return new String(input.readAllBytes(), StandardCharsets.UTF_8); } 

readAllBytes目前在JDK 9主代码库中,所以它很可能出现在发行版中。 您可以使用JDK 9快照构build立即尝试。

我会使用一些Java 8技巧。

 public static String streamToString(final InputStream inputStream) throws Exception { // buffering optional try ( final BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)) ) { // parallel optional return br.lines().parallel().collect(Collectors.joining("\n")); } catch (final IOException e) { throw new RuntimeException(e); // whatever. } } 

基本上与其他答案相同,除了更简洁。

使用Streams的纯Java解决scheme,自Java 8起运行。

 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.stream.Collectors; // ... public static String inputStreamToString(InputStream is) throws IOException { try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) { return br.lines().collect(Collectors.joining(System.lineSeparator())); } } 

正如ChristofferHammarström在其他答案下提到的那样,明确指定字符集更为安全。 也就是说InputStreamReader的构造函数可以做如下修改:

 new InputStreamReader(is, Charset.forName("UTF-8")) 

我经常进行一些时间testing,因为时间很重要。

我试图通过不同的方式将响应转换为string3。 (如下所示)
为了可读性,我省略了try / catch块。

为了给出上下文,这是所有3种方法的前面的代码:

  String response; String url = "www.blah.com/path?key=value"; GetMethod method = new GetMethod(url); int status = client.executeMethod(method); 

1)

  response = method.getResponseBodyAsString(); 

2)

 InputStream resp = method.getResponseBodyAsStream(); InputStreamReader is=new InputStreamReader(resp); BufferedReader br=new BufferedReader(is); String read = null; StringBuffer sb = new StringBuffer(); while((read = br.readLine()) != null) { sb.append(read); } response = sb.toString(); 

3)

 InputStream iStream = method.getResponseBodyAsStream(); StringWriter writer = new StringWriter(); IOUtils.copy(iStream, writer, "UTF-8"); response = writer.toString(); 

因此,在使用相同请求/响应数据的每个方法上运行500次testing之后,这里是数字。 再一次,这些是我的发现,你的发现可能不完全一样,但是我写这个来给其他人提供这些方法的效率差异的一些指示。

排名:
方法#1
方法#3 – 比#1慢2.6%
方法#2 – 比#1慢4.3%

任何这些方法都是获取响应并从中创buildstring的合适解决scheme。

这是或多或lesssampath的答案,清理了一下,并表示为一个函数:

 String streamToString(InputStream in) throws IOException { StringBuilder out = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); for(String line = br.readLine(); line != null; line = br.readLine()) out.append(line); br.close(); return out.toString(); } 

如果你喜欢冒险,你可以混合使用Scala和Java,并最终得到这个:

 scala.io.Source.fromInputStream(is).mkString("") 

混合Java和Scala代码和库有它的好处。

在这里看到完整的描述: 将InputStream转换为Scala中的string的习惯性方法

如果你不能使用Commons IO(FileUtils / IOUtils / CopyUtils),下面是一个使用BufferedReader逐行读取文件的例子:

 public class StringFromFile { public static void main(String[] args) /*throws UnsupportedEncodingException*/ { InputStream is = StringFromFile.class.getResourceAsStream("file.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(is/*, "UTF-8"*/)); final int CHARS_PER_PAGE = 5000; //counting spaces StringBuilder builder = new StringBuilder(CHARS_PER_PAGE); try { for(String line=br.readLine(); line!=null; line=br.readLine()) { builder.append(line); builder.append('\n'); } } catch (IOException ignore) { } String text = builder.toString(); System.out.println(text); } } 

或者如果你想要原始速度,我会build议Paul de Vrieze的build议(避免使用StringWriter(内部使用StringBuffer)):

 public class StringFromFileFast { public static void main(String[] args) /*throws UnsupportedEncodingException*/ { InputStream is = StringFromFileFast.class.getResourceAsStream("file.txt"); InputStreamReader input = new InputStreamReader(is/*, "UTF-8"*/); final int CHARS_PER_PAGE = 5000; //counting spaces final char[] buffer = new char[CHARS_PER_PAGE]; StringBuilder output = new StringBuilder(CHARS_PER_PAGE); try { for(int read = input.read(buffer, 0, buffer.length); read != -1; read = input.read(buffer, 0, buffer.length)) { output.append(buffer, 0, read); } } catch (IOException ignore) { } String text = output.toString(); System.out.println(text); } } 

This is an answer adapted from org.apache.commons.io.IOUtils source code , for those who want to have the apache implementation but do not want the whole library.

 private static final int BUFFER_SIZE = 4 * 1024; public static String inputStreamToString(InputStream inputStream, String charsetName) throws IOException { StringBuilder builder = new StringBuilder(); InputStreamReader reader = new InputStreamReader(inputStream, charsetName); char[] buffer = new char[BUFFER_SIZE]; int length; while ((length = reader.read(buffer)) != -1) { builder.append(buffer, 0, length); } return builder.toString(); } 

Make sure to close the streams at end if you use Stream Readers

 private String readStream(InputStream iStream) throws IOException { //build a Stream Reader, it can read char by char InputStreamReader iStreamReader = new InputStreamReader(iStream); //build a buffered Reader, so that i can read whole line at once BufferedReader bReader = new BufferedReader(iStreamReader); String line = null; StringBuilder builder = new StringBuilder(); while((line = bReader.readLine()) != null) { //Read till end builder.append(line); builder.append("\n"); // append new line to preserve lines } bReader.close(); //close all opened stuff iStreamReader.close(); //iStream.close(); //EDIT: Let the creator of the stream close it! // some readers may auto close the inner stream return builder.toString(); } 

EDIT: On JDK 7+, you can use try-with-resources construct.

 /** * Reads the stream into a string * @param iStream the input stream * @return the string read from the stream * @throws IOException when an IO error occurs */ private String readStream(InputStream iStream) throws IOException { //Buffered reader allows us to read line by line try (BufferedReader bReader = new BufferedReader(new InputStreamReader(iStream))){ StringBuilder builder = new StringBuilder(); String line; while((line = bReader.readLine()) != null) { //Read till end builder.append(line); builder.append("\n"); // append new line to preserve lines } return builder.toString(); } } 

Here is the complete method for converting InputStream into String without using any third party library. Use StringBuilder for single threaded environment otherwise use StringBuffer .

 public static String getString( InputStream is) throws IOException { int ch; StringBuilder sb = new StringBuilder(); while((ch = is.read()) != -1) sb.append((char)ch); return sb.toString(); } 

Here's how to do it using just the JDK using byte array buffers. This is actually how the commons-io IOUtils.copy() methods all work. You can replace byte[] with char[] if you're copying from a Reader instead of an InputStream .

 import java.io.ByteArrayOutputStream; import java.io.InputStream; ... InputStream is = .... ByteArrayOutputStream baos = new ByteArrayOutputStream(8192); byte[] buffer = new byte[8192]; int count = 0; try { while ((count = is.read(buffer)) != -1) { baos.write(buffer, 0, count); } } finally { try { is.close(); } catch (Exception ignore) { } } String charset = "UTF-8"; String inputStreamAsString = baos.toString(charset); 

Kotlin users simply do:

 println(InputStreamReader(is).readText()) 

 readText() 

is Kotlin standard library's built-in extension method.

This one is nice because:

  • Hand safety the Charset.
  • You control the read buffer size.
  • You can provision the length of the builder and can be not exactly.
  • Is free from library dependencies.
  • Is for Java 7 or higher.

What the for?

 public static String convertStreamToString(InputStream is) { if (is == null) return null; StringBuilder sb = new StringBuilder(2048); // Define a size if you have an idea of it. char[] read = new char[128]; // Your buffer size. try (InputStreamReader ir = new InputStreamReader(is, StandardCharsets.UTF_8)) { for (int i; -1 != (i = ir.read(read)); sb.append(read, 0, i)); } catch (Throwable t) {} return sb.toString(); } 

Another one, for all the Spring users:

 import java.nio.charset.StandardCharsets; import org.springframework.util.FileCopyUtils; public String convertStreamToString(InputStream is) throws IOException { return new String(FileCopyUtils.copyToByteArray(is), StandardCharsets.UTF_8); } 

The utility methods in org.springframework.util.StreamUtils are similar to the ones in FileCopyUtils , but they leave the stream open when done.

The easiest way in JDK is with the following code snipplets.

 String convertToString(InputStream in){ String resource = new Scanner(in).useDelimiter("\\Z").next(); return resource; } 

Well you can program it for yourself.. it's not complicated..

 String Inputstream2String (InputStream is) throws IOException { final int PKG_SIZE = 1024; byte[] data = new byte [PKG_SIZE]; StringBuilder buffer = new StringBuilder(PKG_SIZE * 10); int size; size = is.read(data, 0, data.length); while (size > 0) { String str = new String(data, 0, size); buffer.append(str); size = is.read(data, 0, data.length); } return buffer.toString(); } 

JDK 7/8 answer that closes the stream and still throws an IOException:

 StringBuilder build = new StringBuilder(); byte[] buf = new byte[1024]; int length; try (InputStream is = getInputStream()) { while ((length = is.read(buf)) != -1) { build.append(new String(buf, 0, length)); } } 

You can use apache commons. In the IOUtils you can find the toString metod with 3 helpfull implementations.

 public static String toString(InputStream input) throws IOException { return toString(input, Charset.defaultCharset()); } public static String toString(InputStream input) throws IOException { return toString(input, Charset.defaultCharset()); } public static String toString(InputStream input, String encoding) throws IOException { return toString(input, Charsets.toCharset(encoding)); } 

I have written a class that does just that, so I figured I'd share it with everyone. Sometimes you don't want to add Apache Commons just for one thing, and want something dumber than Scanner that doesn't examine the content.

Usage is as follows

 // Read from InputStream String data = new ReaderSink(inputStream, Charset.forName("UTF-8")).drain(); // Read from File data = new ReaderSink(file, Charset.forName("UTF-8")).drain(); // Drain input stream to console new ReaderSink(inputStream, Charset.forName("UTF-8")).drainTo(System.out); 

Here is the code for ReaderSink:

 import java.io.*; import java.nio.charset.Charset; /** * A simple sink class that drains a {@link Reader} to a {@link String} or * to a {@link Writer}. * * @author Ben Barkay * @version 2/20/2014 */ public class ReaderSink { /** * The default buffer size to use if no buffer size was specified. */ public static final int DEFAULT_BUFFER_SIZE = 1024; /** * The {@link Reader} that will be drained. */ private final Reader in; /** * Constructs a new {@code ReaderSink} for the specified file and charset. * @param file The file to read from. * @param charset The charset to use. * @throws FileNotFoundException If the file was not found on the filesystem. */ public ReaderSink(File file, Charset charset) throws FileNotFoundException { this(new FileInputStream(file), charset); } /** * Constructs a new {@code ReaderSink} for the specified {@link InputStream}. * @param in The {@link InputStream} to drain. * @param charset The charset to use. */ public ReaderSink(InputStream in, Charset charset) { this(new InputStreamReader(in, charset)); } /** * Constructs a new {@code ReaderSink} for the specified {@link Reader}. * @param in The reader to drain. */ public ReaderSink(Reader in) { this.in = in; } /** * Drains the data from the underlying {@link Reader}, returning a {@link String} containing * all of the read information. This method will use {@link #DEFAULT_BUFFER_SIZE} for * its buffer size. * @return A {@link String} containing all of the information that was read. */ public String drain() throws IOException { return drain(DEFAULT_BUFFER_SIZE); } /** * Drains the data from the underlying {@link Reader}, returning a {@link String} containing * all of the read information. * @param bufferSize The size of the buffer to use when reading. * @return A {@link String} containing all of the information that was read. */ public String drain(int bufferSize) throws IOException { StringWriter stringWriter = new StringWriter(); drainTo(stringWriter, bufferSize); return stringWriter.toString(); } /** * Drains the data from the underlying {@link Reader}, writing it to the * specified {@link Writer}. This method will use {@link #DEFAULT_BUFFER_SIZE} for * its buffer size. * @param out The {@link Writer} to write to. */ public void drainTo(Writer out) throws IOException { drainTo(out, DEFAULT_BUFFER_SIZE); } /** * Drains the data from the underlying {@link Reader}, writing it to the * specified {@link Writer}. * @param out The {@link Writer} to write to. * @param bufferSize The size of the buffer to use when reader. */ public void drainTo(Writer out, int bufferSize) throws IOException { char[] buffer = new char[bufferSize]; int read; while ((read = in.read(buffer)) > -1) { out.write(buffer, 0, read); } } } 

Guava provides much shorter efficient autoclosing solution in case when input stream comes from classpath resource (which seems to be popular task):

 byte[] bytes = Resources.toByteArray(classLoader.getResource(path)); 

要么

 String text = Resources.toString(classLoader.getResource(path), StandardCharsets.UTF_8); 

There is also general concept of ByteSource and CharSource that gently take care of both opening and closing the stream.

So, for example, instead of explicitly opening a small file to read its contents:

 String content = Files.asCharSource(new File("robots.txt"), StandardCharsets.UTF_8).read(); byte[] data = Files.asByteSource(new File("favicon.ico")).read(); 

要不就

 String content = Files.toString(new File("robots.txt"), StandardCharsets.UTF_8); byte[] data = Files.toByteArray(new File("favicon.ico"));