文件复制

在如今的功能需求中,文件的处理基本上都是会涉及到的,应该说是一个很经常使用的功能
public static void main(String[] args) throws IOException {
        String url = "test.txt";
        String suffixName = url.substring(url.lastIndexOf("."));
        //获取要复制的文件路径
        FileInputStream fileInputStream = new FileInputStream("F:\\" + url);
        String filePath = "F:\\test\\";
        File dest = new File(filePath+System.currentTimeMillis());
        // 判断文件路径是否存在,不存在就建立路径
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }
        //获取要写入的文件路径
        FileOutputStream fileOutputStream = new FileOutputStream(dest + suffixName);
        //获取要复制的的文件通道
        FileChannel fileChannelInput = fileInputStream.getChannel();
        //获取要写入的文件通道
        FileChannel fileChannelOutput = fileOutputStream.getChannel();
        // 将要复制文件通道的数据,写入到要写入的文件通道
        fileChannelInput.transferTo(0, fileChannelInput.size(), fileChannelOutput);
        try {
            if (fileInputStream != null){
                fileInputStream.close();
            }
            if (fileChannelInput != null) {
                fileChannelInput.close();
            }
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
            if (fileChannelOutput != null) {
                fileChannelOutput.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
复制代码
相关文章
相关标签/搜索