美文网首页
java复制文件到指定文件夹

java复制文件到指定文件夹

作者: 墨色尘埃 | 来源:发表于2017-07-10 16:37 被阅读0次
/**
     * 将InputStream写入本地文件
     * 输入流
     *
     * @throws IOException
     */

    private void writeToLocal(String fileName, InputStream input)
            throws IOException {
        String destDirName = "E:/temp1";
        createDir(destDirName);
        String dirFile = destDirName + "/" + fileName;
        int index;
        byte[] bytes = new byte[1024];
        FileOutputStream downloadFile = new FileOutputStream(dirFile);
        while ((index = input.read(bytes)) != -1) {
            downloadFile.write(bytes, 0, index);
            downloadFile.flush();
        }
        downloadFile.close();
        input.close();
    }

    /**
     * 创建文件夹
     * @param destDirName
     * @return
     */
    public boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {
            System.out.println("创建目录" + destDirName + "失败,目标目录已经存在");
            return false;
        }
        if (!destDirName.endsWith(File.separator)) {
            destDirName = destDirName + File.separator;
        }
        //创建目录
        if (dir.mkdirs()) {
            System.out.println("创建目录" + destDirName + "成功!");
            return true;
        } else {
            System.out.println("创建目录" + destDirName + "失败!");
            return false;
        }
    }

    /**
     * 截取图片后缀名
     */
    public String getSuffixal(String name) {
        String str = name.substring(name.length() - 4, name.length());
        return str;
    }
//测试代码
File file = new File("e:/QQ截图20170503093317.png");
        FileInputStream fis = new FileInputStream(file);
        int random = new Random().nextInt(100);
        writeToLocal(random+".png", fis);
        System.out.print("成功");
IO流读取.png

相关文章

网友评论

      本文标题:java复制文件到指定文件夹

      本文链接:https://www.haomeiwen.com/subject/okcuhxtx.html