/**
* @Title: writeFile
* @Description: 写文件
* @param @param srcPath : 源文件路径
* @param @param targetPath : 目标文件路径
* @return void 返回类型
*/
public static void writeFile(String srcPath, String targetPath){
File srcFile = new File(srcPath);
File targetFile = new File(targetPath);
if (!targetFile.exists()){
try {
//targetFile.mkdirs();
targetFile.createNewFile();
} catch (IOException e) {
log.error("CommonMethods.writeFile() error", e);
}
}
FileInputStream fs = null;
FileOutputStream fo = null;
try {
fs = new FileInputStream(srcFile);
fo = new FileOutputStream(targetFile);
byte[] buf = new byte[1024];
int len;
while ((len=fs.read(buf)) != -1){
fo.write(buf, 0, len);
}
log.info("writeFile seccuss.");
} catch (FileNotFoundException e) {
log.error("read file '"+srcPath+"' error.", e);
} catch (IOException e){
log.error("read file '"+srcPath+"' error.", e);
} catch(Exception e){
log.error("occur others exception.", e);
} finally{
closeIOStream(fs, fo);
}
}
/**
* @Title: readFile
* @Description: 读取文件内容
* @param @param path : 文件路径
* @param @return 设定文件
* @return String 返回类型
*/
public static String readFile(String path){
File file = new File(path);
if (!file.exists()){
log.error("the file path '"+path+"' dose not exitst");
return null;
}
StringBuffer buf = new StringBuffer(1024);
byte[] b = new byte[1024];
FileInputStream is = null;
try {
is = new FileInputStream(file);
while ((is.read(b)) != -1){
buf.append(new String(b));
b = new byte[1024];
}
} catch (FileNotFoundException e) {
log.error("the file path '"+path+"' dose not exitst", e);
} catch (IOException e){
log.error("read file error.", e);
} finally{
closeIOStream(is, null);
}
return String.valueOf(buf);
}
/**
* @Title: closeIOStream
* @Description: 释放资源、输入流和输出流
* @param is
* @param os
* @return void
*/
public static void closeIOStream(InputStream is, OutputStream os){
if (null != os){
try {
os.close();
} catch (IOException e) {
log.error("close OutputStream error.", e);
}
}
if (null != is){
try {
is.close();
} catch (IOException e) {
log.error("close InputStream error.", e);
}
}
}
java.io 文件操作
最新推荐文章于 2024-07-18 17:32:08 发布