码迷,mamicode.com
首页 > 编程语言 > 详细

Java中动态生成当前日期的文件

时间:2017-09-16 11:55:45      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:java;文件名自动生成;


1.Java中动态生成当前日期的文件名称并且将控制台的输出信息输入到文件中

    public static void SaveClonseToFile() throws IOException, FileNotFoundException {
        File f = new File(getCurrentDateFileName() + ".txt");
        f.createNewFile();
        FileOutputStream fileOutputStream = new FileOutputStream(f);
        PrintStream printStream = new PrintStream(fileOutputStream);
        System.setOut(printStream);  //将控制台信息输出到文件中
    }

    public static String getCurrentDateFileName() {
		SimpleDateFormat simpleDateFormat;
		simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
		Date date = new Date();
		String str = simpleDateFormat.format(date);
		return str; // 当前时间
    }


2.生成当前日期加随机的数的字符串用于生成文件名	
     public static String getRandomFileName() {
	 SimpleDateFormat simpleDateFormat;
		simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
		Date date = new Date();
		String str = simpleDateFormat.format(date);
	 Random random = new Random();
         int num = (int) (random.nexInt()*100+1);
		return str+num; // 当前时间
	}

3.判断指定的日期是星期几
     public static int dayForWeek(String pTime) throws Exception {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		c.setTime(format.parse(pTime));
		int dayOfWeek = 0;
		if (c.get(Calendar.DAY_OF_WEEK) == 1) {
			dayOfWeek = 7;
		} else {
			dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
		}
		return dayOfWeek;
	}		
	


本文出自 “Apple” 博客,请务必保留此出处http://59465168.blog.51cto.com/5268021/1965751

Java中动态生成当前日期的文件

标签:java;文件名自动生成;

原文地址:http://59465168.blog.51cto.com/5268021/1965751

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!