InputStream 连接到 URL 但 returns 什么都没有
InputStream connects to URL but returns nothing
我将 InputStream 设置为在线托管的原始文本文件的 url。每一行都是不同的说法,方法应该是从文件中获取文本并将其保存到缓存文件夹中以供在应用程序中使用。连接到 URL 没有问题,否则它会在日志中给出 FileNotFoundException(对此进行了测试),并且生成了缓存文件但它没有将任何内容保存到缓存文件中(具有权限,也进行了测试)。是什么导致了这种情况?
从页面读取的代码:
protected Void doInBackground(Void... Params) {
try {
File quote = new File("Absolute path to cache");
URL url = new URL("URL of file");
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(quote);
byte[] buffer = new byte[is.available()];
is.read(buffer);
os.write(buffer);
is.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
根据连接的不同,is.available()
可能可用也可能不可用 - 函数将 return 归零并导致您不向输出流写入任何内容。
执行此操作的最佳方法是读取直到无法读取更多数据 - 例如参见 here。
试试这个。
@Override
protected void doInBackground(Void... Params) {
try{
File quote = new File("Absolute path to cache");
URL url = new URL("URL of file");
HttpURLConnection httpCon =
(HttpURLConnection) url.openConnection();
if(httpCon.getResponseCode() != 200)
throw new Exception("Failed to connect");
}
InputStream is = httpCon.getInputStream();
OutputStream os = new FileOutputStream(quote);
byte[] buffer = new byte[is.available()];
is.read(buffer);
os.write(buffer);
is.close();
os.close();
}catch(Exception e){
e.printTrackTrace();
}
return null;
}
我将 InputStream 设置为在线托管的原始文本文件的 url。每一行都是不同的说法,方法应该是从文件中获取文本并将其保存到缓存文件夹中以供在应用程序中使用。连接到 URL 没有问题,否则它会在日志中给出 FileNotFoundException(对此进行了测试),并且生成了缓存文件但它没有将任何内容保存到缓存文件中(具有权限,也进行了测试)。是什么导致了这种情况?
从页面读取的代码:
protected Void doInBackground(Void... Params) {
try {
File quote = new File("Absolute path to cache");
URL url = new URL("URL of file");
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(quote);
byte[] buffer = new byte[is.available()];
is.read(buffer);
os.write(buffer);
is.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
根据连接的不同,is.available()
可能可用也可能不可用 - 函数将 return 归零并导致您不向输出流写入任何内容。
执行此操作的最佳方法是读取直到无法读取更多数据 - 例如参见 here。
试试这个。
@Override
protected void doInBackground(Void... Params) {
try{
File quote = new File("Absolute path to cache");
URL url = new URL("URL of file");
HttpURLConnection httpCon =
(HttpURLConnection) url.openConnection();
if(httpCon.getResponseCode() != 200)
throw new Exception("Failed to connect");
}
InputStream is = httpCon.getInputStream();
OutputStream os = new FileOutputStream(quote);
byte[] buffer = new byte[is.available()];
is.read(buffer);
os.write(buffer);
is.close();
os.close();
}catch(Exception e){
e.printTrackTrace();
}
return null;
}