com.ccb.suap.util.file package;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
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.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.ccb.suap.cloud.exception.CommonRuntimeException;
import com.ccb.suap.util.Base64;
import com.ccb.suap.util.Utils;
/ **
* file manipulation tools
* @author Deyang
*
* /
public class FileUtils {
Final static String = the ENCODE protected "UTF-8";
public static log001 Final String = "file creation failed";
public static log002 Final String = "file name can not be found";
public static log003 Final String = "read the file failed." ;
public static log004 Final String = "file failed to write people";
/**
* 获取文件流
* @param uri 文件URI
* @return
* @throws IOException
*/
public static final InputStream getResource(String uri) throws IOException {
try {
return new URL(uri).openStream();
} catch (MalformedURLException mue) {
}
return new FileInputStream(uri);
}
/ **
* Check backup file path exists, the new backup path does not exist
* as: /home/ap/log/1.log corresponding backup path: / Home / AP / log / Backup /
* @param File
* @return backup file directory object
* /
public static checkBackupDirectory Final file (file file) {
file BackupDirectory = new new file (file.getParent () + File.separator
+ "backup");
IF ((backupDirectory.exists ())!)
backupDirectory.mkdirs ();
BackupDirectory return;
}
/ **
* Set permissions files or folders, only for the file server / home / tsmfile / tsmftpdir the directory or file
* @param filedir
* /
public static void setFilePermissions Final (String filedir) {
/ * This method efficiency exists, instead umask 022 command to automatically set the file permissions * /
/ * String permissions = Config.getStrPara ( "CREATE_FILE_PERMISSIONS", "775");
the try {
String = OSNAME the System.getProperty ( "The os.name");
Boolean = osName.toLowerCase isWindows () startsWith ( "Windows");.
IF (isWindows) {
return;
}
the while (! fileDir.indexOf (FTPRemoteFileRootPath) = -. 1) {
Runtime.getRuntime () Exec ( "the chmod -R & lt" Permissions + + "" + filedir);.
File File = new new File (filedir);
file.setExecutable (to true, to false); // set executable permissions
file.setReadable ( true, false); // set the read permission
file.setWritable (true, false); // set the writable
filedir file.getParent = ();
IF (filedir == null || FTPRemoteFileRootPath.equals (filedir)) {
BREAK;
}
int IDX = fileDir.indexOf ( "/");
IF (IDX == -. 1) {
IDX = fileDir.indexOf ( "\\");
}
if(idx==-1){
break;
}
}
} catch (IOException e) {
LogUtil.error("chmod -R " + permissions,e);
}*/
}
/ **
* Create the file path
* /
public static Boolean createDirs Final (String path) {
File File = new new File (path);
return file.mkdirs ();
}
/**
* 新建文件
* @param path 文件路径
* @return
*/
public static final File createFile(String path) {
File file = new File(path);
try {
file.createNewFile();
} catch (IOException e) {
throw new CommonRuntimeException("XATF300100AJ", log001 + ":"
+ path, e);
}
return file;
}
/ **
* Get a list of directory file paths
* @param path file path
* @return
* /
public static Final String [] DirList (String path) {
return DirList (new new File (path));
}
public static final String[] dirList(File path) {
String[] list = path.list();
return list;
}
/ **
* reads the contents of the file
* @param file file path
* @return
* /
public static readFile Final String (String File) {
return readFile (File, ENCODE);
}
/ **
* reads the contents of the file
* @param file file path
* @param charsetName character set encoding file
* @return
* /
public static String Final readFile (File String, String charsetName) {
the StringBuffer SB = null;
the BufferedReader in = null;
FIS = null the FileInputStream;
the try {
SB = the StringBuffer new new ();
FIS new new = the FileInputStream (File);
in the BufferedReader new new = (the InputStreamReader new new (
FIS, charsetName));
String STR;
the while ((STR = in.readLine ()) ! = null) {
sb.append(str).append("\r\n");
}
return sb.toString();
} catch (FileNotFoundException e) {
throw new CommonRuntimeException("XATF300100AG", log003 + ":"
+ file + "[" + charsetName + "]", e);
} catch (IOException e) {
throw new CommonRuntimeException("XATF300100AH", log003 + ":"
+ file + "[" + charsetName + "]", e);
} finally {
if(fis!=null){
try{
fis.close();
}catch(Exception e){}
}
if(in!=null){
try{
in.close();
}catch(Exception e){}
}
}
}
public static final Reader getReader(File file, String charsetName)
throws Exception {
return new BufferedReader(new InputStreamReader(new FileInputStream(
file), charsetName));
}
public static final Reader getReader(File file) throws Exception {
return getReader(file, enCode);
}
public static final DataInputStream getDataInputStream(String filePath)
throws Exception {
return new DataInputStream(new FileInputStream(filePath));
}
public static final DataOutputStream getDataOutputStream(String filePath)
throws Exception {
DataOutputStream dos = new DataOutputStream(new FileOutputStream(filePath));
return dos;
}
public static final String readBinaryFile2Hex(String file){
DataInputStream dis = null;
try{
dis = getDataInputStream(file);
byte[] b = new byte[dis.available()];
dis.readFully(b);
return Utils.bytes2Hex(b);
}catch(Exception e){
throw new CommonRuntimeException("XATF300100AG", log003 + ":"
+ file , e);
}finally{
if(dis!=null){
try{
dis.close();
}catch(Exception e){}
}
}
}
public static final String readBinaryFile2Base64(String file){
DataInputStream dis = null;
try{
dis = getDataInputStream(file);
byte[] b = new byte[dis.available()];
dis.readFully(b);
return new String(Base64.encode(b));
}catch(Exception e){
throw new RuntimeException("XATF300100AG" + log003 + ":"
+ file , e);
}finally{
if(dis!=null){
try{
dis.close();
}catch(Exception e){}
}
}
}
/**
* 写入文件内容
* @param file 文件对象
* @param content 内容
*/
public static final void write(File file, String content) {
write(file, content, enCode);
}
/ **
* write contents of a file
* @param file file object
* @param content content
* @param charsetName character set encoding file
* /
public static void Write Final (File File, Content String, String charsetName) {
Writer OUT = null;
{the try
OUT = new new BufferedWriter, (the OutputStreamWriter new new (
new new a FileOutputStream (File), charsetName));
out.write(content);
out.flush();
} catch (FileNotFoundException e) {
throw new CommonRuntimeException("XATF300100AG", log002 + ":"
+ file + "[" + charsetName + "]", e);
} catch (IOException e) {
throw new CommonRuntimeException("XATF300100AI", log004 + ":"
+ file + "[" + charsetName + "]", e);
} finally {
if(out!=null){
try{
out.close();
}catch(Exception e){}
}
}
}
public static final Writer getWriter(File file) throws Exception {
return getWriter(file, enCode);
}
public static final Writer getWriter(File file, String charsetName)
throws Exception {
Writer w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
file), charsetName));
return w;
}
/ **
* write the file content and the backup of the original files to the backup directory, the backup file name:. FileName.yyyyMMdd_hhmmss *
* @param File file object
* @param content contents
* /
public static void writeAndBackup Final (File File, String Content) {
DateFormat backupDF = null;
BufferedWriter, OUT = null;
the try {
backupDF the SimpleDateFormat new new = ( "YYYYMMDD_HHMMSS");
File BackupDirectory = checkBackupDirectory (File);
File = Original new new File (file.getAbsolutePath ());
File Backup File new new = ( BackupDirectory, original.getName () + "."
+ backupDF.format (new new a Date ()));
original.renameTo(backup);
out = new BufferedWriter(new FileWriter(file));
out.write(content);
out.flush();
} catch (FileNotFoundException e) {
throw new CommonRuntimeException("XATF300100AG", log002 + ":"
+ file, e);
} catch (IOException e) {
throw new CommonRuntimeException("XATF300100AI", log004 + ":"
+ file, e);
} finally {
if(out!=null){
try{
out.close();
}catch(Exception e){}
}
}
}
/ **
* is determined whether there is a file path, a new path does not exist file
*
* @param the dir
* file path
* @return
* /
public static Boolean checkDir (String the dir) {
File File new new F = (the dir);
IF (F. EXISTS ())
return to true;
if (!(f.isDirectory())) {
return f.mkdirs();
}
return false;
}
/ **
* Check that file exists
* @param path
* @return
* /
public static Boolean checkFile (String path) {
File File new new F = (path);
Boolean = RES to false;
IF (f.exists ())
RES = to true;
return RES;
}
/ **
* Copy all files in the directory to the target directory
* @param source source file directory
* @param destination target directory
* @return
* @throws IOException
* /
@SuppressWarnings ( "Resource")
public static boolean CopyFiles (String Source, String Where do you want)
throws IOException {
File File = new new File (Source);
IF (checkDir (Where do you want!)) {
return to false;
}
FileChannel in = null;
FileChannel OUT = null;
Boolean RES = to false;
the try {
in = new new the FileInputStream ( file) .getChannel ();
File outFile = new File(destination, file.getName());
out = new FileOutputStream(outFile).getChannel();
in.transferTo(0L, in.size(), out);
res = true;
} finally {
try{
if (in != null)
in.close();
}catch(Exception e){}
try{
if (out != null)
out.close();
}catch(Exception e){}
}
return res;
}
/**
* 复制指定文件至指定目录
* @param s 源文件
* @param t 目标文件
* @return
* @throws Exception
*/
public static boolean copyFile(String s, String t) throws Exception {
File source = new File(s);
File target = new File(t);
if(!checkDir(target.getParent())){
return false;
}
boolean result = false;
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(source));
out = new BufferedOutputStream(new FileOutputStream(target),
(int) source.length());
byte[] file = new byte[(int) source.length()];
while (in.read(file) > 0)
out.write(file);
result = true;
} finally {
try {
if (in != null)
in.close();
} catch (Exception ex) {
result = false;
}
try {
if (out != null)
out.close();
} catch (Exception ex) {
result = false;
}
}
return result;
}
/**
* 删除文件或目录
*
* @param fileName
* 要删除的文件或目录
* @return
*/
public static boolean deleteFile(String fileName) {
boolean result = true;
try {
File file = new File(fileName);
if (file.isFile()) {
file.delete();
} else {
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
deleteFile(fileName + "/" + filelist[i]);
}
file.delete();
}
} catch (Exception e) {
result = false;
}
return result;
}
/**
* 移动文件
*
* @param source
* 源文件
* @param target
* 目标文件
*/
public static void moveFile(String source, String target) throws Exception {
target = target.replaceAll("\\\\", "/");
String targetDirPath = target.substring(0, target.lastIndexOf("/"));
File targetDir = new File(targetDirPath);
if (!targetDir.exists()) {
targetDir.mkdirs();
}
boolean flag = copyFile(source, target);
if (flag) {
deleteFile(source);
}
}
/**
* 将InputStream保存到文件
* @param filePath 文件路径
* @param inputStream
* @return
*/
public static boolean inputStream2File(String filePath,
InputStream inputStream) {
if (filePath == null || filePath.isEmpty()) {
return false;
}
OutputStream os = null;
try {
os = new FileOutputStream(filePath);
int nBytesRead = 0;
byte[] buffer = new byte[8192];
while ((nBytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, nBytesRead);
}
os.flush();
inputStream.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if(os!=null){
try{
os.close();
}catch(Exception e){}
}
if(inputStream!=null){
try{
inputStream.close();
}catch(Exception e){}
}
}
}
}