Java中動態生成當前日期的文件
阿新 • • 發佈:2017-09-16
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中動態生成當前日期的文件