java文件操作工具类分享(file文件工具类)
import java.io.bufferedinputstream;
import java.io.bufferedoutputstream;
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.text.dateformat;
import java.text.messageformat;
import java.util.arraylist;
import java.util.date;
import java.util.enumeration;
import java.util.list;
import java.util.locale;
import java.util.stringtokenizer;
import java.util.zip.zipentry;
import java.util.zip.zipfile;
/**
*
* @author ibm
*
*/
public class fileutil {
public static string dirsplit = "\\";//linux windows
/**
* save file accroding to physical directory infomation
*
* @param physicaldir
* physical directory
* @param fname
* file name of destination
* @param istream
* input stream of destination file
* @return
*/
public static boolean savefilebyphysicaldir(string physicalpath,
inputstream istream) {
boolean flag = false;
try {
outputstream os = new fileoutputstream(physicalpath);
int readbytes = 0;
byte buffer[] = new byte[8192];
while ((readbytes = istream.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, readbytes);
}
os.close();
flag = true;
} catch (filenotfoundexception e) {
e.printstacktrace();
} catch (ioexception e) {
e.printstacktrace();
}
return flag;
}
public static boolean createdirectory(string dir){
file f = new file(dir);
if (!f.exists()) {
f.mkdirs();
}
return true;
}
public static void saveasfileoutputstream(string physicalpath,string content) {
file file = new file(physicalpath);
boolean b = file.getparentfile().isdirectory();
if(!b){
file tem = new file(file.getparent());
// tem.getparentfile().setwritable(true);
tem.mkdirs();// 创建目录
}
//log.info(file.getparent()+";"+file.getparentfile().isdirectory());
fileoutputstream foutput =null;
try {
foutput = new fileoutputstream(physicalpath);
foutput.write(content.getbytes("utf-8"));
//foutput.write(content.getbytes());
}catch(ioexception ex) {
ex.printstacktrace();
throw new runtimeexception(ex);
}finally{
try {
foutput.flush();
foutput.close();
}catch(ioexception ex){
ex.printstacktrace();
throw new runtimeexception(ex);
}
}
//log.info("文件保存成功:"+ physicalpath);
}
/**
* copy文件
* @param srcfile string
* @param desfile string
* @return boolean
*/
public boolean copytofile(string srcfile, string desfile) {
file scrfile = new file(srcfile);
if (scrfile.isfile() == true) {
int length;
fileinputstream fis = null;
try {
fis = new fileinputstream(scrfile);
}
catch (filenotfoundexception ex) {
ex.printstacktrace();
}
file desfile = new file(desfile);
fileoutputstream fos = null;
try {
fos = new fileoutputstream(desfile, false);
}
catch (filenotfoundexception ex) {
ex.printstacktrace();
}
desfile = null;
length = (int) scrfile.length();
byte[] b = new byte[length];
try {
fis.read(b);
fis.close();
fos.write(b);
fos.close();
}
catch (ioexception e) {
e.printstacktrace();
}
} else {
scrfile = null;
return false;
}
scrfile = null;
return true;
}
/**
* copy文件夹
* @param sourcedir string
* @param destdir string
* @return boolean
*/
public boolean copydir(string sourcedir, string destdir) {
file sourcefile = new file(sourcedir);
string tempsource;
string tempdest;
string filename;
file[] files = sourcefile.listfiles();
for (int i = 0; i < files.length; i++) {
filename = files[i].getname();
tempsource = sourcedir + "/" + filename;
tempdest = destdir + "/" + filename;
if (files[i].isfile()) {
copytofile(tempsource, tempdest);
} else {
copydir(tempsource, tempdest);
}
}
sourcefile = null;
return true;
}
/**
* 删除指定目录及其中的所有内容。
* @param dir 要删除的目录
* @return 删除成功时返回true,否则返回false。
*/
public boolean deletedirectory(file dir) {
file[] entries = dir.listfiles();
int sz = entries.length;
for (int i = 0; i < sz; i++) {
if (entries[i].isdirectory()) {
if (!deletedirectory(entries[i])) {
return false;
}
} else {
if (!entries[i].delete()) {
return false;
}
}
}
if (!dir.delete()) {
return false;
}
return true;
}
/**
* file exist check
*
* @param sfilename file name
* @return boolean true - exist<br>
* false - not exist
*/
public static boolean checkexist(string sfilename) {
boolean result = false;
try {
file f = new file(sfilename);
//if (f.exists() && f.isfile() && f.canread()) {
if (f.exists() && f.isfile()) {
result = true;
} else {
result = false;
}
} catch (exception e) {
result = false;
}
/* return */
return result;
}
/**
* get file size
*
* @param sfilename file name
* @return long file's size(byte) when file not exist return -1
*/
public static long getsize(string sfilename) {
long lsize = 0;
try {
file f = new file(sfilename);
//exist
if (f.exists()) {
if (f.isfile() && f.canread()) {
lsize = f.length();
} else {
lsize = -1;
}
//not exist
} else {
lsize = 0;
}
} catch (exception e) {
lsize = -1;
}
/* return */
return lsize;
}
/**
* file delete
*
* @param sfilename file nmae
* @return boolean true - delete success<br>
* false - delete fail
*/
public static boolean deletefromname(string sfilename) {
boolean breturn = true;
try {
file ofile = new file(sfilename);
//exist
if (ofile.exists()) {
//delete file
boolean bresult = ofile.delete();
//delete fail
if (bresult == false) {
breturn = false;
}
//not exist
} else {
}
} catch (exception e) {
breturn = false;
}
//return
return breturn;
}
/**
* file unzip
*
* @param stopath unzip directory path
* @param szipfile unzip file name
*/
@suppresswarnings("rawtypes")
public static void releasezip(string stopath, string szipfile) throws exception {
if (null == stopath ||("").equals(stopath.trim())) {
file objzipfile = new file(szipfile);
stopath = objzipfile.getparent();
}
zipfile zfile = new zipfile(szipfile);
enumeration zlist = zfile.entries();
zipentry ze = null;
byte[] buf = new byte[1024];
while (zlist.hasmoreelements()) {
ze = (zipentry) zlist.nextelement();
if (ze.isdirectory()) {
continue;
}
outputstream os =
new bufferedoutputstream(
new fileoutputstream(getrealfilename(stopath, ze.getname())));
inputstream is = new bufferedinputstream(zfile.getinputstream(ze));
int readlen = 0;
while ((readlen = is.read(buf, 0, 1024)) != -1) {
os.write(buf, 0, readlen);
}
is.close();
os.close();
}
zfile.close();
}
/**
* getrealfilename
*
* @param basedir root directory
* @param absfilename absolute directory file name
* @return java.io.file return file
*/
@suppresswarnings({ "rawtypes", "unchecked" })
private static file getrealfilename(string basedir, string absfilename) throws exception {
file ret = null;
list dirs = new arraylist();
stringtokenizer st = new stringtokenizer(absfilename, system.getproperty("file.separator"));
while (st.hasmoretokens()) {
dirs.add(st.nexttoken());
}
ret = new file(basedir);
if (dirs.size() > 1) {
for (int i = 0; i < dirs.size() - 1; i++) {
ret = new file(ret, (string) dirs.get(i));
}
}
if (!ret.exists()) {
ret.mkdirs();
}
ret = new file(ret, (string) dirs.get(dirs.size() - 1));
return ret;
}
/**
* copyfile
*
* @param srcfile source file
* @param targetfile target file
*/
@suppresswarnings("resource")
static public void copyfile(string srcfile , string targetfile) throws ioexception
{
fileinputstream reader = new fileinputstream(srcfile);
fileoutputstream writer = new fileoutputstream(targetfile);
byte[] buffer = new byte [4096];
int len;
try
{
reader = new fileinputstream(srcfile);
writer = new fileoutputstream(targetfile);
while((len = reader.read(buffer)) > 0)
{
writer.write(buffer , 0 , len);
}
}
catch(ioexception e)
{
throw e;
}
finally
{
if (writer != null)writer.close();
if (reader != null)reader.close();
}
}
/**
* renamefile
*
* @param srcfile source file
* @param targetfile target file
*/
static public void renamefile(string srcfile , string targetfile) throws ioexception
{
try {
copyfile(srcfile,targetfile);
deletefromname(srcfile);
} catch(ioexception e){
throw e;
}
}
public static void write(string tivolimsg,string logfilename) {
try{
byte[] bmsg = tivolimsg.getbytes();
fileoutputstream fout = new fileoutputstream(logfilename, true);
fout.write(bmsg);
fout.close();
} catch(ioexception e){
//throw the exception
}
}
/**
* this method is used to log the messages with timestamp,error code and the method details
* @param errorcd string
* @param classname string
* @param methodname string
* @param msg string
*/
public static void writelog(string logfile, string batchid, string exceptioninfo) {
dateformat df = dateformat.getdatetimeinstance(dateformat.default, dateformat.default, locale.japanese);
object args[] = {df.format(new date()), batchid, exceptioninfo};
string fmtmsg = messageformat.format("{0} : {1} : {2}", args);
try {
file logfile = new file(logfile);
if(!logfile.exists()) {
logfile.createnewfile();
}
filewriter fw = new filewriter(logfile, true);
fw.write(fmtmsg);
fw.write(system.getproperty("line.separator"));
fw.flush();
fw.close();
} catch(exception e) {
}
}
public static string readtextfile(string realpath) throws exception {
file file = new file(realpath);
if (!file.exists()){
system.out.println("file not exist!");
return null;
}
bufferedreader br = new bufferedreader(new inputstreamreader(new fileinputstream(realpath),"utf-8"));
string temp = "";
string txt="";
while((temp = br.readline()) != null){
txt+=temp;
}
br.close();
return txt;
}
}
上一篇: RecyclerView使用详解