您好我使用HttpURLConnection
获取txt
文件的内容,我想知道该文件的大小,我使用内容长度方法,但它返回错误的值,例如在此代码中该文件的大小是17509但它返回5147?
所以任何帮助?
非常感谢提前:)。
new Thread() {
@Override
public void run() {
String path = parser.getValue(e, "txt");
URL u = null;
try {
u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u
.openConnection();
c.setRequestMethod("GET");
c.connect();
int lenghtOfFile = c.getContentLength();
InputStream in = c.getInputStream();
final ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
long total = 0;
Log.i("p1",""+lenghtOfFile);
while ((count = in.read(buffer)) != -1) {
total += count;
Log.i("p2",""+total);
bo.write(buffer, 0, count);
}
bo.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
答案 0 :(得分:1)
内容长度是服务器设置的标头。我会检查以确保您的服务器返回正确的内容长度。您可以使用cUrl执行此操作:
curl -v http://path/to/file.txt
这应该显示已发送和返回的标头。
答案 1 :(得分:1)
我能想到的一个快速解决方法是忽略内容长度和读取输入流,直到没有什么可读的。
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(8192);
int read = inputStream.read();
while (read != -1) {
byteArrayOutputStream.write((byte) read);
read = inputStream.read();
}
byteArrayOutputStream.flush();
buf = byteArrayOutputStream.toByteArray();