2012-06-05 130 views
0

我想从服务器上存在的文件中读取文本,该文件包含文本“hello world”,现在我想在TextView上编写此文本。我导入了所有必需的软件包。在此先感谢如何从.txt文件读取

public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     TextView tv = new TextView(this); 

     try { 
      URL updateURL = new URL("http://--------------------/foldername/hello.txt");     
      URLConnection conn = updateURL.openConnection(); 
      InputStream is = conn.getInputStream(); 
      BufferedInputStream bis = new BufferedInputStream(is); 
      ByteArrayBuffer baf = new ByteArrayBuffer(50); 

      int current = 0; 
      while((current = bis.read()) != -1){ 
       baf.append((byte)current); 
      } 


      final String s = new String(baf.toByteArray());  
      ((TextView)tv).setText(s); 





     } catch (Exception e) { 
     } 
    }; 
+0

什么是你所得到的问题? –

+0

http://stackoverflow.com/q/2902689/601868 – Natali

+0

它只是没有显示什么是写在我的服务器上的文本文件,它没有显示任何错误..但我没有得到所需的resutl –

回答

1

试试这个功能....

public static String convertStreamToString(InputStream is) throws Exception { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 

     while ((line = reader.readLine()) != null) { 
      sb.append(line); 
     } 

     is.close(); 

     return sb.toString(); 
    } 
+0

你会请向我解释如何用我的函数替换此函数,因为我在实现此功能时遇到一些错误,我遇到了问题,我应该在哪里放置链接到服务器上的文件。谢谢 –

0

试试这个代码

URL url = new URL(urlpath); 
BufferedInputStream bis = new BufferedInputStream((url.openStream())); 
DataInputStream dis = new DataInputStream(bis); 
String full = ""; 
String line; 
while ((line=dis.readLine())!=null) { 
    full +=line;    
    }  
bis.close(); 
dis.close(); 

((TextView)tv).setText(full);