为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕标琳琳 2023-04-26 15:57:31
我有这个 :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
查看完整描述

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

        }

    }


}


查看完整回答
反对 回复 2023-04-26
  • 1 回答
  • 0 关注
  • 77 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信