try {
int count;
URL url = new URL("http://www.exampleserver.com/file names.txt");
URLConnection connection = url.openConnection();
connection.setReadTimeout(TIMEOUT_CONNECTION);
connection.setConnectTimeout(TIMEOUT_SOCKET);
connection.setRequestProperty("connection", "close");
connection.connect();
int lengthOfFile = connection.getContentLength();
long total = 0;
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(BasindaOneCikanDosyalar);
byte data[] = new byte[40096];
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (IOException e1) {
e1.printStackTrace();
}
我正在使用此算法,但如果文件名包含空格,我会得到 java.io.FileNotFoundException 和 getResponseCode:400。
是否有库或不同的下载 URL 算法?
最佳答案
您需要对 url 进行转义,并使其像下面这样:
http://www.exampleserver.com/file%20names.txt
在你的代码中做这样的事情:
URI uri = new URI("http", "www.exampleserver.com", "/file names.txt", null);
URL url = uri.toURL();
关于java - 如果文件名包含空格,我们如何在 Android 中使用 URLConnection 下载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26006278/