常用IO方法


public class FileUtil {

static Logger log = Logger.getLogger(FileUtil.class);

public static String readFile(InputStream is) throws IOException{

if(is==null) return null;

BufferedReader reader = new BufferedReader(new InputStreamReader(is));

String tmp = "";
String result = "";

try {
while((tmp = reader.readLine()) !=null)
if(tmp.length() > 0)
result = result + tmp.trim();
}
catch (IOException e) {
throw e;
}
finally {
reader.close();
}

return result;
}

public static String readFile(String path) throws IOException{

InputStream is = null;

try {
is = new FileInputStream(path);
return readFile(is);
}
catch (IOException e) {
throw e;
}
finally {
is.close();
}

}

public static boolean removeFile(String path){

return removeFile(path, true);

}

public static boolean removeFile(String filePath, boolean removeParent){

boolean isdelete = false;
File file = new File(filePath);
if(file.exists()){
isdelete = file.delete();

if(removeParent){
File parent = file.getParentFile();
if(parent!=null){
if(parent.listFiles()==null || parent.listFiles().length==0){
removeFile(parent.getPath(), removeParent);
}
}
}
}
return isdelete;

}

public static void writeFile(String path, String content) throws IOException{

File file = new File(path);
FileWriter fw = null;
try {
fw = new FileWriter(file, true);
fw.write(content);
fw.flush();
}
catch (IOException e) {
throw e;
}
finally{
fw.close();
}

}

public static boolean copyFile(String filePath, String backupPath) throws IOException{

BufferedInputStream reader = null;
PrintStream out = null;

File file = new File(filePath);
if(file.exists()){

try {
reader = new BufferedInputStream(new FileInputStream(file));

String directory = backupPath.substring(0, backupPath.lastIndexOf("/") + 1);

File tempfile = new File(directory);
if(!tempfile.exists()){
tempfile.mkdirs();
}

File backupFile = new File(backupPath);
out = new PrintStream(new BufferedOutputStream(new FileOutputStream(backupFile)));

byte[] b = new byte[2048];

while((reader.read(b, 0, b.length))!=-1){
out.write(b);
}
out.flush();
}
catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
catch (IOException e) {
e.printStackTrace();
return false;
}
finally {
reader.close();
out.close();
}

} else {
log.error("文件" + filePath + "在当前路径下不存在!");
return false;
}
return true;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值