標籤:runtime ring break file ber tar dep new sim
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.text.SimpleDateFormat;
- import java.util.Calendar;
-
- /**
- * 讀取檔案建立時間和最後修改時間
- */
- public class ReadFileTime {
-
- public static void main(String[] args) {
- getCreateTime();
- getModifiedTime_1();
- getModifiedTime_2();
- }
-
- /**
- * 讀取檔案建立時間
- */
- public static void getCreateTime(){
- String filePath = "C:\\test.txt";
- String strTime = null;
- try {
- Process p = Runtime.getRuntime().exec("cmd /C dir "
- + filePath
- + "/tc" );
- InputStream is = p.getInputStream();
- BufferedReader br = new BufferedReader(new InputStreamReader(is));
- String line;
- while((line = br.readLine()) != null){
- if(line.endsWith(".txt")){
- strTime = line.substring(0,17);
- break;
- }
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- System.out.println("建立時間 " + strTime);
- //輸出:建立時間 2009-08-17 10:21
- }
- /**
- * 讀取檔案修改時間的方法1
- */
- @SuppressWarnings("deprecation")
- public static void getModifiedTime_1(){
- File f = new File("C:\\test.txt");
- Calendar cal = Calendar.getInstance();
- long time = f.lastModified();
- cal.setTimeInMillis(time);
- //此處toLocalString()方法是不推薦的,但是仍可輸出
- System.out.println("修改時間[1] " + cal.getTime().toLocaleString());
- //輸出:修改時間[1] 2009-8-17 10:32:38
- }
-
- /**
- * 讀取修改時間的方法2
- */
- public static void getModifiedTime_2(){
- File f = new File("C:\\test.txt");
- Calendar cal = Calendar.getInstance();
- long time = f.lastModified();
- SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- cal.setTimeInMillis(time);
- System.out.println("修改時間[2] " + formatter.format(cal.getTime()));
- //輸出:修改時間[2] 2009-08-17 10:32:38
- }
- }
Java讀取檔案建立時間和最後修改時間