欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

值得分享的超全文件工具类FileUtil

程序员文章站 2023-11-09 14:43:40
结合以前的项目开发中遇到的不同的文件操作,在这里基本上提取出了所遇到过的文件操作的工具类。 1 我项目中用到的文件工具类 1 读取raw文件、file文件,drawab...

结合以前的项目开发中遇到的不同的文件操作,在这里基本上提取出了所遇到过的文件操作的工具类。

1 我项目中用到的文件工具类

1 读取raw文件、file文件,drawable文件,asset文件,比如本地的json数据,本地文本等;
如:string result =fileutil.getstring(context,”raw://first.json”)
2 读取本地的property文件,并转化为hashmap类型的数据 (simpleproperty2hashmap);
3 将raw文件拷贝到指定目录(copyrawfile);
4 基本文件读写操作(readfile,writefile);
5 从文件的完整路径名(路径+文件名)中提取 路径(extractfilepath);
6 从文件的完整路径名(路径+文件名)中提取文件名(包含扩展名)
如:d:\path\file.ext –> file.ext(extractfilename)
7 检查指定文件的路径是否存在(pathexists)
8 检查制定文件是否存在(fileexists)
9 创建目录(makedir)
10 移除字符串中的bom前缀(removebomheaderifexists)

package com.nsu.edu.library.utils;

import android.content.context;
import android.graphics.bitmap;
import android.graphics.drawable.bitmapdrawable;
import android.text.textutils;

import java.io.bufferedreader;
import java.io.bytearrayinputstream;
import java.io.bytearrayoutputstream;
import java.io.file;
import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.io.outputstream;
import java.util.hashmap;
import java.util.iterator;
import java.util.properties;
import java.util.set;

/**
 * create by anthony on 2016/1/15
 * class note:文件工具类
 * 包含内容:
 * 1 读取raw文件、file文件,drawable文件,asset文件,比如本地的json数据,本地文本等;
 * 如:string result =fileutil.getstring(context,"raw://first.json")
 * 2 读取本地的property文件,并转化为hashmap类型的数据(simpleproperty2hashmap);
 * 3 将raw文件拷贝到指定目录(copyrawfile);
 * 4 基本文件读写操作(readfile,writefile);
 * 5 从文件的完整路径名(路径+文件名)中提取 路径(extractfilepath);
 * 6 从文件的完整路径名(路径+文件名)中提取文件名(包含扩展名) 
 如:d:\path\file.ext --> file.ext(extractfilename)
 *7 检查指定文件的路径是否存在(pathexists)
 *8 检查制定文件是否存在(fileexists)
 *9 创建目录(makedir)
 *10 移除字符串中的bom前缀(removebomheaderifexists)
 */
public class fileutil {
 public static final string assets_prefix = "file://android_assets/";
 public static final string assets_prefix2 = "file://android_asset/";
 public static final string assets_prefix3 = "assets://";
 public static final string assets_prefix4 = "asset://";
 public static final string raw_prefix = "file://android_raw/";
 public static final string raw_prefix2 = "raw://";
 public static final string file_prefix = "file://";
 public static final string drawable_prefix = "drawable://";

 public static inputstream getstream(context context, string url) throws ioexception {
  string lowerurl = url.tolowercase();
  inputstream is;
  if (lowerurl.startswith(assets_prefix)) {
   string assetpath = url.substring(assets_prefix.length());
   is = getassetsstream(context, assetpath);
  } else if (lowerurl.startswith(assets_prefix2)) {
   string assetpath = url.substring(assets_prefix2.length());
   is = getassetsstream(context, assetpath);
  } else if (lowerurl.startswith(assets_prefix3)) {
   string assetpath = url.substring(assets_prefix3.length());
   is = getassetsstream(context, assetpath);
  } else if (lowerurl.startswith(assets_prefix4)) {
   string assetpath = url.substring(assets_prefix4.length());
   is = getassetsstream(context, assetpath);
  } else if (lowerurl.startswith(raw_prefix)) {
   string rawname = url.substring(raw_prefix.length());
   is = getrawstream(context, rawname);
  } else if (lowerurl.startswith(raw_prefix2)) {
   string rawname = url.substring(raw_prefix2.length());
   is = getrawstream(context, rawname);
  } else if (lowerurl.startswith(file_prefix)) {
   string filepath = url.substring(file_prefix.length());
   is = getfilestream(filepath);
  } else if (lowerurl.startswith(drawable_prefix)) {
   string drawablename = url.substring(drawable_prefix.length());
   is = getdrawablestream(context, drawablename);
  } else {
   throw new illegalargumentexception(string.format("unsupported url: %s \n" +
     "supported: \n%sxxx\n%sxxx\n%sxxx", url, assets_prefix, raw_prefix, file_prefix));
  }
  return is;
 }

 private static inputstream getassetsstream(context context, string path) throws ioexception {
  return context.getassets().open(path);
 }

 private static inputstream getfilestream(string path) throws ioexception {
  return new fileinputstream(path);
 }

 private static inputstream getrawstream(context context, string rawname) throws ioexception {
  int id = context.getresources().getidentifier(rawname, "raw", context.getpackagename());
  if (id != 0) {
   try {
    return context.getresources().openrawresource(id);
   } catch (exception e) {
    e.printstacktrace();
   }
  }

  throw new ioexception(string.format("raw of id: %s from %s not found", id, rawname));
 }

 private static inputstream getdrawablestream(context context, string rawname) throws ioexception {
  int id = context.getresources().getidentifier(rawname, "drawable", context.getpackagename());
  if (id != 0) {
   bitmapdrawable drawable = (bitmapdrawable) context.getresources().getdrawable(id);
   bitmap bitmap = drawable.getbitmap();

   bytearrayoutputstream os = new bytearrayoutputstream();
   bitmap.compress(bitmap.compressformat.png, 0, os);
   return new bytearrayinputstream(os.tobytearray());
  }

  throw new ioexception(string.format("bitmap of id: %s from %s not found", id, rawname));
 }

 public static string getstring(context context, string url) throws ioexception {
  return getstring(context, url, "utf-8");
 }

 public static string getstring(context context, string url, string encoding) throws ioexception {
  string result = readstreamstring(getstream(context, url), encoding);
  if (result.startswith("\ufeff")) {
   result = result.substring(1);
  }

  return result;
 }

 public static string readstreamstring(inputstream is, string encoding) throws ioexception {
  return new string(readstream(is), encoding);
 }

 public static byte[] readstream(inputstream is) throws ioexception {
  bytearrayoutputstream baos = new bytearrayoutputstream();
  byte[] buf = new byte[1024 * 10];
  int readlen;
  while ((readlen = is.read(buf)) >= 0) {
   baos.write(buf, 0, readlen);
  }
  baos.close();

  return baos.tobytearray();
 }

 public static bitmap getdrawablebitmap(context context, string rawname) {
  int id = context.getresources().getidentifier(rawname, "drawable", context.getpackagename());
  if (id != 0) {
   bitmapdrawable drawable = (bitmapdrawable) context.getresources().getdrawable(id);
   if (drawable != null) {
    return drawable.getbitmap();
   }
  }

  return null;
 }

 /**
  * 读取property文件
  */
 public static hashmap<string, string> simpleproperty2hashmap(context context, string path) {
  try {
   inputstream is = getstream(context, path);
   return simpleproperty2hashmap(is);
  } catch (ioexception e) {
   e.printstacktrace();
  }

  return new hashmap<string, string>();
 }

 private static hashmap<string, string> simpleproperty2hashmap(inputstream in) throws ioexception {
  hashmap<string, string> hashmap = new hashmap<string, string>();
  properties properties = new properties();
  properties.load(in);
  in.close();
  set keyvalue = properties.keyset();
  for (iterator it = keyvalue.iterator(); it.hasnext(); ) {
   string key = (string) it.next();
   hashmap.put(key, (string) properties.get(key));
  }

  return hashmap;
 }

 /**
  * 将raw文件拷贝到指定目录
  */
 public static void copyrawfile(context ctx, string rawfilename, string to) {
  string[] names = rawfilename.split("\\.");
  string tofile = to + "/" + names[0] + "." + names[1];
  file file = new file(tofile);
  if (file.exists()) {
   return;
  }
  try {
   inputstream is = getstream(ctx, "raw://" + names[0]);
   outputstream os = new fileoutputstream(tofile);
   int bytecount = 0;
   byte[] bytes = new byte[1024];

   while ((bytecount = is.read(bytes)) != -1) {
    os.write(bytes, 0, bytecount);
   }
   os.close();
   is.close();
  } catch (exception e) {
   e.printstacktrace();
  }
 }

 /**
  * 基本文件操作
  */
 public static string file_reading_encoding = "utf-8";
 public static string file_writing_encoding = "utf-8";

 public static string readfile(string _sfilename, string _sencoding) throws exception {
  stringbuffer buffcontent = null;
  string sline;

  fileinputstream fis = null;
  bufferedreader buffreader = null;
  if (_sencoding == null || "".equals(_sencoding)) {
   _sencoding = file_reading_encoding;
  }

  try {
   fis = new fileinputstream(_sfilename);
   buffreader = new bufferedreader(new inputstreamreader(fis,
     _sencoding));
   boolean zfirstline = "utf-8".equalsignorecase(_sencoding);
   while ((sline = buffreader.readline()) != null) {
    if (buffcontent == null) {
     buffcontent = new stringbuffer();
    } else {
     buffcontent.append("\n");
    }
    if (zfirstline) {
     sline = removebomheaderifexists(sline);
     zfirstline = false;
    }
    buffcontent.append(sline);
   }// end while
   return (buffcontent == null ? "" : buffcontent.tostring());
  } catch (filenotfoundexception ex) {
   throw new exception("要读取的文件没有找到!", ex);
  } catch (ioexception ex) {
   throw new exception("读取文件时错误!", ex);
  } finally {
   // 增加异常时资源的释放
   try {
    if (buffreader != null)
     buffreader.close();
    if (fis != null)
     fis.close();
   } catch (exception ex) {
    ex.printstacktrace();
   }
  }
 }

 public static file writefile(inputstream is, string path, boolean isoverride) throws exception {
  string spath = extractfilepath(path);
  if (!pathexists(spath)) {
   makedir(spath, true);
  }

  if (!isoverride && fileexists(path)) {
   if(path.contains(".")) {
    string suffix = path.substring(path.lastindexof("."));
    string pre = path.substring(0, path.lastindexof("."));
    path = pre + "_" + timeutils.getnowtime() + suffix;
   } else {
    path = path + "_" + timeutils.getnowtime();
   }
  }

  fileoutputstream os = null;
  file file = null;

  try {
   file = new file(path);
   os = new fileoutputstream(file);
   int bytecount = 0;
   byte[] bytes = new byte[1024];

   while ((bytecount = is.read(bytes)) != -1) {
    os.write(bytes, 0, bytecount);
   }
   os.flush();

   return file;
  } catch (exception e) {
   e.printstacktrace();
   throw new exception("写文件错误", e);
  } finally {
   try {
    if (os != null)
     os.close();
    if (is != null)
     is.close();
   } catch (exception e) {
    e.printstacktrace();
   }
  }
 }

 public static file writefile(string path, string content, string encoding, boolean isoverride) throws exception {
  if (textutils.isempty(encoding)) {
   encoding = file_writing_encoding;
  }
  inputstream is = new bytearrayinputstream(content.getbytes(encoding));
  return writefile(is, path, isoverride);
 }

 /**
  * 从文件的完整路径名(路径+文件名)中提取 路径(包括:drive+directroy )
  *
  * @param _sfilepathname
  * @return
  */
 public static string extractfilepath(string _sfilepathname) {
  int npos = _sfilepathname.lastindexof('/');
  if (npos < 0) {
   npos = _sfilepathname.lastindexof('\\');
  }

  return (npos >= 0 ? _sfilepathname.substring(0, npos + 1) : "");
 }

 /**
  * 从文件的完整路径名(路径+文件名)中提取文件名(包含扩展名) <br>
  * 如:d:\path\file.ext --> file.ext
  *
  * @param _sfilepathname
  * @return
  */
 public static string extractfilename(string _sfilepathname) {
  return extractfilename(_sfilepathname, file.separator);
 }

 /**
  * 从文件的完整路径名(路径+文件名)中提取文件名(包含扩展名) <br>
  * 如:d:\path\file.ext --> file.ext
  *
  * @param _sfilepathname 全文件路径名
  * @param _sfileseparator 文件分隔符
  * @return
  */
 public static string extractfilename(string _sfilepathname,
           string _sfileseparator) {
  int npos = -1;
  if (_sfileseparator == null) {
   npos = _sfilepathname.lastindexof(file.separatorchar);
   if (npos < 0) {
    npos = _sfilepathname
      .lastindexof(file.separatorchar == '/' ? '\\' : '/');
   }
  } else {
   npos = _sfilepathname.lastindexof(_sfileseparator);
  }

  if (npos < 0) {
   return _sfilepathname;
  }

  return _sfilepathname.substring(npos + 1);
 }

 /**
  * 检查指定文件的路径是否存在
  *
  * @param _spathfilename 文件名称(含路径)
  * @return 若存在,则返回true;否则,返回false
  */
 public static boolean pathexists(string _spathfilename) {
  string spath = extractfilepath(_spathfilename);
  return fileexists(spath);
 }

 public static boolean fileexists(string _spathfilename) {
  file file = new file(_spathfilename);
  return file.exists();
 }

 /**
  * 创建目录
  *
  * @param _sdir    目录名称
  * @param _bcreateparentdir 如果父目录不存在,是否创建父目录
  * @return
  */
 public static boolean makedir(string _sdir, boolean _bcreateparentdir) {
  boolean zresult = false;
  file file = new file(_sdir);
  if (_bcreateparentdir)
   zresult = file.mkdirs(); // 如果父目录不存在,则创建所有必需的父目录
  else
   zresult = file.mkdir(); // 如果父目录不存在,不做处理
  if (!zresult)
   zresult = file.exists();
  return zresult;
 }

 /**
  * 移除字符串中的bom前缀
  *
  * @param _sline 需要处理的字符串
  * @return 移除bom后的字符串.
  */
 private static string removebomheaderifexists(string _sline) {
  if (_sline == null) {
   return null;
  }
  string line = _sline;
  if (line.length() > 0) {
   char ch = line.charat(0);
   // 使用while是因为用一些工具看到过某些文件前几个字节都是0xfffe.
   // 0xfeff,0xfffe是字节序的不同处理.jvm中,一般是0xfeff
   while ((ch == 0xfeff || ch == 0xfffe)) {
    line = line.substring(1);
    if (line.length() == 0) {
     break;
    }
    ch = line.charat(0);
   }
  }
  return line;
 }

}

2 网上的工具类

这个工具类也大同小异。其中也有很多和我上面重复的一些方法,也有上面没有的方法。转自trinea的android-common项目。这里直接贴出来,不做任何更改。希望能对看到的人有帮助。也做一个笔记。

package com.nsu.edu.library.utils;

import android.text.textutils;

import java.io.bufferedreader;
import java.io.file;
import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.fileoutputstream;
import java.io.filewriter;
import java.io.ioexception;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.io.outputstream;
import java.util.arraylist;
import java.util.list;

/**
 * file utils
 * <ul>
 * read or write file
 * <li>{@link #readfile(string, string)} read file</li>
 * <li>{@link #readfiletolist(string, string)} read file to string list</li>
 * <li>{@link #writefile(string, string, boolean)} write file from string</li>
 * <li>{@link #writefile(string, string)} write file from string</li>
 * <li>{@link #writefile(string, list, boolean)} write file from string list</li>
 * <li>{@link #writefile(string, list)} write file from string list</li>
 * <li>{@link #writefile(string, inputstream)} write file</li>
 * <li>{@link #writefile(string, inputstream, boolean)} write file</li>
 * <li>{@link #writefile(file, inputstream)} write file</li>
 * <li>{@link #writefile(file, inputstream, boolean)} write file</li>
 * </ul>
 * <ul>
 * operate file
 * <li>{@link #movefile(file, file)} or {@link #movefile(string, string)}</li>
 * <li>{@link #copyfile(string, string)}</li>
 * <li>{@link #getfileextension(string)}</li>
 * <li>{@link #getfilename(string)}</li>
 * <li>{@link #getfilenamewithoutextension(string)}</li>
 * <li>{@link #getfilesize(string)}</li>
 * <li>{@link #deletefile(string)}</li>
 * <li>{@link #isfileexist(string)}</li>
 * <li>{@link #isfolderexist(string)}</li>
 * <li>{@link #makefolders(string)}</li>
 * <li>{@link #makedirs(string)}</li>
 * </ul>
 * 
 * @author <a href="http://www.trinea.cn" rel="external nofollow" target="_blank">trinea</a> 2012-5-12
 */
public class fileutils {

 public final static string file_extension_separator = ".";

 private fileutils() {
  throw new assertionerror();
 }

 /**
  * read file
  * 
  * @param filepath
  * @param charsetname the name of a supported {@link java.nio.charset.charset </code>charset<code>}
  * @return if file not exist, return null, else return content of file
  * @throws runtimeexception if an error occurs while operator bufferedreader
  */
 public static stringbuilder readfile(string filepath, string charsetname) {
  file file = new file(filepath);
  stringbuilder filecontent = new stringbuilder("");
  if (file == null || !file.isfile()) {
   return null;
  }

  bufferedreader reader = null;
  try {
   inputstreamreader is = new inputstreamreader(new fileinputstream(file), charsetname);
   reader = new bufferedreader(is);
   string line = null;
   while ((line = reader.readline()) != null) {
    if (!filecontent.tostring().equals("")) {
     filecontent.append("\r\n");
    }
    filecontent.append(line);
   }
   return filecontent;
  } catch (ioexception e) {
   throw new runtimeexception("ioexception occurred. ", e);
  } finally {
   ioutils.close(reader);
  }
 }

 /**
  * write file
  * 
  * @param filepath
  * @param content
  * @param append is append, if true, write to the end of file, else clear content of file and write into it
  * @return return false if content is empty, true otherwise
  * @throws runtimeexception if an error occurs while operator filewriter
  */
 public static boolean writefile(string filepath, string content, boolean append) {
  if (stringutils.isempty(content)) {
   return false;
  }

  filewriter filewriter = null;
  try {
   makedirs(filepath);
   filewriter = new filewriter(filepath, append);
   filewriter.write(content);
   return true;
  } catch (ioexception e) {
   throw new runtimeexception("ioexception occurred. ", e);
  } finally {
   ioutils.close(filewriter);
  }
 }

 /**
  * write file
  * 
  * @param filepath
  * @param contentlist
  * @param append is append, if true, write to the end of file, else clear content of file and write into it
  * @return return false if contentlist is empty, true otherwise
  * @throws runtimeexception if an error occurs while operator filewriter
  */
 public static boolean writefile(string filepath, list<string> contentlist, boolean append) {
  if (listutils.isempty(contentlist)) {
   return false;
  }

  filewriter filewriter = null;
  try {
   makedirs(filepath);
   filewriter = new filewriter(filepath, append);
   int i = 0;
   for (string line : contentlist) {
    if (i++ > 0) {
     filewriter.write("\r\n");
    }
    filewriter.write(line);
   }
   return true;
  } catch (ioexception e) {
   throw new runtimeexception("ioexception occurred. ", e);
  } finally {
   ioutils.close(filewriter);
  }
 }

 /**
  * write file, the string will be written to the begin of the file
  * 
  * @param filepath
  * @param content
  * @return
  */
 public static boolean writefile(string filepath, string content) {
  return writefile(filepath, content, false);
 }

 /**
  * write file, the string list will be written to the begin of the file
  * 
  * @param filepath
  * @param contentlist
  * @return
  */
 public static boolean writefile(string filepath, list<string> contentlist) {
  return writefile(filepath, contentlist, false);
 }

 /**
  * write file, the bytes will be written to the begin of the file
  * 
  * @param filepath
  * @param stream
  * @return
  * @see {@link #writefile(string, inputstream, boolean)}
  */
 public static boolean writefile(string filepath, inputstream stream) {
  return writefile(filepath, stream, false);
 }

 /**
  * write file
  * 
  * @param file the file to be opened for writing.
  * @param stream the input stream
  * @param append if <code>true</code>, then bytes will be written to the end of the file rather than the beginning
  * @return return true
  * @throws runtimeexception if an error occurs while operator fileoutputstream
  */
 public static boolean writefile(string filepath, inputstream stream, boolean append) {
  return writefile(filepath != null ? new file(filepath) : null, stream, append);
 }

 /**
  * write file, the bytes will be written to the begin of the file
  * 
  * @param file
  * @param stream
  * @return
  * @see {@link #writefile(file, inputstream, boolean)}
  */
 public static boolean writefile(file file, inputstream stream) {
  return writefile(file, stream, false);
 }

 /**
  * write file
  * 
  * @param file the file to be opened for writing.
  * @param stream the input stream
  * @param append if <code>true</code>, then bytes will be written to the end of the file rather than the beginning
  * @return return true
  * @throws runtimeexception if an error occurs while operator fileoutputstream
  */
 public static boolean writefile(file file, inputstream stream, boolean append) {
  outputstream o = null;
  try {
   makedirs(file.getabsolutepath());
   o = new fileoutputstream(file, append);
   byte data[] = new byte[1024];
   int length = -1;
   while ((length = stream.read(data)) != -1) {
    o.write(data, 0, length);
   }
   o.flush();
   return true;
  } catch (filenotfoundexception e) {
   throw new runtimeexception("filenotfoundexception occurred. ", e);
  } catch (ioexception e) {
   throw new runtimeexception("ioexception occurred. ", e);
  } finally {
   ioutils.close(o);
   ioutils.close(stream);
  }
 }

 /**
  * move file
  * 
  * @param sourcefilepath
  * @param destfilepath
  */
 public static void movefile(string sourcefilepath, string destfilepath) {
  if (textutils.isempty(sourcefilepath) || textutils.isempty(destfilepath)) {
   throw new runtimeexception("both sourcefilepath and destfilepath cannot be null.");
  }
  movefile(new file(sourcefilepath), new file(destfilepath));
 }

 /**
  * move file
  * 
  * @param srcfile
  * @param destfile
  */
 public static void movefile(file srcfile, file destfile) {
  boolean rename = srcfile.renameto(destfile);
  if (!rename) {
   copyfile(srcfile.getabsolutepath(), destfile.getabsolutepath());
   deletefile(srcfile.getabsolutepath());
  }
 }

 /**
  * copy file
  * 
  * @param sourcefilepath
  * @param destfilepath
  * @return
  * @throws runtimeexception if an error occurs while operator fileoutputstream
  */
 public static boolean copyfile(string sourcefilepath, string destfilepath) {
  inputstream inputstream = null;
  try {
   inputstream = new fileinputstream(sourcefilepath);
  } catch (filenotfoundexception e) {
   throw new runtimeexception("filenotfoundexception occurred. ", e);
  }
  return writefile(destfilepath, inputstream);
 }

 /**
  * read file to string list, a element of list is a line
  * 
  * @param filepath
  * @param charsetname the name of a supported {@link java.nio.charset.charset </code>charset<code>}
  * @return if file not exist, return null, else return content of file
  * @throws runtimeexception if an error occurs while operator bufferedreader
  */
 public static list<string> readfiletolist(string filepath, string charsetname) {
  file file = new file(filepath);
  list<string> filecontent = new arraylist<string>();
  if (file == null || !file.isfile()) {
   return null;
  }

  bufferedreader reader = null;
  try {
   inputstreamreader is = new inputstreamreader(new fileinputstream(file), charsetname);
   reader = new bufferedreader(is);
   string line = null;
   while ((line = reader.readline()) != null) {
    filecontent.add(line);
   }
   return filecontent;
  } catch (ioexception e) {
   throw new runtimeexception("ioexception occurred. ", e);
  } finally {
   ioutils.close(reader);
  }
 }

 /**
  * get file name from path, not include suffix
  * 
  * <pre>
  *  getfilenamewithoutextension(null)    = null
  *  getfilenamewithoutextension("")     = ""
  *  getfilenamewithoutextension(" ")    = " "
  *  getfilenamewithoutextension("abc")    = "abc"
  *  getfilenamewithoutextension("a.mp3")   = "a"
  *  getfilenamewithoutextension("a.b.rmvb")   = "a.b"
  *  getfilenamewithoutextension("c:\\")    = ""
  *  getfilenamewithoutextension("c:\\a")    = "a"
  *  getfilenamewithoutextension("c:\\a.b")   = "a"
  *  getfilenamewithoutextension("c:a.txt\\a")  = "a"
  *  getfilenamewithoutextension("/home/admin")  = "admin"
  *  getfilenamewithoutextension("/home/admin/a.txt/b.mp3") = "b"
  * </pre>
  * 
  * @param filepath
  * @return file name from path, not include suffix
  * @see
  */
 public static string getfilenamewithoutextension(string filepath) {
  if (stringutils.isempty(filepath)) {
   return filepath;
  }

  int extenposi = filepath.lastindexof(file_extension_separator);
  int fileposi = filepath.lastindexof(file.separator);
  if (fileposi == -1) {
   return (extenposi == -1 ? filepath : filepath.substring(0, extenposi));
  }
  if (extenposi == -1) {
   return filepath.substring(fileposi + 1);
  }
  return (fileposi < extenposi ? filepath.substring(fileposi + 1, extenposi) : filepath.substring(fileposi + 1));
 }

 /**
  * get file name from path, include suffix
  * 
  * <pre>
  *  getfilename(null)    = null
  *  getfilename("")     = ""
  *  getfilename(" ")    = " "
  *  getfilename("a.mp3")   = "a.mp3"
  *  getfilename("a.b.rmvb")   = "a.b.rmvb"
  *  getfilename("abc")    = "abc"
  *  getfilename("c:\\")    = ""
  *  getfilename("c:\\a")    = "a"
  *  getfilename("c:\\a.b")   = "a.b"
  *  getfilename("c:a.txt\\a")  = "a"
  *  getfilename("/home/admin")  = "admin"
  *  getfilename("/home/admin/a.txt/b.mp3") = "b.mp3"
  * </pre>
  * 
  * @param filepath
  * @return file name from path, include suffix
  */
 public static string getfilename(string filepath) {
  if (stringutils.isempty(filepath)) {
   return filepath;
  }

  int fileposi = filepath.lastindexof(file.separator);
  return (fileposi == -1) ? filepath : filepath.substring(fileposi + 1);
 }

 /**
  * get folder name from path
  * 
  * <pre>
  *  getfoldername(null)    = null
  *  getfoldername("")     = ""
  *  getfoldername(" ")    = ""
  *  getfoldername("a.mp3")   = ""
  *  getfoldername("a.b.rmvb")   = ""
  *  getfoldername("abc")    = ""
  *  getfoldername("c:\\")    = "c:"
  *  getfoldername("c:\\a")    = "c:"
  *  getfoldername("c:\\a.b")   = "c:"
  *  getfoldername("c:a.txt\\a")  = "c:a.txt"
  *  getfoldername("c:a\\b\\c\\d.txt") = "c:a\\b\\c"
  *  getfoldername("/home/admin")  = "/home"
  *  getfoldername("/home/admin/a.txt/b.mp3") = "/home/admin/a.txt"
  * </pre>
  * 
  * @param filepath
  * @return
  */
 public static string getfoldername(string filepath) {

  if (stringutils.isempty(filepath)) {
   return filepath;
  }

  int fileposi = filepath.lastindexof(file.separator);
  return (fileposi == -1) ? "" : filepath.substring(0, fileposi);
 }

 /**
  * get suffix of file from path
  * 
  * <pre>
  *  getfileextension(null)    = ""
  *  getfileextension("")     = ""
  *  getfileextension(" ")    = " "
  *  getfileextension("a.mp3")   = "mp3"
  *  getfileextension("a.b.rmvb")   = "rmvb"
  *  getfileextension("abc")    = ""
  *  getfileextension("c:\\")    = ""
  *  getfileextension("c:\\a")    = ""
  *  getfileextension("c:\\a.b")   = "b"
  *  getfileextension("c:a.txt\\a")  = ""
  *  getfileextension("/home/admin")  = ""
  *  getfileextension("/home/admin/a.txt/b") = ""
  *  getfileextension("/home/admin/a.txt/b.mp3") = "mp3"
  * </pre>
  * 
  * @param filepath
  * @return
  */
 public static string getfileextension(string filepath) {
  if (stringutils.isblank(filepath)) {
   return filepath;
  }

  int extenposi = filepath.lastindexof(file_extension_separator);
  int fileposi = filepath.lastindexof(file.separator);
  if (extenposi == -1) {
   return "";
  }
  return (fileposi >= extenposi) ? "" : filepath.substring(extenposi + 1);
 }

 /**
  * creates the directory named by the trailing filename of this file, including the complete directory path required
  * to create this directory. <br/>
  * <br/>
  * <ul>
  * <strong>attentions:</strong>
  * <li>makedirs("c:\\users\\trinea") can only create users folder</li>
  * <li>makefolder("c:\\users\\trinea\\") can create trinea folder</li>
  * </ul>
  * 
  * @param filepath
  * @return true if the necessary directories have been created or the target directory already exists, false one of
  *   the directories can not be created.
  *   <ul>
  *   <li>if {@link fileutils#getfoldername(string)} return null, return false</li>
  *   <li>if target directory already exists, return true</li>
  *   <li>return {@link file#makefolder}</li>
  *   </ul>
  */
 public static boolean makedirs(string filepath) {
  string foldername = getfoldername(filepath);
  if (stringutils.isempty(foldername)) {
   return false;
  }

  file folder = new file(foldername);
  return (folder.exists() && folder.isdirectory()) ? true : folder.mkdirs();
 }

 /**
  * @param filepath
  * @return
  * @see #makedirs(string)
  */
 public static boolean makefolders(string filepath) {
  return makedirs(filepath);
 }

 /**
  * indicates if this file represents a file on the underlying file system.
  * 
  * @param filepath
  * @return
  */
 public static boolean isfileexist(string filepath) {
  if (stringutils.isblank(filepath)) {
   return false;
  }

  file file = new file(filepath);
  return (file.exists() && file.isfile());
 }

 /**
  * indicates if this file represents a directory on the underlying file system.
  * 
  * @param directorypath
  * @return
  */
 public static boolean isfolderexist(string directorypath) {
  if (stringutils.isblank(directorypath)) {
   return false;
  }

  file dire = new file(directorypath);
  return (dire.exists() && dire.isdirectory());
 }

 /**
  * delete file or directory
  * <ul>
  * <li>if path is null or empty, return true</li>
  * <li>if path not exist, return true</li>
  * <li>if path exist, delete recursion. return true</li>
  * <ul>
  * 
  * @param path
  * @return
  */
 public static boolean deletefile(string path) {
  if (stringutils.isblank(path)) {
   return true;
  }

  file file = new file(path);
  if (!file.exists()) {
   return true;
  }
  if (file.isfile()) {
   return file.delete();
  }
  if (!file.isdirectory()) {
   return false;
  }
  for (file f : file.listfiles()) {
   if (f.isfile()) {
    f.delete();
   } else if (f.isdirectory()) {
    deletefile(f.getabsolutepath());
   }
  }
  return file.delete();
 }

 /**
  * get file size
  * <ul>
  * <li>if path is null or empty, return -1</li>
  * <li>if path exist and it is a file, return file size, else return -1</li>
  * <ul>
  * 
  * @param path
  * @return returns the length of this file in bytes. returns -1 if the file does not exist.
  */
 public static long getfilesize(string path) {
  if (stringutils.isblank(path)) {
   return -1;
  }

  file file = new file(path);
  return (file.exists() && file.isfile() ? file.length() : -1);
 }
}

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