JAVA读取网络文件生成File类型和输出到本地

疯一样的男子
疯一样的男子
发布于 2022-08-15 / 2 阅读
0
0

JAVA读取网络文件生成File类型和输出到本地

public class Test2 {

    public static void main(String[] args) throws Exception {
        //获取网络资源文件并生成 File类型对象
        File file = getFile("http://file.vipspt.cn/oss/enterpriseImg/20220815/41e94133v00.jpeg");
        //文件输出到本地
        outputFile("D://test", file);
    }

    /**
     * file类型转为MockMultipartFile类型
     */
    private static MultipartFile getMultipartFile() throws Exception {
        File file = new File("D:\\test.png");
        //file类型转为MockMultipartFile类型
        MockMultipartFile media = new MockMultipartFile(file.getName(), file.getPath(), ContentType.APPLICATION_OCTET_STREAM.toString(), new FileInputStream(file));
        return media;
    }

    /**
     * 读取网络资源文件
     *
     * @param url
     * @return
     * @throws Exception
     */
    private static File getFile(String url) throws Exception {
        //读取图片类型
        String fileName = url.substring(url.lastIndexOf("."), url.length());
        File file = null;

        URL urlfile;
        InputStream inStream = null;
        OutputStream os = null;
        try {
            //创建临时文件
            file = File.createTempFile("new_url", fileName);
            //获取文件
            urlfile = new URL(url);
            inStream = urlfile.openStream();
            os = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != inStream) {
                    inStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    /**
     * 文件输出方法
     *
     * @param outputPath 输出路径
     * @param file       文件对象
     */
    public static void outputFile(String outputPath, File file) {
        File wFile = new File(outputPath, file.getName());
        OutputStream output = null;
        try {
            output = new FileOutputStream(wFile);
            InputStream input = new FileInputStream(file);
            int len = 0; // 保存每次的读取数据长度
            byte[] data = new byte[2048];
            while ((len = input.read(data)) != -1) {
                output.write(data, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


评论