如何在新文件中转义问题斜杠?

我有这个 :

fos = new FileOutputStream(new File(cdn.replace('/', File.separatorChar), request.getEntity().getNewfilepath()));

我也试过这个:

fos = new FileOutputStream(new File(cdn, request.getEntity().getNewfilepath()));

但我收到一个错误:

java.io.FileNotFoundException: http:\cdn\test.jpg(文件名、目录名或卷标语法不正确)

任何建议我该如何解决?

cdn是网址:http://cdn

我想要实现的是将文件保存在http://cdn/test.jpg


慕标琳琳
浏览 80回答 1
1回答

繁花不似锦

正斜杠总是有效,在 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);        }    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java