java文件I/O

文件访问时间识别

代码1

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 hello {  

    public static void main(String[] args) {  
        getCreateTime();  
        //getModifiedTime_1();  
        getModifiedTime_2();          
    }  

    /** 
     * 读取文件创建时间 
     */  
    public static void getCreateTime(){  
        String filePath = "/home/dear/code/sh/1.sh";  
        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(".sh")){  
                    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("/home/dear/code/sh/1.sh");              
        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  
    }  
}  

代码2

NIO.2详解

import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ObtainPath
{
   public static void main(String[] args)
   {
      Path path = Paths.get("a", "b");
      System.out.println(path);

      path = Paths.get(FileSystems.getDefault().getSeparator() + "a", "b", "c");
      System.out.println(path);

      path = Paths.get("a", ":", "b");
      System.out.println(path);
   }
}
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;

public class hello
{
   public static void main(String[] args)
   {
      dumpPathInfo(Paths.get("a", "b", "c"));

      FileSystem fs = FileSystems.getDefault();
      Iterable<Path> roots = fs.getRootDirectories();
      for(Path root: roots)
      {
         dumpPathInfo(Paths.get(root.toString(), "a", "b", "c"));
         break;
      }
   }

   static void dumpPathInfo(Path path)
   {
      System.out.printf("Path: %s%n", path);
      System.out.printf("Filename: %s%n", path.getFileName());
      System.out.println("Components");
      for (int i = 0; i < path.getNameCount(); i++)
         System.out.printf("   %s%n", path.getName(i));
      System.out.printf("Parent: %s%n", path.getParent());
      System.out.printf("Root: %s%n", path.getRoot());
      System.out.printf("Absolute: %b%n", path.isAbsolute());
      System.out.printf("Subpath [0, 2): %s%n%n", path.subpath(0, 2));   
   }
}
import java.nio.file.Path;
import java.nio.file.Paths;

public class hello
{
   public static void main(String[] args)
   {
      Path path1 = Paths.get("reports", ".", "2015", "jan");
      System.out.println(path1);
      System.out.println(path1.normalize());
      path1 = Paths.get("reports", "2015", "..", "jan");
      System.out.println(path1.normalize());
      System.out.println();

      path1 = Paths.get("reports", "2015", "jan");
      System.out.println(path1);
      System.out.println(path1.relativize(Paths.get("reports", "2016", "mar")));
      try
      {
         System.out.println(path1.relativize(Paths.get("/reports", "2016", 
                                                       "mar")));
      }
      catch (IllegalArgumentException iae)
      {
         iae.printStackTrace();
      }
      System.out.println();

      path1 = Paths.get("reports", "2015");
      System.out.println(path1);
      System.out.println(path1.resolve("apr"));
      System.out.println(path1.resolve("/apr"));
   }
}
/*************************************************************************
    > File Name: PathAttrib.java
    > Author: 
    > Mail: 
    > Created Time: 2016年09月21日 星期三 17时07分45秒
 ************************************************************************/

import java.io.IOException;

import java.nio.file.attribute.FileTime;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class PathAttrib
{
   public static void main(String[] args) throws IOException
   {
      if (args.length != 1)
      {
         System.err.println("usage: java PathAttrib path-object");
         return;
      }

      Path path = Paths.get(args[0]);
      System.out.printf("Last modified time: %s%n", Files.getLastModifiedTime(path));
      System.out.printf("Last access time: %s%n", (FileTime)Files.getAttribute(path, "lastAccessTime"));
      System.out.printf("Owner: %s%n", Files.getOwner(path));
      System.out.printf("Size: %d%n", Files.size(path));
   }
}

文件访问时间修改

import java.io.File;
import java.util.Date;

public class FileUtil {

  public void changeFiletime(String filename) {

    File fileToChange = new File(filename);

    //读取文件的最后修改时间
    Date filetime = new Date(fileToChange.lastModified());
    System.out.println(filetime.toString());

    //将最近修改时间修改为当前时间
    if (fileToChange.setLastModified(System.currentTimeMillis()))
      System.out.println("Success!");
    else
      System.out.println("Failed!");

    //读取最近更新时间
    filetime = new Date(fileToChange.lastModified());
    System.out.println(filetime.toString());

  }

  public static void main(String[] args) {
    FileUtil fileutil = new FileUtil();
    fileutil.changeFiletime("C:\\\\temp\\\\myfile.txt");
  }
}

手机文件遍历

代码1

// 获取当前目录下所有的mp4文件
    public static Vector<string> GetVideoFileName(String fileAbsolutePath) {
        Vector<string> vecFile = new Vector<string>();
        File file = new File(fileAbsolutePath);
        File[] subFile = file.listFiles();

        for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
            // 判断是否为文件夹
            if (!subFile[iFileLength].isDirectory()) {
                String filename = subFile[iFileLength].getName();
                // 判断是否为MP4结尾
                if (filename.trim().toLowerCase().endsWith(".mp4")) {
                    vecFile.add(filename);
                }
            }
        }
        return vecFile;
}

代码2

import java.io.IOException;

import java.io.*;

public class hello 
{
   public static void main(String[] args) throws IOException
   {
       String path="/home/dear/code";
       int count =countFile(path);
       System.out.println("文件有"+count+"个");
//      Path path = Paths.get("/home/dear/code/sh/2.sh");
//      System.out.printf("Last modified time: %s%n", Files.getLastModifiedTime(path));
//      System.out.printf("Last access time: %s%n", (FileTime)Files.getAttribute(path, "lastAccessTime"));
//      System.out.printf("Owner: %s%n", Files.getOwner(path));
//      System.out.printf("Size: %d%n", Files.size(path));
   }
   static int result= 0;
   public static int countFile(String path){
        //创建file的对象
         File file  = new File(path);
         //判断路径是否存在
          if(!file.exists()){
              System.out.println("提供的路径不存在!");
          return 0;
          }
          //将的得到的路径存储到数组中
          File[] fs =file.listFiles();

          //判断得到的是否是一个文件
          if(fs==null){
              System.out.println("提供的路径不是一个标准文件");
              return 0;
          }


          //遍历数组
          for(int i =0;i<fs.length;i++){
              File f = fs[i];
              String str = f.getAbsolutePath();


          if(f.isFile()){
              result++;
              System.out.println("找到文件"+str);

          }else if(f.isDirectory()){
                     //调用递归来处理
              result +=countFile(str);
          }
         }
        return result;
        }
}

文件遍历+访问时间+距离时间

import java.io.*;
import java.util.Date; 
import java.text.ParseException;
import java.text.SimpleDateFormat;  
import java.util.Calendar;  

public class hello 
{
   public static void main(String[] args) throws IOException
   {
       String path="/home/dear/Desktop";
       int count =countFile(path);
       System.out.println("文件有"+count+"个");
   }
   static int result= 0;
   static Date now=new Date();
   static long nowtime=now.getTime();
   public static int countFile(String path){
        //创建file的对象
         File file  = new File(path);
         //判断路径是否存在
          if(!file.exists()){
              System.out.println("提供的路径不存在!");
          return 0;
          }
          //将的得到的路径存储到数组中
          File[] fs =file.listFiles();

          //判断得到的是否是一个文件
          if(fs==null){
              System.out.println("提供的路径不是一个标准文件");
              return 0;
          }


          //遍历数组
          for(int i =0;i<fs.length;i++){
              File f = fs[i];
              String str = f.getAbsolutePath();
              //文件
              if(f.isFile()){
                  result++;
                  System.out.println("找到文件"+str);
                  String strTime = null;  
                    try {  
                        Process p = Runtime.getRuntime().exec("stat " + str);  
                        InputStream is = p.getInputStream();   
                        BufferedReader br = new BufferedReader(new InputStreamReader(is));             
                        String line;  
                        while((line = br.readLine()) != null){  
                            if(line.endsWith("00")&&line.startsWith("Access")){  
                                strTime = line.substring(8,27);
                                break;
                            }                             
                         }
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        try{
                            Date access_time=formatter.parse(strTime);
                            long time=access_time.getTime();
                            System.out.println((nowtime-time)/3600/1000/24);
                        }
                        catch(ParseException pppp){
                            pppp.printStackTrace();
                            }

                    } catch (IOException e) {  
                        e.printStackTrace();  
                    }
                    System.out.println(strTime); 
              }
              //目录
              else if(f.isDirectory()){
                         //调用递归来处理
                  result +=countFile(str);
              }
         }
        return result;
   }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值