复制代码代码如下:
importar java.io.bufferInputStream;
importar java.io.bufferedOutputStream;
importar java.io.bufferedReader;
importar java.io.file;
importar java.io.fileInputStream;
importar java.io.filenotfoundException;
importar java.io.fileOutputStream;
importar java.io.filewriter;
importar java.io.ioException;
importar java.io.inputStream;
importar java.io.inputStreamReader;
importar java.io.OutputStream;
importar java.text.dateFormat;
importar java.text.messageFormat;
importar java.util.arraylist;
importar java.util.date;
importar java.util.enumeration;
importar java.util.list;
importar java.util.locale;
importar java.util.stringTokenizer;
importar java.util.zip.zipentry;
importar java.util.zip.zipfile;
/**
*
* @Author IBM
*
*/
classe pública FileUtil {
public static string dirsplit = "//"; // Windows Linux
/**
* Salvar o arquivo acumulado na informação do diretório físico
*
* @param PhysicalDir
* diretório físico
* @param fname
* Nome do arquivo de destino
* @param isTream
* Fluxo de entrada de arquivo de destino
* @retornar
*/
Public Static Boolean SaveFileByphysicalDir (String PhysicalPath,
InputStream isTream) {
bandeira booleana = false;
tentar {
OutputStream OS = new FileOutputStream (PhysicalPath);
int readBytes = 0;
buffer de byte [] = novo byte [8192];
while ((readbytes = iStream.read (buffer, 0, 8192))! = -1) {
OS.WRITE (Buffer, 0, ReadBytes);
}
os.close ();
bandeira = true;
} catch (filenotfoundException e) {
E.PrintStackTrace ();
} catch (ioexception e) {
E.PrintStackTrace ();
}
bandeira de retorno;
}
public estático booleano criado.
Arquivo f = novo arquivo (dir);
if (! f.exists ()) {
f.mkdirs ();
}
retornar true;
}
public static void SAVEasFileOutputStream (String PhysicalPath, String Content) {
Arquivo de arquivo = novo arquivo (PhysicalPath);
booleano b = file.getParentFile (). IsDirectory ();
if (! b) {
Arquivo tem = novo arquivo (file.getParent ());
// tem.getparentfile (). setWritable (true);
tem.mkdirs (); // 创建目录
}
//Log.info(file.getParent ()+";"+file.getParentFile (). IsDirectory ());
FileOutputStream foutput = null;
tentar {
foutput = new FileOutputStream (PhysicalPath);
foutput.Write (Content.getBytes ("UTF-8"));
//foutput.write (content.getBytes ());
} catch (ioexception ex) {
Ex.PrintStackTrace ();
lançar a nova RuntimeTimeException (EX);
}finalmente{
tentar {
foutput.flush ();
foutput.close ();
} catch (ioexception ex) {
Ex.PrintStackTrace ();
lançar a nova RuntimeTimeException (EX);
}
}
//Log.info ("文件保存成功:"+ PhysicalPath);
}
/**
* Copiar 文件
* @param srcfile string
* @param desfile string
* @return boolean
*/
public boolean copytofile (string srcfile, string desfile) {
Arquivo scrfile = novo arquivo (srcfile);
if (scrfile.isfile () == true) {
comprimento int;
FileInputStream fis = null;
tentar {
fis = new FileInputStream (scrfile);
}
Catch (filenotfoundException ex) {
Ex.PrintStackTrace ();
}
Arquivo desfile = novo arquivo (desfile);
FileOutputStream fos = null;
tentar {
fos = new FileOutputStream (desfile, false);
}
Catch (filenotfoundException ex) {
Ex.PrintStackTrace ();
}
DESFILE = NULL;
comprimento = (int) scrfile.length ();
byte [] b = novo byte [comprimento];
tentar {
fis.read (b);
fis.close ();
fos.write (b);
fos.close ();
}
Catch (ioexception e) {
E.PrintStackTrace ();
}
} outro {
scrfile = null;
retornar falso;
}
scrfile = null;
retornar true;
}
/**
* Copiar 文件夹
* @param soucedir string
* @param destdir string
* @return boolean
*/
public boolean copydir (string soucedir, string destdir) {
Arquivo fontesfile = novo arquivo (sourcedir);
String tempsource;
String tempdest;
String filename;
Arquivo [] arquivos = fontefile.listfiles ();
for (int i = 0; i <files.length; i ++) {
arquivo de arquivo = arquivos [i] .getName ();
tempsource = soucedir + "/" + nome do arquivo;
tempdest = destdir + "/" + filename;
if (arquivos [i] .isfile ()) {
copytofile (tempsource, tempdest);
} outro {
copydir (tempsource, tempdest);
}
}
Sourcefile = NULL;
retornar true;
}
/**
* 删除指定目录及其中的所有内容。
* @param dir 要删除的目录
* @return 删除成功时返回 true , 否则返回 falso。
*/
Public Boolean Deletedirectory (Arquivo dir) {
Arquivo [] entradas = dir.ListFiles ();
int sz = entradas.length;
for (int i = 0; i <sz; i ++) {
if (entradas [i] .Isdirectory ()) {
if (! deletedirectory (entradas [i])) {
retornar falso;
}
} outro {
if (! entradas [i] .Delete ()) {
retornar falso;
}
}
}
if (! Dir.Delete ()) {
retornar falso;
}
retornar true;
}
/**
* O arquivo existe verificação
*
* Nome do arquivo @param sfilename
* @return boolean true - existe <br>
* Falso - não existe
*/
Public Static Boolean CheCkexist (String SfileName) {
resultado booleano = false;
tentar {
Arquivo f = novo arquivo (sfilename);
// if (f.exists () && f.isfile () && f.canread ()) {
if (f.Exists () && f.isfile ()) {
resultado = true;
} outro {
resultado = false;
}
} catch (Exceção e) {
resultado = false;
}
/* retornar */
resultado de retorno;
}
/**
* Obtenha o tamanho do arquivo
*
* Nome do arquivo @param sfilename
* @return size (byte) quando o arquivo não existir retorna -1
*/
public static long getsize (string sfilename) {
long lsize = 0;
tentar {
Arquivo f = novo arquivo (sfilename);
// existe
if (f.Exists ()) {
if (f.isfile () && f.canread ()) {
lsize = f.Length ();
} outro {
lsize = -1;
}
// não existe
} outro {
lsize = 0;
}
} catch (Exceção e) {
lsize = -1;
}
/* retornar */
retornar lsize;
}
/**
* Excluir arquivo
*
* @param sfilename arquivo nmae
* @return boolean true - Excluir sucesso <br>
* Falso - Excluir falha
*/
public static boolean DeleteFromName (String SfileName) {
breturn booleano = true;
tentar {
Arquivo deile = novo arquivo (sfilename);
// existe
if (ofile.exists ()) {
// Excluir arquivo
boolean bresult = ofile.delete ();
// excluir falha
if (bresult == false) {
breturn = false;
}
// não existe
} outro {
}
} catch (Exceção e) {
breturn = false;
}
//retornar
retornar breturn;
}
/**
* Arquive descompactação
*
* @param stopath unzip diretório caminho
* @param szipfile Unzip Nome do arquivo
*/
@Suppresswarnings ("RawTypes")
public static void ReleaseZip (String Stopath, String szipfile) lança exceção {
if (null == stopath || (""). igual a (stopath.trim ())) {
Arquivo objzipfile = novo arquivo (szipfile);
stopath = objzipfile.getParent ();
}
Zipfile zfile = novo zipfile (szipfile);
Enumeração zlist = zfile.entries ();
Zipentry ze = null;
byte [] buf = novo byte [1024];
while (zlist.hasMoreElements ()) {
ze = (zipentry) zlist.nextElement ();
if (ze.isdirectory ()) {
continuar;
}
OutputStream OS =
New BufferedOutputStream (
novo FileOutputStream (getRealFilename (Stopath, ze.getName ())));
InputStream é = new bufferInputStream (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 baseado no diretório raiz
* @param absfilename de diretório absoluto Nome do arquivo
* @return java.io.file Retorno Arquivo
*/
@Suppresswarnings ({"RawTypes", "desmarcado"})
arquivo estático privado getRealfilename (string baseado, string absfilename) lança Exceção {
Arquivo ret = null;
Lista Dirs = new ArrayList ();
StringTokenizer st = new StringTokenizer (absfilename, System.getProperty ("file.separator"));
while (St.HasmoreTokens ()) {
Dirs.Add (St.NextToken ());
}
ret = novo arquivo (baseado);
if (dir.size ()> 1) {
for (int i = 0; i <dirs.size () - 1; i ++) {
ret = novo arquivo (ret, (string) dir.get (i));
}
}
if (! ret.exists ()) {
ret.mkdirs ();
}
ret = novo arquivo (ret, (string) dir.get (dir.size () - 1));
retornar ret;
}
/**
* CopyFile
*
* @param srcfile fonte de origem
* Arquivo de destino @param TargetFile
*/
@Suppresswarnings ("recurso")
estático public void copyfile (string srcfile, string TargetFile) lança a ioexception
{
FileInputStream Reader = new FileInputStream (srcfile);
FileOutputStream Writer = new FileOutputStream (TargetFile);
byte [] buffer = novo byte [4096];
int len;
tentar
{
leitor = new FileInputStream (srcfile);
writer = new FileOutputStream (TargetFile);
while ((len = leitor.read (buffer))> 0)
{
writer.write (buffer, 0, len);
}
}
Catch (ioexception e)
{
jogar e;
}
finalmente
{
if (writer! = null) writer.close ();
if (leitor! = null) leitor.close ();
}
}
/**
* Renomearfile
*
* @param srcfile fonte de origem
* Arquivo de destino @param TargetFile
*/
estático public void renamefile (string srcfile, string targetfile) lança a ioexception
{
tentar {
CopyFile (SRCFile, TargetFile);
deletefromName (srcfile);
} catch (ioexception e) {
jogar e;
}
}
public static void write (string tivolimsg, string logfilename) {
tentar{
byte [] bmsg = tivolimsg.getBytes ();
FileOutputStream fout = new FileOutputStream (LogFileName, true);
fout.Write (BMSG);
fout.close ();
} catch (ioexception e) {
// joga a exceção
}
}
/**
* Este método é usado para registrar as mensagens com registro de data e hora, código de erro e detalhes do método
* @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);
Objeto args [] = {df.format (new Date ()), Batchid, ExceptionInfo};
String fmtmsg = messageFormat.format ("{0}: {1}: {2}", args);
tentar {
Arquivo logfile = novo arquivo (arquivo de log);
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 (Exceção e) {
}
}
public static string readtextfile (string realpath) lança exceção {
Arquivo de arquivo = novo arquivo (realpath);
if (! file.exists ()) {
System.out.println ("arquivo não existe!");
retornar nulo;
}
BufferErader BR = new BufferredReader (new InputStreamReader (new FileInputStream (RealPath), "UTF-8"));
String temp = "";
String txt = "";
while ((temp = br.readline ())! = null) {
txt+= temp;
}
br.close ();
retornar txt;
}
}