package com.dy.pipIrrWebFile.util;
|
|
import java.io.File;
|
import java.io.FileNotFoundException;
|
import java.io.FileOutputStream;
|
import java.io.IOException;
|
import java.io.InputStream;
|
import java.io.OutputStream;
|
import java.io.RandomAccessFile;
|
import java.nio.channels.FileChannel;
|
|
import org.apache.logging.log4j.LogManager;
|
import org.apache.logging.log4j.Logger;
|
|
|
public class FileUtil {
|
|
protected static final Logger log = LogManager.getLogger(FileUtil.class.getName()) ;
|
/**
|
* 保存文件
|
* @param fileAbsolutelyPath 文件绝对路径
|
* @param input
|
* @return 保存文件的是否成功的结果
|
*/
|
public boolean saveFile(String fileAbsolutelyPath , InputStream input){
|
boolean success = true ;
|
if(fileAbsolutelyPath == null || input == null){
|
success = false ;
|
}else{
|
OutputStream os = null;
|
try {
|
os = new FileOutputStream(fileAbsolutelyPath);
|
byte[] b = new byte[1024] ;
|
int len = input.read(b) ;
|
while(len > 0){
|
os.write(b, 0, len);
|
len = input.read(b) ;
|
os.flush();
|
}
|
} catch (Exception e) {
|
e.printStackTrace();
|
success = false ;
|
} finally {
|
try {
|
if(os != null){
|
os.close();
|
}
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
}
|
return success ;
|
}
|
/**
|
* 复制文件
|
* @param fromFile
|
* @param realPath 绝对路径
|
* @param newFileRelativityPath 相对路径
|
* @return
|
*/
|
public boolean copyFile(File fromFile, String realPath, String newFileRelativityPath){
|
boolean flag = true ;
|
FileChannel fromChannel = null ;
|
FileChannel toChannel = null ;
|
try {
|
fromChannel = new RandomAccessFile(fromFile, "r").getChannel();
|
toChannel = new RandomAccessFile(new File(realPath + newFileRelativityPath), "rw").getChannel();
|
fromChannel.transferTo(0, fromChannel.size(), toChannel);
|
} catch (FileNotFoundException e) {
|
flag = false ;
|
log.error("复制文件出错:" + e.getMessage()) ;
|
} catch (IOException e) {
|
flag = false ;
|
log.error("复制文件出错:" + e.getMessage()) ;
|
}finally{
|
try{
|
if(fromChannel != null){
|
fromChannel.close() ;
|
}
|
if(toChannel != null){
|
toChannel.close() ;
|
}
|
}catch(Exception e){}finally{}
|
}
|
return flag ;
|
}
|
|
/**
|
* 删除文件
|
* @param f
|
*/
|
public boolean deleteFile(File f){
|
boolean flag = false ;
|
try{
|
if(f != null){
|
flag = f.delete() ;
|
}
|
}catch(Exception e){
|
}finally{}
|
return flag ;
|
}
|
|
/**
|
* 删除文件
|
* @param path
|
*/
|
public boolean deleteFile(String path){
|
boolean flag = false ;
|
try{
|
if(path != null && !path.equals("")){
|
File f = new File(path) ;
|
if(f != null && f.exists()){
|
flag = f.delete() ;
|
}
|
}
|
}catch(Exception e){
|
}finally{}
|
return flag ;
|
}
|
|
}
|