复制代码代码如下:
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;
importar java.util.enerumeration;
import java.util.list;
import java.util.locale;
import java.util.stringTokenizer;
import java.util.zip.zipentry;
import java.util.zip.zipfile;
/**
*
* @author ibm
*
*/
clase pública FileUtil {
public static string dirsplit = "//"; // Linux Windows
/**
* Guardar el archivo de acroda a la infominación del directorio físico
*
* @param físicodir
* Directorio físico
* @param fname
* Nombre del archivo del destino
* @param istream
* FLUJO DE ENTRADA DEL ARCHIVO DE Destino
* @devolver
*/
Público estático Boolean SaveFileByPhySicalDir (String PhysicalPath,
InputStream istream) {
bandera booleana = falso;
intentar {
OutputStream OS = new FileOutputStream (PhysicalPath);
int readbytes = 0;
byte buffer [] = nuevo byte [8192];
while ((readBytes = istream.read (buffer, 0, 8192))! = -1) {
OS.Write (Buffer, 0, Readbytes);
}
os.close ();
bandera = verdadero;
} catch (FileNotFoundException e) {
E.PrintStackTrace ();
} Catch (ioException e) {
E.PrintStackTrace ();
}
Bandera de regreso;
}
Public static boolean createIrectory (string dir) {
Archivo F = nuevo archivo (Dir);
if (! f.exists ()) {
f.mkdirs ();
}
devolver verdadero;
}
public static void saveasfileOutputStream (String PhysicalPath, String Content) {
Archivo archivo = nuevo archivo (PhysicalPath);
booleano b = file.getParentFile (). ISDirectory ();
if (! b) {
Archivo tem = nuevo archivo (file.getParent ());
// tem.getParentFile (). SetWritable (true);
tem.mkdirs (); // 创建目录
}
//Log.info(file.getParent ()+";"+file.getParentFile (). IsDirectory ());
FileOutputStream foutput = null;
intentar {
foutput = new FileOutputStream (PhysicalPath);
foutput.write (content.getBytes ("utf-8"));
//foutput.write (content.getBytes ());
} catch (ioException ex) {
Ex.PrintStackTrace ();
tirar nueva runtimeException (ex);
}finalmente{
intentar {
foutput.flush ();
foutput.close ();
} catch (ioException ex) {
Ex.PrintStackTrace ();
tirar nueva runtimeException (ex);
}
}
//Log.info ("文件保存成功:"+ PhysicalPath);
}
/**
* Copiar 文件
* @param srcfile cadena
* @param desfile cadena
* @return boolean
*/
public boolean CopyToFile (String srcFile, string desfile) {
Archivo scrfile = nuevo archivo (srcfile);
if (scrfile.isfile () == true) {
int longitud;
FileInputStream fis = null;
intentar {
fis = nuevo FileInputStream (SCRFILE);
}
Catch (FileNotFoundException ex) {
Ex.PrintStackTrace ();
}
Archivo desfile = nuevo archivo (desfile);
FileOutputStream fos = null;
intentar {
fos = nuevo FileOutputStream (Desfile, False);
}
Catch (FileNotFoundException ex) {
Ex.PrintStackTrace ();
}
desfile = nulo;
longitud = (int) scrfile.length ();
byte [] b = nuevo byte [longitud];
intentar {
fis.read (b);
fis.close ();
fos.write (b);
fos.close ();
}
Catch (ioException e) {
E.PrintStackTrace ();
}
} demás {
scrfile = nulo;
devolver falso;
}
scrfile = nulo;
devolver verdadero;
}
/**
* Copiar 文件夹
* @param Sourcedir String
* @param Destdir String
* @return boolean
*/
public boolean Copydir (String SourCedir, String Destdir) {
Archivo SourceFile = nuevo archivo (SourDir);
Cadena TempSource;
Cadena tempDest;
Nombre de archivo de cadena;
Archivo [] archivos = fuenteFile.ListFiles ();
for (int i = 0; i <files.length; i ++) {
filename = archivos [i] .getName ();
tempSource = SourCedir + "/" + nombre de archivo;
tempDest = DestDir + "/" + FileName;
if (files [i] .isfile ()) {
CopyToFile (TempSource, TempDest);
} demás {
CopyDir (TempSource, TempDest);
}
}
fuenteFile = nulo;
devolver verdadero;
}
/**
* 删除指定目录及其中的所有内容。
* @param dir 要删除的目录
* @return 删除成功时返回 verdadero , 否则返回 falso。
*/
Public Boolean Deletedirectory (File Dir) {
Archivo [] entradas = dir.listFiles ();
int sz = entrates.length;
para (int i = 0; i <sz; i ++) {
if (entradas [i] .isDirectory ()) {
if (! deletedirectory (entradas [i])) {
devolver falso;
}
} demás {
if (! entradas [i] .delete ()) {
devolver falso;
}
}
}
if (! dir.delete ()) {
devolver falso;
}
devolver verdadero;
}
/**
* El archivo existe verificación
*
* @param Sfilename Nombre del archivo
* @return boolean verdadero - existir <br>
* Falso - no existir
*/
Public static static boolean checkexist (string sfileName) {
resultado booleano = falso;
intentar {
Archivo f = nuevo archivo (sfileName);
// if (f.exists () && f.isfile () && f.canread ()) {
if (f.exists () && f.isfile ()) {
resultado = verdadero;
} demás {
resultado = falso;
}
} Catch (Exception e) {
resultado = falso;
}
/* devolver */
resultado de retorno;
}
/**
* Obtener el tamaño del archivo
*
* @param Sfilename Nombre del archivo
* @return long size (byte) cuando el archivo no existe return -1
*/
public static long getsize (string sfileName) {
long lsize = 0;
intentar {
Archivo f = nuevo archivo (sfileName);
//existir
if (f.exists ()) {
if (f.isfile () && f.canread ()) {
lsize = f.length ();
} demás {
lsize = -1;
}
// no existir
} demás {
lsize = 0;
}
} Catch (Exception e) {
lsize = -1;
}
/* devolver */
devolver lsize;
}
/**
* Eliminar el archivo
*
* @param sfilename archivo nmae
* @return boolean true - Eliminar éxito <br>
* Falso - Eliminar falla
*/
public static boolean deleteFromName (string sfileName) {
boolean breturn = verdadero;
intentar {
Archivo ofile = nuevo archivo (sfileName);
//existir
if (ofile.exists ()) {
// Eliminar archivo
boolean bresult = ofile.delete ();
// Eliminar falla
if (bresult == false) {
Breturn = falso;
}
// no existir
} demás {
}
} Catch (Exception e) {
Breturn = falso;
}
//devolver
regresar Breturn;
}
/**
* Archivo descifrado
*
* @param stopath ruta de directorio unzip
* @param szipfile nombre de archivo unzip
*/
@SupessWarnings ("RawTypes")
Public static void libeSzip (string stopath, string szipfile) arroja excepción {
if (null == stopath || (""). igual (stopath.trim ())) {
Archivo objzipfile = nuevo archivo (szipfile);
stopath = objzipfile.getParent ();
}
ZIPFILE zFILE = new ZipFile (szipfile);
Enumeración zlist = zfile.entries ();
ZipEntry ze = nulo;
byte [] buf = nuevo byte [1024];
while (zlist.hasmoreelements ()) {
ze = (ZipEntry) ZList.NextElement ();
if (ze.isdirectory ()) {
continuar;
}
OutputStream OS =
nuevo bufferingoutputStream (
nuevo FileOutputStream (getRealFileName (stopath, ze.getName ())));
InputStream es = 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 Nombre del archivo de directorio absoluto
* @return java.io.file File de retorno
*/
@SupessWarnings ({"RawTypes", "sin control"})
Archivo estático privado GetRealFileName (String Basedir, String AbsfileName) lanza la excepción {
Archivo ret = null;
List dirs = new ArrayList ();
StringTokenizer st = new StringTokenizer (absfileName, system.getProperty ("file.separator"));
while (St.hasmoretokens ()) {
dirs.add (St.NextToken ());
}
Ret = nuevo archivo (Basedir);
if (dirs.size ()> 1) {
para (int i = 0; i <dirs.size () - 1; i ++) {
ret = nuevo archivo (ret, (string) dirs.get (i));
}
}
if (! ret.exists ()) {
ret.mkdirs ();
}
Ret = nuevo archivo (ret, (string) dirs.get (dirs.size () - 1));
regresar ret;
}
/**
* CopyFile
*
* @param srcfile archivo fuente
* @Param TargetFile Target File
*/
@SupessWarnings ("recurso")
static public void copyfile (string srcfile, string TargetFile) lanza ioexception
{
FileInputStream lector = new FileInputStream (srcfile);
FileOutputStream Writer = new FileOutputStream (TargetFile);
byte [] buffer = new Byte [4096];
int len;
intentar
{
lector = new FileInputStream (srcfile);
escritor = nuevo FileOutputStream (TargetFile);
while ((len = lector.read (buffer))> 0)
{
Writer.Write (Buffer, 0, Len);
}
}
Catch (ioexception e)
{
tirar E;
}
finalmente
{
if (escritor! = null) escritor.close ();
if (lector! = null) lector.close ();
}
}
/**
* RenameFile
*
* @param srcfile archivo fuente
* @Param TargetFile Target File
*/
static public void renameFile (string srcfile, string TargetFile) lanza ioexception
{
intentar {
copyfile (srcfile, targetFile);
eliminar de nombre (srcfile);
} Catch (ioException e) {
tirar E;
}
}
Public static void write (string tivolimsg, string logFileName) {
intentar{
byte [] bmsg = tivolimsg.getBytes ();
FileOutputStream fout = new FileOutputStream (logFileName, true);
fout.write (BMSG);
fout.close ();
} Catch (ioException e) {
// arroja la excepción
}
}
/**
* Este método se usa para registrar los mensajes con marca de tiempo, código de error y detalles del método
* @param ErrorCD String
* @param ClassName String
* @Param MethodName String
* @param msg cadena
*/
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);
intentar {
Archivo logFile = nuevo archivo (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) lanza la excepción {
Archivo archivo = nuevo archivo (realPath);
if (! file.exists ()) {
System.out.println ("Archivo no existen!");
regresar nulo;
}
BufferedReader BR = New BufferedReader (nuevo InputStreamReader (nuevo FileInputStream (RealPath), "UTF-8"));
Cadena temp = "";
Cadena txt = "";
while ((temp = br.readline ())! = null) {
txt+= temp;
}
br.close ();
devolver txt;
}
}