java Android - 如何从 url 读取文本文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38372571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android - How can I read a text file from a url?
提问by killertoge
I uploaded a text file(*.txt) to a server, now I want to read the text file...
我上传了一个文本文件(*.txt)到服务器,现在我想读取文本文件......
I tried this example without luck.
我在没有运气的情况下尝试了这个例子。
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
App is closing itself...
Can it be up to the domain name ? Should there be a IP instead ?
I figured out that the while loop isn't executed.
Because if I put t.setText* in the while loop there is no error, and the TextView is empty.
LogCat Error : http://textuploader.com/5iijrit highlight the line with t.setText(urls.get(0));
应用程序正在关闭自己...可以由域名决定吗?应该有一个IP吗?我发现没有执行 while 循环。因为如果我将 t.setText* 放入 while 循环中,则没有错误,并且 TextView 为空。LogCat 错误:http: //textuploader.com/5iijr它突出显示与t.setText(urls.get(0));
Thanks in Advance !!!
提前致谢 !!!
回答by Kushan
Try using an HTTPUrlConnection or a OKHTTP Request to get the info, here try this:
尝试使用 HTTPUrlConnection 或 OKHTTP 请求来获取信息,在这里试试这个:
Always do any kind of networking in a background thread else android will throw a NetworkOnMainThread Exception
始终在后台线程中进行任何类型的网络操作,否则 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();
回答by Burak Cakir
1-) Add internet permission to your Manifest file.
1-) 为您的清单文件添加互联网权限。
2-) Make sure that you are launching your code in separate thread.
2-) 确保您在单独的线程中启动代码。
Here is the snippet which works for me great.
这是对我很有用的片段。
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;
}
Our reader function is ready, let's call it by using another thread
我们的 reader 函数已经准备好了,让我们使用另一个线程来调用它
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();
回答by farhad.kargaran
declare a string variable to save text:
声明一个字符串变量来保存文本:
public String txt;
declare a method to check connectivity:
声明一个方法来检查连通性:
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
delare an AsyncTask like this:
像这样定义一个 AsyncTask:
private class ReadFileTask extends AsyncTask<String,Integer,Void> {
protected Void doInBackground(String...params){
URL url;
try {
//create url object to point to the file location on internet
url = new URL(params[0]);
//make a request to server
HttpURLConnection con=(HttpURLConnection)url.openConnection();
//get InputStream instance
InputStream is=con.getInputStream();
//create BufferedReader object
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line;
//read content of the file line by line
while((line=br.readLine())!=null){
txt+=line;
}
br.close();
}catch (Exception e) {
e.printStackTrace();
//close dialog if error occurs
}
return null;
}
now call AsyncTask with desired Url:
现在使用所需的 URL 调用 AsyncTask:
if(isNetworkConnected())
{
ReadFileTask tsk=new ReadFileTask ();
tsk.execute("http://mystite.com/test.txt");
}
and dont forget to add following permission in Manifest:
并且不要忘记在清单中添加以下权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
回答by Aishik kirtaniya
just put it inside a new thread and start the thread it will work.
只需将它放在一个新线程中并启动它将工作的线程。
new Thread(new Runnable()
{
@Override
public void run()
{
try
{
URL url = new URL("https://texts-8e2bd.firebaseapp.com/");//my app link change it
HttpsURLConnection uc = (HttpsURLConnection) url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String line;
StringBuilder lin2 = new StringBuilder();
while ((line = br.readLine()) != null)
{
lin2.append(line);
}
Log.d("texts", "onClick: "+lin2);
} catch (IOException e)
{
Log.d("texts", "onClick: "+e.getLocalizedMessage());
e.printStackTrace();
}
}
}).start();
thats it.
而已。