我正在尝试从服务器上存在的文件中读取文本,此文件包含文本“hello world”,现在我想在TextView上编写此文本。我已导入所有必需的包。提前谢谢
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 :(得分: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();
}
答案 1 :(得分: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);