Java基础回顾练习之(随机命名+IO流文件拷贝)

Java基础回顾练习

(随机命名+文件拷贝)

Java 效果测试

public static void main(String[] args) throws Exception {
    File resourceFile = new File("C:\\Users\\zhangxu\\Pictures\\Camera Roll\\0.jpeg");
    String filename = generateRandomFilename();
    File targetFile = new File("E:\\photo\\c\\"+filename+".jpeg");
    copyFile(resourceFile,targetFile);
}
/**
 * 复制文件
 *
 * @param resource
 * @param target
 */
public static void copyFile(File resource, File target) throws Exception {
    // 输入流 --> 从一个目标读取数据
    // 输出流 --> 向一个目标写入数据

    long start = System.currentTimeMillis();

    // 文件输入流并进行缓冲
    FileInputStream inputStream = new FileInputStream(resource);
    BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
    
    FileOutputStream outputStream = new FileOutputStream(target);
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);

    // 缓冲数组
    // 大文件 可将 1024 * 2 改大一些,但是 并不是越大就越快
    byte[] bytes = new byte[1024 * 2];
    int len = 0;
    while ((len = inputStream.read(bytes)) != -1) {
        bufferedOutputStream.write(bytes, 0, len);
    }
    // 刷新输出缓冲流
    bufferedOutputStream.flush();
    //关闭流
    bufferedInputStream.close();
    bufferedOutputStream.close();
    inputStream.close();
    outputStream.close();

    long end = System.currentTimeMillis();

    System.out.println("耗时:" + (end - start) / 1000 + " s");
}



/**
 *  * 生成随机文件名
 * */

    public static String generateRandomFilename(){

        String RandomFilename = "";

        Random rand = new Random();//生成随机数

        int random = rand.nextInt();

        Calendar calCurrent = Calendar.getInstance();

        int intDay = calCurrent.get(Calendar.DATE);

        int intMonth = calCurrent.get(Calendar.MONTH) + 1;

        int intYear = calCurrent.get(Calendar.YEAR);

        String now = String.valueOf(intYear) + "_" + String.valueOf(intMonth) + "_" +

                String.valueOf(intDay) + "_";

        System.out.println("生成于今日的文件名前缀为:"+now);;

        RandomFilename = now + String.valueOf(random > 0 ? random : ( -1) * random) + ".";

        return RandomFilename;

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值