简体   繁体   English

如何逃避新文件中的斜线?

[英]How to escape problem slashes in new File?

I have this : 我有这个 :

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

I also tried this: 我也试过这个:

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

But I'm getting an error: 但是我遇到一个错误:

java.io.FileNotFoundException: http:\\cdn\\test.jpg (The filename, directory name, or volume label syntax is incorrect) java.io.FileNotFoundException:http:\\ cdn \\ test.jpg(文件名,目录名或卷标签语法不正确)

Any suggesion how can i fix this?? 任何建议我该如何解决?

cdn is url : http://cdn cdn是url: http:// cdn

What I'm trying to achieve is to save the file on http://cdn/test.jpg 我想要实现的是将文件保存在http://cdn/test.jpg上

Forward slash always works, also on Windows. 正斜杠始终有效,在Windows上也是如此。 See " forward-slash-or-backslash " 请参阅“ 正斜杠或反斜杠

And backward slash will definitely not work on URLs. 反斜杠绝对不会在URL上起作用。

After your response on Abra I understand better what you want to do. 在您回答了Abra之后,我会更好地了解您想做什么。 You need to open the URL as a inputstream and create a new outputstream wchich points to your local file. 您需要打开URL作为输入流,并创建指向本地文件的新输出流。

File understands http layout so you can use it to get the last part of the url which contains the name of the file (see variable f): 文件了解http布局,因此您可以使用它来获取包含文件名的url的最后一部分(请参见变量f):

File also has a constructor with 2 arguments: path + filename. File还具有一个带有2个参数的构造函数:path + filename。 If you use this one you don't need to bother forward or backward slash problems. 如果使用此斜杠,则无需理会正斜杠问题。

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);
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM