java.io 文件操作

/**
	 * @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);
			}
		}
	} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值