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