六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 49|回复: 0

java.io 文件操作

[复制链接]

升级  52%

34

主题

34

主题

34

主题

秀才

Rank: 2

积分
128
 楼主| 发表于 2013-1-15 01:56:34 | 显示全部楼层 |阅读模式
/** * @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);}}}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表