复制代码代码如下:
Импорт java.io.bufferedinputstream;
Импорт java.io.bufferedOutputStream;
Импорт java.io.bufferedReader;
Импорт java.io.file;
импортировать java.io.fileinputstream;
Импорт java.io.filenotFoundException;
Импорт java.io.fileOutputStream;
Импорт java.io.fileWriter;
импортировать java.io.ioexception;
импортировать java.io.inputstream;
Импорт java.io.inputStreamReader;
импортировать java.io.outputstream;
импортировать java.text.dateformat;
импортировать java.text.messageformat;
импортировать java.util.arraylist;
импортировать java.util.date;
Импорт java.util.enumeration;
импортировать java.util.list;
импортировать java.util.locale;
импортировать java.util.stringtokenizer;
Импорт java.util.zip.zipentry;
Импорт java.util.zip.zipfile;
/**
*
* @Author IBM
*
*/
открытый класс fileutil {
public static String dirsplit = "//"; // linux windows
/**
* Сохранить файл приобретения в инфомации физического каталога
*
* @param physicaldir
* Физический каталог
* @param fname
* Имя файла назначения
* @param iStream
* Поток ввода файла назначения
* @возвращаться
*/
Public Static Boolean SaveFileByphysicalDir (String PhysicalPath,
InputStream iStream) {
логический флаг = false;
пытаться {
OutputStream OS = new FileOutputStream (PhysicalPath);
int readbytes = 0;
байтовый буфер [] = новый байт [8192];
while ((readbytes = istream.read (буфер, 0, 8192))! = -1) {
Os.Write (буфер, 0, readbytes);
}
os.close ();
flag = true;
} catch (filenotFoundException e) {
e.printstacktrace ();
} catch (ioException e) {
e.printstacktrace ();
}
вернуть флаг;
}
Public Static Boolean Cenectirectory (String Dir) {
Файл f = новый файл (dir);
if (! f.exists ()) {
f.mkdirs ();
}
вернуть истину;
}
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 (). setWriteble (true);
Tem.mkdirs (); // 创建目录
}
//Log.info(file.getParent ()+";"+file.getParentFile (). IsDirectory ());
FileOutputStream foutput = null;
пытаться {
foutput = new FileOutputStream (PhysicalPath);
foutput.write (content.getbytes ("utf-8"));
//foutput.write (content.getbytes ());
} catch (ioException ex) {
ex.printstacktrace ();
бросить новое runtimeexception (ex);
}окончательно{
пытаться {
foutput.flush ();
foutput.close ();
} catch (ioException ex) {
ex.printstacktrace ();
бросить новое runtimeexception (ex);
}
}
//Log.info ("文件保存成功:"+ physicalpath);
}
/**
* Копировать 文件
* @param srcfile string
* @param desfile string
* @return Boolean
*/
public boolean copytofile (string srcfile, string desfile) {
File scrfile = new File (srcfile);
if (scrfile.ishile () == true) {
int длина;
FileInputStream fis = null;
пытаться {
fis = new FileInputStream (scrfile);
}
Catch (filenotFoundException ex) {
ex.printstacktrace ();
}
File desfile = new File (desfile);
FileOutputStream fos = null;
пытаться {
fos = new FileOutputStream (desFile, false);
}
Catch (filenotFoundException ex) {
ex.printstacktrace ();
}
desfile = null;
длина = (int) scrfile.length ();
byte [] b = новый байт [длина];
пытаться {
fis.read (b);
fis.close ();
fos.write (b);
fos.close ();
}
поймать (ioException e) {
e.printstacktrace ();
}
} еще {
scrfile = null;
вернуть ложь;
}
scrfile = null;
вернуть истину;
}
/**
* Копировать 文件夹
* @param Sourcedir String
* @param destdir String
* @return Boolean
*/
Public Boolean CopyDir (String Sourcedir, String destdir) {
File SourceFile = новый файл (Sourcedir);
String Tempsource;
String tempdest;
String FileName;
File [] files = sourcefile.listfiles ();
для (int i = 0; i <files.length; i ++) {
filename = files [i] .getName ();
tempsource = sourcedir + "/" + имя файла;
tempdest = destdir + "/" + filename;
if (files [i] .isfile ()) {
Copytofile (Tempsource, Tempdest);
} еще {
Copydir (Tempsource, Tempdest);
}
}
SourceFile = null;
вернуть истину;
}
/**
* 删除指定目录及其中的所有内容。
* @param dir 要删除的目录
* @return 删除成功时返回 true , 否则返回 false。
*/
public boolean deletedirectory (файл dir) {
File [] negries = dir.list -files ();
int sz = negries.length;
для (int i = 0; i <sz; i ++) {
if (intries [i] .isdirectory ()) {
if (! deletEdirectory (записи [i])) {
вернуть ложь;
}
} еще {
if (! nepros [i] .delete ()) {
вернуть ложь;
}
}
}
if (! dir.delete ()) {
вернуть ложь;
}
вернуть истину;
}
/**
* Файл существует проверка
*
* @param sfilename Имя файла
* @return Boolean True - существует <br>
* Неверно - не существует
*/
Public Static Boolean checkexist (String sfilename) {
логический результат = false;
пытаться {
Файл f = новый файл (sfilEname);
// if (f.exists () && f.isfile () && f.canread ()) {
if (f.exists () && f.isfile ()) {
result = true;
} еще {
result = false;
}
} catch (Exception e) {
result = false;
}
/* возвращаться */
результат возврата;
}
/**
* Получить размер файла
*
* @param sfilename Имя файла
* @return Long File (байт), когда файл не существует, возвращайте -1
*/
Public Static Long Getsize (String sfilename) {
long lsize = 0;
пытаться {
Файл f = новый файл (sfilEname);
//существовать
if (f.exists ()) {
if (f.isfile () && f.canread ()) {
lsize = f.length ();
} еще {
lsize = -1;
}
// не существует
} еще {
lsize = 0;
}
} catch (Exception e) {
lsize = -1;
}
/* возвращаться */
вернуть lsize;
}
/**
* Файл удалить
*
* @param sfilename file nmae
* @return Boolean True - Удалить успех <br>
* false - удалить неудачу
*/
public static boolean deletefromName (String sfilEname) {
Boolean Breturn = True;
пытаться {
File ofile = новый файл (sfilename);
//существовать
if (ofile.exists ()) {
// удалить файл
Boolean bresult = ofile.delete ();
// удалить неудачу
if (bresult == false) {
breturn = false;
}
// не существует
} еще {
}
} catch (Exception e) {
breturn = false;
}
//возвращаться
вернуть Брерн;
}
/**
* Файл unzip
*
* @param stoptath unzip tap
* @param szipfile unzip name файл
*/
@Suppresswarnings ("rawtypes")
public static void releasezip (String Stopath, String Szipfile) бросает исключение {
if (null == stopath || (""). equals (stopath.trim ())) {
File objzipfile = new File (szipfile);
stopath = objzipfile.getParent ();
}
Zipfile zfile = new zipfile (szipfile);
Перечисление zlist = ZFILE.Entries ();
Zipentry ze = null;
byte [] buf = new Byte [1024];
while (zlist.hasmoreelements ()) {
ze = (zipentry) zlist.nextelement ();
if (ze.isdirectory ()) {
продолжать;
}
OutputStream OS =
Новый буферизатор
new FileOutputStream (getRealFilEname (stophate, 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 на основе корневой каталог
* @param absfileName Absolute Directory Имя файла
* @return java.io.file File return File
*/
@Suppresswarnings ({"rawtypes", "uncecked"})
Частный статический файл getRealfilEname (string foundir, string absfilename) бросает исключение {
File ret = null;
Список dirs = new ArrayList ();
StringTokenizer st = new StringTokenizer (absfilEname, system.getProperty ("file.separator"));
в то время как (St.hasmoretokens ()) {
dirs.add (St.nexttoken ());
}
ret = новый файл (основанный);
if (dirs.size ()> 1) {
для (int i = 0; i <dirs.size () - 1; i ++) {
ret = новый файл (ret, (string) dirs.get (i));
}
}
if (! ret.exists ()) {
ret.mkdirs ();
}
ret = новый файл (ret, (строка) dirs.get (dirs.size () - 1));
вернуть вт;
}
/**
* CopyFile
*
* @param srcfile source file
* @param TargetFile Target File
*/
@Suppresswarnings ("ресурс")
Статический публичный void copyfile (String srcfile, String TargetFile) бросает ioException
{
FileInputStream Reader = new FileInputStream (srcfile);
FileOutputStream Writer = new FileOutputStream (TargetFile);
Byte [] buffer = новый байт [4096];
int len;
пытаться
{
reader = new FileInputStream (srcfile);
writer = new FileOutputStream (TargetFile);
while ((len = reader.read (buffer))> 0)
{
writer.write (Buffer, 0, Len);
}
}
поймать (ioException e)
{
бросить E;
}
окончательно
{
if (writer! = null) writer.close ();
if (reader! = null) reader.close ();
}
}
/**
* Переименовать
*
* @param srcfile source file
* @param TargetFile Target File
*/
Статическая публичная void renamefile (String srcfile, String TargetFile) бросает ioException
{
пытаться {
CopyFile (srcfile, TargetFile);
DeleteFromName (srcfile);
} catch (ioException e) {
бросить E;
}
}
public static void write (string tivolimsg, string logfilename) {
пытаться{
byte [] bmsg = tivolimsg.getbytes ();
FileOutputStream fout = new FileOutputStream (logFilename, true);
fout.write (bmsg);
fout.close ();
} catch (ioException e) {
// бросить исключение
}
}
/**
* Этот метод используется для регистрации сообщений с помощью метки времени, кода ошибки и сведений о методе
* @param errorcd строка
* @param classname String
* @param methodname String
* @param msg String
*/
public static void writelog (строка 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);
пытаться {
File logfile = new File (logfile);
if (! logfile.exists ()) {
logfile.createnewfile ();
}
FileWriter FW = новый файл -автора (logfile, true);
fw.write (fmtmsg);
fw.write (System.getProperty ("line.separator"));
fw.flush ();
fw.close ();
} catch (Exception e) {
}
}
Public Static String ReadTextFile (String RealPath) бросает исключение {
File file = new File (realPath);
if (! file.exists ()) {
System.out.println («Файл не существует!»);
вернуть ноль;
}
BufferedReader br = new BufferedReader (New InputStreamReader (New FileInputStream (RealPath), "UTF-8"));
String temp = "";
String txt = "";
while ((temp = br.readline ())! = null) {
txt+= temp;
}
br.close ();
вернуть txt;
}
}