如何从服务器读取txt文件内容并在android中使用? Android新手! 这是我的代码。
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;
/**
* Created by Mukesh on 4/23/2017.
*/
public class PlayerActivity extends Activity {
private String urlStream;
private VideoView myVideoView;
public static void main(String[] args) {
try {
URL url = new URL("http://www.example.com/file.txt");
InputStream is = url.openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ( (line = br.readLine()) != null)
System.out.println(line);
br.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
myVideoView = (VideoView) this.findViewById(R.id.myVideoView);
MediaController mc = new MediaController(this);
myVideoView.setMediaController(mc);
urlStream = ""; //how to keep the text read from txt file from server
runOnUiThread(new Runnable() {
@Override
public void run() {
myVideoView.setVideoURI(Uri.parse(urlStream));
myVideoView.start();
}
});
}
}
这里urlStream =从url读取的文本。检查解决方案无处不在,但无法修复它。这是一个m3u8播放器Android应用程序。 m3u8 url保存在服务器的txt文件中,应用程序应该从txt文件中读取url并将其附加到app中的urlStream。
答案 0 :(得分:1)
找到解决方案
private String getTextFromUrl(){
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).toString();
}
然后将文本int放到TextView
t.setText(getTextFromUrl());