值得分享的超全文件工具类FileUtil
结合以前的项目开发中遇到的不同的文件操作,在这里基本上提取出了所遇到过的文件操作的工具类。
1我项目中用到的文件工具类
1读取raw文件、file文件,drawable文件,asset文件,比如本地的json数据,本地文本等;
如:Stringresult=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)
packagecom.nsu.edu.library.utils; importandroid.content.Context; importandroid.graphics.Bitmap; importandroid.graphics.drawable.BitmapDrawable; importandroid.text.TextUtils; importjava.io.BufferedReader; importjava.io.ByteArrayInputStream; importjava.io.ByteArrayOutputStream; importjava.io.File; importjava.io.FileInputStream; importjava.io.FileNotFoundException; importjava.io.FileOutputStream; importjava.io.IOException; importjava.io.InputStream; importjava.io.InputStreamReader; importjava.io.OutputStream; importjava.util.HashMap; importjava.util.Iterator; importjava.util.Properties; importjava.util.Set; /** *CreateByAnthonyon2016/1/15 *ClassNote:文件工具类 *包含内容: *1读取raw文件、file文件,drawable文件,asset文件,比如本地的json数据,本地文本等; *如:Stringresult=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) */ publicclassFileUtil{ publicstaticfinalStringASSETS_PREFIX="file://android_assets/"; publicstaticfinalStringASSETS_PREFIX2="file://android_asset/"; publicstaticfinalStringASSETS_PREFIX3="assets://"; publicstaticfinalStringASSETS_PREFIX4="asset://"; publicstaticfinalStringRAW_PREFIX="file://android_raw/"; publicstaticfinalStringRAW_PREFIX2="raw://"; publicstaticfinalStringFILE_PREFIX="file://"; publicstaticfinalStringDRAWABLE_PREFIX="drawable://"; publicstaticInputStreamgetStream(Contextcontext,Stringurl)throwsIOException{ StringlowerUrl=url.toLowerCase(); InputStreamis; if(lowerUrl.startsWith(ASSETS_PREFIX)){ StringassetPath=url.substring(ASSETS_PREFIX.length()); is=getAssetsStream(context,assetPath); }elseif(lowerUrl.startsWith(ASSETS_PREFIX2)){ StringassetPath=url.substring(ASSETS_PREFIX2.length()); is=getAssetsStream(context,assetPath); }elseif(lowerUrl.startsWith(ASSETS_PREFIX3)){ StringassetPath=url.substring(ASSETS_PREFIX3.length()); is=getAssetsStream(context,assetPath); }elseif(lowerUrl.startsWith(ASSETS_PREFIX4)){ StringassetPath=url.substring(ASSETS_PREFIX4.length()); is=getAssetsStream(context,assetPath); }elseif(lowerUrl.startsWith(RAW_PREFIX)){ StringrawName=url.substring(RAW_PREFIX.length()); is=getRawStream(context,rawName); }elseif(lowerUrl.startsWith(RAW_PREFIX2)){ StringrawName=url.substring(RAW_PREFIX2.length()); is=getRawStream(context,rawName); }elseif(lowerUrl.startsWith(FILE_PREFIX)){ StringfilePath=url.substring(FILE_PREFIX.length()); is=getFileStream(filePath); }elseif(lowerUrl.startsWith(DRAWABLE_PREFIX)){ StringdrawableName=url.substring(DRAWABLE_PREFIX.length()); is=getDrawableStream(context,drawableName); }else{ thrownewIllegalArgumentException(String.format("Unsupportedurl:%s\n"+ "Supported:\n%sxxx\n%sxxx\n%sxxx",url,ASSETS_PREFIX,RAW_PREFIX,FILE_PREFIX)); } returnis; } privatestaticInputStreamgetAssetsStream(Contextcontext,Stringpath)throwsIOException{ returncontext.getAssets().open(path); } privatestaticInputStreamgetFileStream(Stringpath)throwsIOException{ returnnewFileInputStream(path); } privatestaticInputStreamgetRawStream(Contextcontext,StringrawName)throwsIOException{ intid=context.getResources().getIdentifier(rawName,"raw",context.getPackageName()); if(id!=0){ try{ returncontext.getResources().openRawResource(id); }catch(Exceptione){ e.printStackTrace(); } } thrownewIOException(String.format("rawofid:%sfrom%snotfound",id,rawName)); } privatestaticInputStreamgetDrawableStream(Contextcontext,StringrawName)throwsIOException{ intid=context.getResources().getIdentifier(rawName,"drawable",context.getPackageName()); if(id!=0){ BitmapDrawabledrawable=(BitmapDrawable)context.getResources().getDrawable(id); Bitmapbitmap=drawable.getBitmap(); ByteArrayOutputStreamos=newByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG,0,os); returnnewByteArrayInputStream(os.toByteArray()); } thrownewIOException(String.format("bitmapofid:%sfrom%snotfound",id,rawName)); } publicstaticStringgetString(Contextcontext,Stringurl)throwsIOException{ returngetString(context,url,"UTF-8"); } publicstaticStringgetString(Contextcontext,Stringurl,Stringencoding)throwsIOException{ Stringresult=readStreamString(getStream(context,url),encoding); if(result.startsWith("\ufeff")){ result=result.substring(1); } returnresult; } publicstaticStringreadStreamString(InputStreamis,Stringencoding)throwsIOException{ returnnewString(readStream(is),encoding); } publicstaticbyte[]readStream(InputStreamis)throwsIOException{ ByteArrayOutputStreambaos=newByteArrayOutputStream(); byte[]buf=newbyte[1024*10]; intreadlen; while((readlen=is.read(buf))>=0){ baos.write(buf,0,readlen); } baos.close(); returnbaos.toByteArray(); } publicstaticBitmapgetDrawableBitmap(Contextcontext,StringrawName){ intid=context.getResources().getIdentifier(rawName,"drawable",context.getPackageName()); if(id!=0){ BitmapDrawabledrawable=(BitmapDrawable)context.getResources().getDrawable(id); if(drawable!=null){ returndrawable.getBitmap(); } } returnnull; } /** *读取Property文件 */ publicstaticHashMapsimpleProperty2HashMap(Contextcontext,Stringpath){ try{ InputStreamis=getStream(context,path); returnsimpleProperty2HashMap(is); }catch(IOExceptione){ e.printStackTrace(); } returnnewHashMap (); } privatestaticHashMap simpleProperty2HashMap(InputStreamin)throwsIOException{ HashMap hashMap=newHashMap (); Propertiesproperties=newProperties(); properties.load(in); in.close(); SetkeyValue=properties.keySet(); for(Iteratorit=keyValue.iterator();it.hasNext();){ Stringkey=(String)it.next(); hashMap.put(key,(String)properties.get(key)); } returnhashMap; } /** *将raw文件拷贝到指定目录 */ publicstaticvoidcopyRawFile(Contextctx,StringrawFileName,Stringto){ String[]names=rawFileName.split("\\."); StringtoFile=to+"/"+names[0]+"."+names[1]; Filefile=newFile(toFile); if(file.exists()){ return; } try{ InputStreamis=getStream(ctx,"raw://"+names[0]); OutputStreamos=newFileOutputStream(toFile); intbyteCount=0; byte[]bytes=newbyte[1024]; while((byteCount=is.read(bytes))!=-1){ os.write(bytes,0,byteCount); } os.close(); is.close(); }catch(Exceptione){ e.printStackTrace(); } } /** *基本文件操作 */ publicstaticStringFILE_READING_ENCODING="UTF-8"; publicstaticStringFILE_WRITING_ENCODING="UTF-8"; publicstaticStringreadFile(String_sFileName,String_sEncoding)throwsException{ StringBufferbuffContent=null; StringsLine; FileInputStreamfis=null; BufferedReaderbuffReader=null; if(_sEncoding==null||"".equals(_sEncoding)){ _sEncoding=FILE_READING_ENCODING; } try{ fis=newFileInputStream(_sFileName); buffReader=newBufferedReader(newInputStreamReader(fis, _sEncoding)); booleanzFirstLine="UTF-8".equalsIgnoreCase(_sEncoding); while((sLine=buffReader.readLine())!=null){ if(buffContent==null){ buffContent=newStringBuffer(); }else{ buffContent.append("\n"); } if(zFirstLine){ sLine=removeBomHeaderIfExists(sLine); zFirstLine=false; } buffContent.append(sLine); }//endwhile return(buffContent==null?"":buffContent.toString()); }catch(FileNotFoundExceptionex){ thrownewException("要读取的文件没有找到!",ex); }catch(IOExceptionex){ thrownewException("读取文件时错误!",ex); }finally{ //增加异常时资源的释放 try{ if(buffReader!=null) buffReader.close(); if(fis!=null) fis.close(); }catch(Exceptionex){ ex.printStackTrace(); } } } publicstaticFilewriteFile(InputStreamis,Stringpath,booleanisOverride)throwsException{ StringsPath=extractFilePath(path); if(!pathExists(sPath)){ makeDir(sPath,true); } if(!isOverride&&fileExists(path)){ if(path.contains(".")){ Stringsuffix=path.substring(path.lastIndexOf(".")); Stringpre=path.substring(0,path.lastIndexOf(".")); path=pre+"_"+TimeUtils.getNowTime()+suffix; }else{ path=path+"_"+TimeUtils.getNowTime(); } } FileOutputStreamos=null; Filefile=null; try{ file=newFile(path); os=newFileOutputStream(file); intbyteCount=0; byte[]bytes=newbyte[1024]; while((byteCount=is.read(bytes))!=-1){ os.write(bytes,0,byteCount); } os.flush(); returnfile; }catch(Exceptione){ e.printStackTrace(); thrownewException("写文件错误",e); }finally{ try{ if(os!=null) os.close(); if(is!=null) is.close(); }catch(Exceptione){ e.printStackTrace(); } } } publicstaticFilewriteFile(Stringpath,Stringcontent,Stringencoding,booleanisOverride)throwsException{ if(TextUtils.isEmpty(encoding)){ encoding=FILE_WRITING_ENCODING; } InputStreamis=newByteArrayInputStream(content.getBytes(encoding)); returnwriteFile(is,path,isOverride); } /** *从文件的完整路径名(路径+文件名)中提取路径(包括:Drive+Directroy) * *@param_sFilePathName *@return */ publicstaticStringextractFilePath(String_sFilePathName){ intnPos=_sFilePathName.lastIndexOf('/'); if(nPos<0){ nPos=_sFilePathName.lastIndexOf('\\'); } return(nPos>=0?_sFilePathName.substring(0,nPos+1):""); } /** *从文件的完整路径名(路径+文件名)中提取文件名(包含扩展名)
*如:d:\path\file.ext-->file.ext * *@param_sFilePathName *@return */ publicstaticStringextractFileName(String_sFilePathName){ returnextractFileName(_sFilePathName,File.separator); } /** *从文件的完整路径名(路径+文件名)中提取文件名(包含扩展名)
*如:d:\path\file.ext-->file.ext * *@param_sFilePathName全文件路径名 *@param_sFileSeparator文件分隔符 *@return */ publicstaticStringextractFileName(String_sFilePathName, String_sFileSeparator){ intnPos=-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 */ publicstaticbooleanpathExists(String_sPathFileName){ StringsPath=extractFilePath(_sPathFileName); returnfileExists(sPath); } publicstaticbooleanfileExists(String_sPathFileName){ Filefile=newFile(_sPathFileName); returnfile.exists(); } /** *创建目录 * *@param_sDir目录名称 *@param_bCreateParentDir如果父目录不存在,是否创建父目录 *@return */ publicstaticbooleanmakeDir(String_sDir,boolean_bCreateParentDir){ booleanzResult=false; Filefile=newFile(_sDir); if(_bCreateParentDir) zResult=file.mkdirs();//如果父目录不存在,则创建所有必需的父目录 else zResult=file.mkdir();//如果父目录不存在,不做处理 if(!zResult) zResult=file.exists(); returnzResult; } /** *移除字符串中的BOM前缀 * *@param_sLine需要处理的字符串 *@return移除BOM后的字符串. */ privatestaticStringremoveBomHeaderIfExists(String_sLine){ if(_sLine==null){ returnnull; } Stringline=_sLine; if(line.length()>0){ charch=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); } } returnline; } }
2网上的工具类
这个工具类也大同小异。其中也有很多和我上面重复的一些方法,也有上面没有的方法。转自Trinea的android-common项目。这里直接贴出来,不做任何更改。希望能对看到的人有帮助。也做一个笔记。
packagecom.nsu.edu.library.utils; importandroid.text.TextUtils; importjava.io.BufferedReader; importjava.io.File; importjava.io.FileInputStream; importjava.io.FileNotFoundException; importjava.io.FileOutputStream; importjava.io.FileWriter; importjava.io.IOException; importjava.io.InputStream; importjava.io.InputStreamReader; importjava.io.OutputStream; importjava.util.ArrayList; importjava.util.List; /** *FileUtils *
-
*Readorwritefile
*
- {@link#readFile(String,String)}readfile *
- {@link#readFileToList(String,String)}readfiletostringlist *
- {@link#writeFile(String,String,boolean)}writefilefromString *
- {@link#writeFile(String,String)}writefilefromString *
- {@link#writeFile(String,List,boolean)}writefilefromStringList *
- {@link#writeFile(String,List)}writefilefromStringList *
- {@link#writeFile(String,InputStream)}writefile *
- {@link#writeFile(String,InputStream,boolean)}writefile *
- {@link#writeFile(File,InputStream)}writefile *
- {@link#writeFile(File,InputStream,boolean)}writefile *
-
*Operatefile
*
- {@link#moveFile(File,File)}or{@link#moveFile(String,String)} *
- {@link#copyFile(String,String)} *
- {@link#getFileExtension(String)} *
- {@link#getFileName(String)} *
- {@link#getFileNameWithoutExtension(String)} *
- {@link#getFileSize(String)} *
- {@link#deleteFile(String)} *
- {@link#isFileExist(String)} *
- {@link#isFolderExist(String)} *
- {@link#makeFolders(String)} *
- {@link#makeDirs(String)} *
}
*@returniffilenotexist,returnnull,elsereturncontentoffile
*@throwsRuntimeExceptionifanerroroccurswhileoperatorBufferedReader
*/
publicstaticStringBuilderreadFile(StringfilePath,StringcharsetName){
Filefile=newFile(filePath);
StringBuilderfileContent=newStringBuilder("");
if(file==null||!file.isFile()){
returnnull;
}
BufferedReaderreader=null;
try{
InputStreamReaderis=newInputStreamReader(newFileInputStream(file),charsetName);
reader=newBufferedReader(is);
Stringline=null;
while((line=reader.readLine())!=null){
if(!fileContent.toString().equals("")){
fileContent.append("\r\n");
}
fileContent.append(line);
}
returnfileContent;
}catch(IOExceptione){
thrownewRuntimeException("IOExceptionoccurred.",e);
}finally{
IOUtils.close(reader);
}
}
/**
*writefile
*
*@paramfilePath
*@paramcontent
*@paramappendisappend,iftrue,writetotheendoffile,elseclearcontentoffileandwriteintoit
*@returnreturnfalseifcontentisempty,trueotherwise
*@throwsRuntimeExceptionifanerroroccurswhileoperatorFileWriter
*/
publicstaticbooleanwriteFile(StringfilePath,Stringcontent,booleanappend){
if(StringUtils.isEmpty(content)){
returnfalse;
}
FileWriterfileWriter=null;
try{
makeDirs(filePath);
fileWriter=newFileWriter(filePath,append);
fileWriter.write(content);
returntrue;
}catch(IOExceptione){
thrownewRuntimeException("IOExceptionoccurred.",e);
}finally{
IOUtils.close(fileWriter);
}
}
/**
*writefile
*
*@paramfilePath
*@paramcontentList
*@paramappendisappend,iftrue,writetotheendoffile,elseclearcontentoffileandwriteintoit
*@returnreturnfalseifcontentListisempty,trueotherwise
*@throwsRuntimeExceptionifanerroroccurswhileoperatorFileWriter
*/
publicstaticbooleanwriteFile(StringfilePath,ListcontentList,booleanappend){
if(ListUtils.isEmpty(contentList)){
returnfalse;
}
FileWriterfileWriter=null;
try{
makeDirs(filePath);
fileWriter=newFileWriter(filePath,append);
inti=0;
for(Stringline:contentList){
if(i++>0){
fileWriter.write("\r\n");
}
fileWriter.write(line);
}
returntrue;
}catch(IOExceptione){
thrownewRuntimeException("IOExceptionoccurred.",e);
}finally{
IOUtils.close(fileWriter);
}
}
/**
*writefile,thestringwillbewrittentothebeginofthefile
*
*@paramfilePath
*@paramcontent
*@return
*/
publicstaticbooleanwriteFile(StringfilePath,Stringcontent){
returnwriteFile(filePath,content,false);
}
/**
*writefile,thestringlistwillbewrittentothebeginofthefile
*
*@paramfilePath
*@paramcontentList
*@return
*/
publicstaticbooleanwriteFile(StringfilePath,ListcontentList){
returnwriteFile(filePath,contentList,false);
}
/**
*writefile,thebyteswillbewrittentothebeginofthefile
*
*@paramfilePath
*@paramstream
*@return
*@see{@link#writeFile(String,InputStream,boolean)}
*/
publicstaticbooleanwriteFile(StringfilePath,InputStreamstream){
returnwriteFile(filePath,stream,false);
}
/**
*writefile
*
*@paramfilethefiletobeopenedforwriting.
*@paramstreamtheinputstream
*@paramappendiftrue
,thenbyteswillbewrittentotheendofthefileratherthanthebeginning
*@returnreturntrue
*@throwsRuntimeExceptionifanerroroccurswhileoperatorFileOutputStream
*/
publicstaticbooleanwriteFile(StringfilePath,InputStreamstream,booleanappend){
returnwriteFile(filePath!=null?newFile(filePath):null,stream,append);
}
/**
*writefile,thebyteswillbewrittentothebeginofthefile
*
*@paramfile
*@paramstream
*@return
*@see{@link#writeFile(File,InputStream,boolean)}
*/
publicstaticbooleanwriteFile(Filefile,InputStreamstream){
returnwriteFile(file,stream,false);
}
/**
*writefile
*
*@paramfilethefiletobeopenedforwriting.
*@paramstreamtheinputstream
*@paramappendiftrue
,thenbyteswillbewrittentotheendofthefileratherthanthebeginning
*@returnreturntrue
*@throwsRuntimeExceptionifanerroroccurswhileoperatorFileOutputStream
*/
publicstaticbooleanwriteFile(Filefile,InputStreamstream,booleanappend){
OutputStreamo=null;
try{
makeDirs(file.getAbsolutePath());
o=newFileOutputStream(file,append);
bytedata[]=newbyte[1024];
intlength=-1;
while((length=stream.read(data))!=-1){
o.write(data,0,length);
}
o.flush();
returntrue;
}catch(FileNotFoundExceptione){
thrownewRuntimeException("FileNotFoundExceptionoccurred.",e);
}catch(IOExceptione){
thrownewRuntimeException("IOExceptionoccurred.",e);
}finally{
IOUtils.close(o);
IOUtils.close(stream);
}
}
/**
*movefile
*
*@paramsourceFilePath
*@paramdestFilePath
*/
publicstaticvoidmoveFile(StringsourceFilePath,StringdestFilePath){
if(TextUtils.isEmpty(sourceFilePath)||TextUtils.isEmpty(destFilePath)){
thrownewRuntimeException("BothsourceFilePathanddestFilePathcannotbenull.");
}
moveFile(newFile(sourceFilePath),newFile(destFilePath));
}
/**
*movefile
*
*@paramsrcFile
*@paramdestFile
*/
publicstaticvoidmoveFile(FilesrcFile,FiledestFile){
booleanrename=srcFile.renameTo(destFile);
if(!rename){
copyFile(srcFile.getAbsolutePath(),destFile.getAbsolutePath());
deleteFile(srcFile.getAbsolutePath());
}
}
/**
*copyfile
*
*@paramsourceFilePath
*@paramdestFilePath
*@return
*@throwsRuntimeExceptionifanerroroccurswhileoperatorFileOutputStream
*/
publicstaticbooleancopyFile(StringsourceFilePath,StringdestFilePath){
InputStreaminputStream=null;
try{
inputStream=newFileInputStream(sourceFilePath);
}catch(FileNotFoundExceptione){
thrownewRuntimeException("FileNotFoundExceptionoccurred.",e);
}
returnwriteFile(destFilePath,inputStream);
}
/**
*readfiletostringlist,aelementoflistisaline
*
*@paramfilePath
*@paramcharsetNameThenameofasupported{@linkjava.nio.charset.Charset
charset}
*@returniffilenotexist,returnnull,elsereturncontentoffile
*@throwsRuntimeExceptionifanerroroccurswhileoperatorBufferedReader
*/
publicstaticListreadFileToList(StringfilePath,StringcharsetName){
Filefile=newFile(filePath);
ListfileContent=newArrayList();
if(file==null||!file.isFile()){
returnnull;
}
BufferedReaderreader=null;
try{
InputStreamReaderis=newInputStreamReader(newFileInputStream(file),charsetName);
reader=newBufferedReader(is);
Stringline=null;
while((line=reader.readLine())!=null){
fileContent.add(line);
}
returnfileContent;
}catch(IOExceptione){
thrownewRuntimeException("IOExceptionoccurred.",e);
}finally{
IOUtils.close(reader);
}
}
/**
*getfilenamefrompath,notincludesuffix
*
*
*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"
*
*
*@paramfilePath
*@returnfilenamefrompath,notincludesuffix
*@see
*/
publicstaticStringgetFileNameWithoutExtension(StringfilePath){
if(StringUtils.isEmpty(filePath)){
returnfilePath;
}
intextenPosi=filePath.lastIndexOf(FILE_EXTENSION_SEPARATOR);
intfilePosi=filePath.lastIndexOf(File.separator);
if(filePosi==-1){
return(extenPosi==-1?filePath:filePath.substring(0,extenPosi));
}
if(extenPosi==-1){
returnfilePath.substring(filePosi+1);
}
return(filePosi
*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"
*
*
*@paramfilePath
*@returnfilenamefrompath,includesuffix
*/
publicstaticStringgetFileName(StringfilePath){
if(StringUtils.isEmpty(filePath)){
returnfilePath;
}
intfilePosi=filePath.lastIndexOf(File.separator);
return(filePosi==-1)?filePath:filePath.substring(filePosi+1);
}
/**
*getfoldernamefrompath
*
*
*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"
*
*
*@paramfilePath
*@return
*/
publicstaticStringgetFolderName(StringfilePath){
if(StringUtils.isEmpty(filePath)){
returnfilePath;
}
intfilePosi=filePath.lastIndexOf(File.separator);
return(filePosi==-1)?"":filePath.substring(0,filePosi);
}
/**
*getsuffixoffilefrompath
*
*
*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"
*
*
*@paramfilePath
*@return
*/
publicstaticStringgetFileExtension(StringfilePath){
if(StringUtils.isBlank(filePath)){
returnfilePath;
}
intextenPosi=filePath.lastIndexOf(FILE_EXTENSION_SEPARATOR);
intfilePosi=filePath.lastIndexOf(File.separator);
if(extenPosi==-1){
return"";
}
return(filePosi>=extenPosi)?"":filePath.substring(extenPosi+1);
}
/**
*Createsthedirectorynamedbythetrailingfilenameofthisfile,includingthecompletedirectorypathrequired
*tocreatethisdirectory.
*
*
*Attentions:
*- makeDirs("C:\\Users\\Trinea")canonlycreateusersfolder
*- makeFolder("C:\\Users\\Trinea\\")cancreateTrineafolder
*
*
*@paramfilePath
*@returntrueifthenecessarydirectorieshavebeencreatedorthetargetdirectoryalreadyexists,falseoneof
*thedirectoriescannotbecreated.
*
*- if{@linkFileUtils#getFolderName(String)}returnnull,returnfalse
*- iftargetdirectoryalreadyexists,returntrue
*- return{@linkFile#makeFolder}
*
*/
publicstaticbooleanmakeDirs(StringfilePath){
StringfolderName=getFolderName(filePath);
if(StringUtils.isEmpty(folderName)){
returnfalse;
}
Filefolder=newFile(folderName);
return(folder.exists()&&folder.isDirectory())?true:folder.mkdirs();
}
/**
*@paramfilePath
*@return
*@see#makeDirs(String)
*/
publicstaticbooleanmakeFolders(StringfilePath){
returnmakeDirs(filePath);
}
/**
*Indicatesifthisfilerepresentsafileontheunderlyingfilesystem.
*
*@paramfilePath
*@return
*/
publicstaticbooleanisFileExist(StringfilePath){
if(StringUtils.isBlank(filePath)){
returnfalse;
}
Filefile=newFile(filePath);
return(file.exists()&&file.isFile());
}
/**
*Indicatesifthisfilerepresentsadirectoryontheunderlyingfilesystem.
*
*@paramdirectoryPath
*@return
*/
publicstaticbooleanisFolderExist(StringdirectoryPath){
if(StringUtils.isBlank(directoryPath)){
returnfalse;
}
Filedire=newFile(directoryPath);
return(dire.exists()&&dire.isDirectory());
}
/**
*deletefileordirectory
*
*- ifpathisnullorempty,returntrue
*- ifpathnotexist,returntrue
*- ifpathexist,deleterecursion.returntrue
*
*
*@parampath
*@return
*/
publicstaticbooleandeleteFile(Stringpath){
if(StringUtils.isBlank(path)){
returntrue;
}
Filefile=newFile(path);
if(!file.exists()){
returntrue;
}
if(file.isFile()){
returnfile.delete();
}
if(!file.isDirectory()){
returnfalse;
}
for(Filef:file.listFiles()){
if(f.isFile()){
f.delete();
}elseif(f.isDirectory()){
deleteFile(f.getAbsolutePath());
}
}
returnfile.delete();
}
/**
*getfilesize
*
*- ifpathisnullorempty,return-1
*- ifpathexistanditisafile,returnfilesize,elsereturn-1
*
*
*@parampath
*@returnreturnsthelengthofthisfileinbytes.returns-1ifthefiledoesnotexist.
*/
publicstaticlonggetFileSize(Stringpath){
if(StringUtils.isBlank(path)){
return-1;
}
Filefile=newFile(path);
return(file.exists()&&file.isFile()?file.length():-1);
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。