1 回答

TA貢獻1851條經驗 獲得超4個贊
正斜杠總是有效,在 Windows 上也是如此。
并且反斜線絕對不適用于 URL。
在您對 Abra 做出回應后,我更了解您想做什么。您需要將 URL 作為輸入流打開,并創建一個指向本地文件的新輸出流。
文件理解 http 布局,因此您可以使用它來獲取包含文件名的 url 的最后一部分(參見變量 f):
File 也有一個帶有 2 個參數的構造
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
public class InternetReader {
? ? private static void copyInputStreamToOutputstream(InputStream in, OutputStream out) throws IOException {
? ? ? ? byte[] buf = new byte[1024];
? ? ? ? int len;
? ? ? ? while ((len = in.read(buf)) > 0) {
? ? ? ? ? ? out.write(buf, 0, len);
? ? ? ? }
? ? }
? ? public static void main(String[] args) throws IOException {
? ? ? ? File f = new File("http://google.be/test.jpg");
? ? ? ? System.out.println(f.getName());
? ? ? ? File localPath = new File("/cdn/opt");
? ? ? ? File localDestination = new File(localPath, f.getName());
? ? ? ? URL remoteURL = new URL("http://google.be/test.jpg");
? ? ? ? try (InputStream is = remoteURL.openStream(); OutputStream os = new FileOutputStream(localDestination)) {
? ? ? ? ? ? copyInputStreamToOutputstream(is, os);
? ? ? ? }
? ? }
}
添加回答
舉報