1 回答

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超4個(gè)贊
正斜杠總是有效,在 Windows 上也是如此。
并且反斜線絕對(duì)不適用于 URL。
在您對(duì) Abra 做出回應(yīng)后,我更了解您想做什么。您需要將 URL 作為輸入流打開(kāi),并創(chuàng)建一個(gè)指向本地文件的新輸出流。
文件理解 http 布局,因此您可以使用它來(lái)獲取包含文件名的 url 的最后一部分(參見(jiàn)變量 f):
File 也有一個(gè)帶有 2 個(gè)參數(shù)的構(gòu)造
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);
? ? ? ? }
? ? }
}
添加回答
舉報(bào)