当前位置: 移动技术网 > IT编程>开发语言>Java > JavaSE文件操作工具类FileUtil详解

JavaSE文件操作工具类FileUtil详解

2019年09月06日  | 移动技术网IT编程  | 我要评论

国际老虎日,莫妮卡·贝鲁奇r级电影,常春晓奋斗

本文实例为大家分享了javase文件操作工具类fileutil的具体代码,供大家参考,具体内容如下

先展示一下文件工具类中打印文件夹树形结构的结果:

代码如下:

package com.mjq.iotest;
 
import java.io.file;
import java.io.fileinputstream;
import java.io.fileoutputstream;
import java.io.filenamefilter;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
import java.util.regex.matcher;
import java.util.regex.pattern;
 
/**
 * 练习file api 
 * @author administrator
 *
 */
public class fileutil 
{
 /**
 * 单例模式
 *//*
 private static fileutil instance = null;
 private fileutil()
 {
 }
 public static fileutil getinstance()
 {
 synchronized (fileutil.class) 
 {
  if(null == instance)
  {
  instance = new fileutil();
  }
 }
 return instance;
 }*/
 /**
 * 创建文件/文件夹
 * @param path 路径
 * @return 是否创建成功
 * @throws exception 
 */
 public static boolean creatfile(string path) throws exception
 {
 if(null == path || path.length() == 0)
 {
  throw new exception("路径不正确!");
 }
 file file = new file(path);
 //如果路径存在,则不创建
 if(!file.exists())
 {
  if(file.isdirectory())
  {
  //文件夹
  file.mkdirs();
  // file.mkdir();  创建单层路径 file.mkdirs() 可以创建多层路径
  return true;
  }
  else
  {
  //文件  先创建父路径,然后再创建文件
  string dirpath = path.substring(0,path.lastindexof(file.separator));
  file dirfile = new file(dirpath);
  if(!dirfile.exists())
  {
   dirfile.mkdirs();
  }
  file filefile = new file(path);
  try {
   filefile.createnewfile();
   return true;
  } catch (ioexception e) {
   // todo auto-generated catch block
   e.printstacktrace();
  }
  }
 }
 else
 {
  throw new exception("文件已存在!");
 }
 return false;
 } 
 /**
 * 删除文件/文件夹及其中的所有子文件夹和文件
 * @return
 * @throws exception 
 */
 public static void deletefile(string filepath) throws exception
 {
 if(null == filepath || filepath.length() == 0)
 {
  throw new exception("filepath:"+filepath+"路径不正确!");
 }
 file file = new file(filepath);
 if(!file.exists())
 {
  throw new exception("filepath:"+filepath+"文件不存在!");
 }
 if(file.isfile())
 {
  file.delete();
 }
 if(file.isdirectory())
 {
  file [] childfiles = file.listfiles();
  if(null != childfiles && childfiles.length!=0)
  {
  //循环递归删除
  for(file childfile:childfiles)
  {
   deletefile(childfile.getabsolutepath());
  }
  }
  file.delete();
 }
 }
 /**
 * 获取文件基本信息
 * @param file
 */
 public static void getbaseinfo(file file)
 {
 //文件绝对路径  文件大小  文件是否是文件夹   文件是否是文件   文件是否可读   文件是否可写      文件是否可执行     文件修改时间    文件父目录名
 //文件所在分区总大小  未使用大小  可用大小
 system.out.println("文件基本信息如下:");
 system.out.println("文件绝对路径:"+file.getabsolutepath());
 system.out.println("文件名称:"+file.getname());
 system.out.println("文件大小:"+file.length());
 system.out.println("文件是否是文件夹:"+file.isdirectory());
 system.out.println("文件是否是文件:"+file.isfile());
 system.out.println("文件是否可读:"+file.canexecute());
 system.out.println("文件是否可读:"+file.canread());
 system.out.println("文件是否可写:"+file.canwrite());
 system.out.println("文件修改时间:"+file.lastmodified());
 system.out.println("文件父目录名称:"+file.getparent());
 system.out.println("文件所在分区大小:"+file.gettotalspace()/1024/1024+"mb");
 system.out.println("文件所在分区未使用大小:"+file.getfreespace()/1024/1024+"mb");
 system.out.println("文件所在分区可用大小:"+file.getusablespace()/1024/1024+"mb");
 system.out.println("文件夹结构如下图:");
 try {
  printfilestructure(file,1);
 } catch (exception e) {
  // todo auto-generated catch block
  e.printstacktrace();
 }
 }
 /**
 * 打印文件路径
 * @param file
 * @param deepth
 * @throws exception 
 */
 public static void printfilestructure(file file ,int deepth) throws exception
 {
 if(!file.exists())
 {
  throw new exception("文件路径不存在!");
 }
 if(!file.ishidden())
 {
  if(file.isfile())
  {
  //直接打印
  printfile(file,deepth);
  return;
  }
  if(file.isdirectory())
  {
  //先打印自身,然后递归打印子文件夹和子文件
  printfile(file,deepth);
  file [] childfiles = file.listfiles();
  if(null != childfiles && childfiles.length>0)
  {
   deepth++;
   for(file childfile : childfiles)
   {
   printfilestructure(childfile ,deepth);
   }
  }
  }
 }
 
 }
 /**
 * 打印文件夹树形结构
 * @param file
 * @param deepth
 */
 public static void printfile(file file ,int deepth)
 {
 string name = file.getname();
 stringbuffer sb = new stringbuffer();
 stringbuffer tempsb = new stringbuffer();
 for(int i =0;i<deepth;i++)
 {
  tempsb.append("   ");
 }
 sb.append(tempsb);
 sb.append("|"+"\n");
 sb.append(tempsb);
 sb.append("------"+name);
 system.out.println(sb.tostring());
 }
 
 /**
 * 删除特定的文件
 * @return
 * @throws exception 
 */
 public static void deletenamedfile(string filepath,string regex) throws exception
 {
 file file = new file(filepath);
 if(!file.exists())
 {
  throw new exception("文件不存在!");
 }
 //匿名内部类实现 filenamefilter 接口种的accept()方法,使用在正则表达式进行匹配
 //accept(file dir,string name) 使用当前文件对象  和  当前文件的名称 进行文件是否符合要求的标准判断;
 /*
  =======================================================================================
  file file = new file(".");
 string [] namelist = file.list((dir,name) -> name.endswith(".java") || new file(name).isdirectory());
 for(string name : namelist)
 {
  system.out.println(name);
 }
 ========================================================================================
 这里使用lamda表达式实现filenamefilter 接口种的accept()方法
 */
 file[] filelist = file.listfiles(new filenamefilter(){
 
  /**
  * 使用正则表达式进行匹配
  * @param regexstr
  * @return
  */
  private boolean regexmatch(string name,string regexstr)
  {
  pattern pattern = pattern.compile(regexstr);
  matcher matcher = pattern.matcher(name);
  return matcher.find();
  }
  @override
  public boolean accept(file dir, string name) {
  return regexmatch(name,regex);
  }});
 if(null != filelist && filelist.length>0)
 {
  for(file filteredfile: filelist)
  {
  filteredfile.delete();
  
  }
 }
 }
 /**
 * 复制文件/文件夹及其中的所有子文件夹和文件
 * @return
 */
 public static void copyfile(string srcfilepath,string destfilepath)
 {
 inputstream is = null;
 outputstream os = null;
 try {
  if(creatfile(destfilepath))
  {
  file srcfile = new file(srcfilepath);
  file destfile = new file(destfilepath);
   is = new fileinputstream(srcfile);
   os = new fileoutputstream(destfile);
  byte [] buffer = new byte[2048];
  int temp = 0;
  while((temp = is.read(buffer))!=-1)
  {
   os.write(buffer, 0, temp);
  }
  }
 } catch (exception e) {
  // todo auto-generated catch block
  e.printstacktrace();
 }
 finally
 {
  //java 7 以后可以不关闭,可以自动关闭
  if(null != os)
  {
  try {
   os.close();
  } catch (ioexception e) {
   // todo auto-generated catch block
   e.printstacktrace();
  }
  }
  if(null != is)
  {
  try {
   is.close();
  } catch (ioexception e) {
   // todo auto-generated catch block
   e.printstacktrace();
  }
  }
 }
 }
 /**
 * 复制指定地文件
 * @return
 *//*
 public static boolean copynamedfile()
 {
 
 }
 *//**
 * 剪切文件/文件夹及其中的所有子文件夹和文件
 * @return
 */
 public static void cutfile(string srcfilepath,string destfilepath)
 {
 //先复制,再删除
 try {
  copyfile( srcfilepath, destfilepath);
  deletefile(srcfilepath);
 } catch (exception e) {
  // todo auto-generated catch block
  e.printstacktrace();
 }
 }
 /**
 * 剪切文件/文件夹及其中的所有子文件夹和文件
 * @return
 *//*
 public static boolean cutnamedfile()
 {
 
 }
 *//**
 * 文件压缩
 * @param destpath
 * @param fileformats
 * @param srcfile
 * @return
 *//*
 public static boolean filecompress(string destpath,string fileformats,string srcfile,string regex)
 {
 
 }
 *//**
 * 文件解压缩
 * @param destpath
 * @param srcfile
 * @return
 *//*
 public static boolean filedecompress(string destpath,string srcpath)
 {
 
 }
 *//**
 * 文件加密
 * @param srcpath
 * @param destpath
 * @param encryptkey
 * @param encryptalgorithm
 * @return
 *//*
 public static boolean fileencrypt(string srcpath,string destpath,string encryptkey,string encryptalgorithm)
 {
 
 }
 *//**
 * 文件解密
 * @param srcpath
 * @param destpath
 * @param encryptkey
 * @param encryptalgorithm
 * @return
 *//*
 public static boolean filedecrypt(string srcpath,string destpath,string encryptkey,string encryptalgorithm)
 {
 
 }*/
 
 public static void main(string [] args)
 {
 file file = new file("d:\\北邮人下载\\书籍\\编译原理");
 getbaseinfo(file);
 try {
  /*deletenamedfile("d:\\北邮人下载\\书籍",".pdf");*/
 } catch (exception e) {
  // todo auto-generated catch block
  e.printstacktrace();
 } 
 /*cutfile("f:\\抢票软件\\12306bypass.exe","f:\\抢票软件\\12306bypass\\12306bypass.exe");*/
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网