2010-08-25 32 views
1

我正在从example.com/test.txt下载文本文件,并且仅在我的应用运行时期间需要内容,它们不需要保存到一个静态文件。缓存字符串中的在线文件内容而不是本地文件

到目前为止我的代码:

  InputStream input = new BufferedInputStream(getURL.openStream()); 
      OutputStream output = new FileOutputStream(tempFile); 

      byte data[] = new byte[1024]; 

      long total = 0; 

      while ((count = input.read(data)) != -1) { 
       output.write(data, 0, count); 
      } 

      output.flush(); 
      output.close(); 
      input.close(); 

我将如何去写的在线文件内容为一个字符串,而不是在本地保存文件?我曾尝试在while语句中将data附加到String,但只是得到乱码文本(如预期的那样,但我不知道该怎么办)。将byte转换回字符串?

感谢您的帮助!

回答

1

而不是FileOutputStream使用ByteArrayOutput流。然后您可以调用toString将其转换为字符串。

 InputStream input = new BufferedInputStream(getURL.openStream()); 
     OutputStream output = new ByteArrayOutputStream(); 

     byte data[] = new byte[1024]; 

     long total = 0; 

     while ((count = input.read(data)) != -1) { 
      output.write(data, 0, count); 
     } 

     output.flush(); 
     output.close(); 
     input.close(); 
     String result = output.toString(); 
+0

完美的作品,感谢您的快速回复! – Nick 2010-08-25 04:07:23

1

您可以使用类似于here所述的方法。从Java文档

代码片段:

URL yahoo = new URL("http://www.yahoo.com/"); 
BufferedReader in = new BufferedReader(
      new InputStreamReader(
      yahoo.openStream())); 

String inputLine; 

while ((inputLine = in.readLine()) != null) 
    System.out.println(inputLine); 

in.close(); 

你只需要每行一个字符串追加其发送到System.out代替。

+0

通过+运算符进行字符串连接并不是那么有效。你最好使用StringBuilder。 – 2010-08-25 04:02:59

+0

也适用,谢谢:-)! – Nick 2010-08-25 04:08:03

相关问题