动态生成该目录结构和文件

动态生成该目录结构和文件: 2019-08-23/111/222222.jpg
2019-08-23 : 第一层必须为日期格式名称文件夹.
111/222222.jpg : 随机生成该文件夹名(不超过3位数),和文件名(不超过6位数).

import java.io.File;
import java.io.IOException;
import java.util.Random;

public class Test4 {

	public static void main(String[] args) throws IOException {
		while (true) {
			//将随机得到的字符串数字,转换为int基本数据类型
			int year = Integer.parseInt(random(4));
			int month = Integer.parseInt(random(2));
			int day = Integer.parseInt(random(2));
			//控制年,月,日的随机产生,只有符合的才会被作为路径
			//File.separator:直接使用Flie类的静态属性,来实现文件名分隔符,这样可以根据不同的jdk获取到不同平台的分隔符,保证代码的跨平台性
			if ((year >= 1900 && year <= 2020) && (month >= 1 && month <= 12)
					&& (day >= 1 && day <= 31)) {
				String folderName = year + "-" + month + "-" + day + File.separator
						+ random(3);
				String fileName = folderName + File.separator + random(6) + ".jpg";
				//路径
				File f1 = new File(folderName);
				File f2 = new File(fileName);
				//创建文件夹和文件
				boolean mkdirs = f1.mkdirs();
				System.out.println(mkdirs);
				boolean createNewFile = f2.createNewFile();
				System.out.println(createNewFile);
				//展示完整路径
				String path = f2.getPath();
				System.out.println(path);
				
				break;
			}
		}
		
			
		//利用随机数产生器,然后拼接字符串,作为路径(不控制年,月,日)
//		String folderName = random(4).concat(
//				"-" + random(2).concat("-" + random(2)))+"/"+random(3);
//		String fileName =folderName+"/"+random(6)+".jpg";
//   
//		File f1 = new File(folderName);
//		File f2 = new File(fileName);
//
//		boolean mkdirs = f1.mkdirs();
//		System.out.println(mkdirs);
//		boolean createNewFile = f2.createNewFile();
//		System.out.println(createNewFile);

	}
//随机数产生器
	//因为要产生固定位数的随机数,所以采用字符串拼接,用循环控制位数
	public static String random(int places) {
		StringBuilder num = new StringBuilder();
		Random ran = new Random();
		String new_nums = " ";
		for (int i = 0; i < places; i++) {
			StringBuilder nums = num.append(ran.nextInt(10));
			new_nums = nums.toString();
		}
		return new_nums;
	}
}


路径正确!

发布了15 篇原创文章 · 获赞 11 · 访问量 965

猜你喜欢

转载自blog.csdn.net/qq_41414186/article/details/100043090