Java Android-如何通过url获取pdf文件大小?
当我运行这些方法时,我的程序将崩溃 我想以字符串形式获取pdf文件长度,并在TextView上设置此文本Java Android-如何通过url获取pdf文件大小?,java,android,Java,Android,当我运行这些方法时,我的程序将崩溃 我想以字符串形式获取pdf文件长度,并在TextView上设置此文本 private String getSize(String url1){ URL url = null; try { url = new URL(url1); } catch (MalformedURLException e) { e.printStackTrace(); } URLConnection conne
private String getSize(String url1){
URL url = null;
try {
url = new URL(url1);
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection connection = null;
try {
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
final int length = connection.getContentLength();
String size = "" + length;
return size;
}
使用以下代码获取文件大小:
URL url = new URL("http://testserver.com/file.pdf");
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
int fileSize = urlConnection.getContentLength();
textView.setText(String.valueOf(fileSize));
尝试使用
URLConnection.getContentLength()
如下
URL url = new URL("http://your_url.com/filename.pdf");
final URLConnection connection = url.openConnection();
final int length = connection.getContentLength();
Log.d(tag, String.valueof(length));
你的回答是:-
private String getSize(String url1){
URL url = null;
try {
url = new URL(url1);
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection connection = null;
try {
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
final int length = connection.getContentLength();
String size = "" + String.valueof(length);
return size;
}
记住在menifest中授予INTERNET权限:-
<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.INTERNET" />
<application ...
</manifest>
...
你说“会被压碎”是什么意思?它会崩溃吗?如果是,请提供Stacktrace/错误信息。如果遇到catch块,则连接仍将是null
-因此connection.getContentLength()
将产生NullPointerException
我发现我的应用程序因[urlConnection.getContentLength();]而崩溃。我不知道我该怎么办。