gpt4 book ai didi

Android 从互联网读取文本文件

转载 作者:搜寻专家 更新时间:2023-11-01 08:03:48 24 4
gpt4 key购买 nike

我想读取远程文本文件并在 TextView 中显示其内容。我在下面编写了这段代码,但它没有从文本文件中获取任何信息。我怎样才能找到这个问题的原因或解决它?我的代码有什么问题吗?

    private void readFile()
{
try {
String path ="http://host.com/info.txt";
URL u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
Log.e("value",in.toString());
AssetManager mngr=getAssets();
ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
in.read(buffer); // Read from Buffer.
bo.write(buffer); // Write Into Buffer.
TextView text = (TextView) findViewById(R.id.TextView1);
text.setText(bo.toString());
bo.close();
}
catch (NetworkOnMainThreadException e) {
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

最佳答案

  1. 您是否向 list 文件添加了互联网许可?
  2. 您是否在单独的线程中启动您的代码(请不要捕获 NetworkOnMainThreadException)
  3. 检查 LogCat 你有什么异常?
  4. 删除了用于向服务器发送数据的c.setDoOutput(true);

这里应该是这样的:

new Thread() {
@Override
public void run() {
String path ="http://host.com/info.txt";
URL u = null;
try {
u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.connect();
InputStream in = c.getInputStream();
final ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
in.read(buffer); // Read from Buffer.
bo.write(buffer); // Write Into Buffer.

runOnUiThread(new Runnable() {
@Override
public void run() {
TextView text = (TextView) findViewById(R.id.TextView1);
text.setText(bo.toString());
try {
bo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
}.start();

关于Android 从互联网读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17141829/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com