2016-07-14 64 views
-1

我上傳了一個文本文件(* .txt)到服務器,現在我想讀取文本文件...Android - 如何從網址讀取文本文件?

我試過這個例子沒有運氣。

ArrayList<String> urls=new ArrayList<String>(); //to read each line 
TextView t; //to show the result 
try { 
     // Create a URL for the desired page 
     URL url = new URL("mydomainname.de/test.txt"); //My text file location 
     // Read all the text returned by the server 
     BufferedReader in = new BufferedReader(new  InputStreamReader(url.openStream())); 

    t=(TextView)findViewById(R.id.TextView1); 
    String str; 
    while ((str = in.readLine()) != null) { 
     urls.add(str); 


    } 
    in.close(); 
    } catch (MalformedURLException e) { 
    } catch (IOException e) { 
} 
t.setText(urls.get(0)); // My TextFile has 3 lines 

應用程序被關閉本身...... 可以向上的域名?應該有IP嗎? 我發現while循環沒有執行。 因爲如果我把t.setText *放在while循環中沒有錯誤,並且TextView是空的。 LogCat錯誤:http://textuploader.com/5iijr它突出顯示的行t.setText(urls.get(0));

在此先感謝!

+3

「mydomainname.de/test.txt」不是一個有效的URL調用它。結果'URL'構造函數會拋出一個你完全忽略的'MalformedURLException'。作爲第二個結果,你的'urls'列表沒有被填充並保持爲空。 – Seelenvirtuose

+0

我刪除了原始鏈接,這是有效的,我的列表沒有填充多少?我沒有明白。 @Seelenvirtuose – killertoge

+0

你正在用一個空的列表初始化變量'urls'。然後你有一個try-catch塊,你首先用_malformed_URL創建一個URL對象。所以你會得到一個例外。這就讓你的變量'urls'保持不變。不多,不少。結論:不要吞下例外!至少打印堆棧跟蹤:'e.printStackTrace()'。 – Seelenvirtuose

回答

4

嘗試使用HttpURLConnection類或OKHTTP請求得到的信息,在這裏試試這個:

永遠做任何形式在後臺線程聯網否則Android將拋出一個NetworkOnMainThread異常

new Thread(new Runnable(){ 

    public void run(){ 


    ArrayList<String> urls=new ArrayList<String>(); //to read each line 
    //TextView t; //to show the result, please declare and find it inside onCreate() 



    try { 
     // Create a URL for the desired page 
     URL url = new URL("http://somevaliddomain.com/somevalidfile"); //My text file location 
     //First open the connection 
     HttpURLConnection conn=(HttpURLConnection) url.openConnection(); 
     conn.setConnectTimeout(60000); // timing out in a minute 

     BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); 

     //t=(TextView)findViewById(R.id.TextView1); // ideally do this in onCreate() 
     String str; 
     while ((str = in.readLine()) != null) { 
      urls.add(str); 
     } 
     in.close(); 
    } catch (Exception e) { 
     Log.d("MyTag",e.toString()); 
    } 

    //since we are in background thread, to post results we have to go back to ui thread. do the following for that 

    Activity.this.runOnUiThread(new Runnable(){ 
     public void run(){ 
      t.setText(urls.get(0)); // My TextFile has 3 lines 
     } 
    }); 

    } 
}).start(); 
+0

urls.get(0)只會讓你第一行 - >根據需要修改它。 – Kushan

0

試試這個。這個對我有用。

private static String readText(){ 
    String link="http://.../file.txt"; 
    ArrayList<String> al=new ArrayList<>(); 

    try{ 
     URL url = new URL(link); 
     URLConnection conn = url.openConnection(); 
     conn.setDoOutput(true); 
     conn.connect(); 

     InputStream is = conn.getInputStream(); 
     InputStreamReader isr = new InputStreamReader(is, "UTF-8"); 
     BufferedReader br = new BufferedReader(isr); 
     String line; 

     try { 
      while ((line = br.readLine()) != null) { 
       al.add(line); 
      } 
     } finally { 
      br.close(); 
     } 
    }catch (IOException e){ 
     e.printStackTrace(); 
    } 
    return al.get(0); 
} 

所以,

t.setText(readText()); 
1

1)互聯網的權限添加到您的清單文件。 2)確保你在不同的線程中啓動你的代碼。

下面是對我很好的代碼片段。

public List<String> getTextFromWeb(String urlString) 
    { 
     URLConnection feedUrl; 
     List<String> placeAddress = new ArrayList<>(); 

     try 
     { 
      feedUrl = new URL(urlString).openConnection(); 
      InputStream is = feedUrl.getInputStream(); 

      BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));   
      String line = null; 

      while ((line = reader.readLine()) != null) // read line by line 
      { 
       placeAddress.add(line); // add line to list 
      } 
      is.close(); // close input stream 

      return placeAddress; // return whatever you need 
     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 

     return null; 
    } 

我們的閱讀器的功能是準備好了,讓我們用另一個線程

  new Thread(new Runnable() 
      { 
       public void run() 
       { 
        final List<String> addressList = getTextFromWeb("http://www.google.com/sometext.txt"); // format your URL 
        runOnUiThread(new Runnable() 
        { 
         @Override 
         public void run() 
         { 
          //update ui 
         } 
        }); 
       } 
      }).start(); 
+0

這個工作,但我花了一些時間來填補你添加的更新的UI評論,我在這裏提到它的魔杖可能是一些需要它的人 'StringBuilder sb = new StringBuilder();對於(String s:placeAddress) { sb.append(s); sb.append(「\ n」); } TextView lyricsTextView =(TextView)getView()。findViewById(R.id.lyricsTextView); lyricsTextView.setText(sb.toString());' –