Java利用IO流写入文件

以文件恢复为例

1.首先定义一个文件恢复的方法restore,传入的参数为String类型的文件路径filePath

public static void restore(String filePath) {}

2.创建要恢复的文件对象

File sqlFile = new File(filePath);//创建备份文件对象

3.声明所需要的对象

Statement stmt = null;// sql语句直接接口
		FileInputStream fis = null;// 文件输入字节流
		InputStreamReader isr = null;// 字节流转为字符流
		BufferedReader br = null;// 缓存输入字符流

4.关键代码

fis = new FileInputStream(sqlFile);
		isr = new InputStreamReader(fis);
		br = new BufferedReader(isr);
		String readStr = null;// 缓冲字符串,保存备份文件中一行的内容
			while ((readStr = br.readLine()) != null) {// 逐行读取备份文件中的内容
				if (!"".equals(readStr.trim())) {// 如果读取的内容不为空
					stmt = conn.createStatement();// 创建sql语句直接接口
					int count = stmt.executeUpdate(readStr);// 执行sql语句
					stmt.close();// 关闭接口
				}
			}

最后需要倒序关闭所有的IO流

finally {
		// 倒序依次关闭所有IO流
		if (br != null) {
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (isr != null) {
			try {
				isr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (fis != null) {
			try {
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

完整的代码

//数据恢复
	public static void restore(String filePath) {
		File sqlFile = new File(filePath);//创建备份文件对象
		Statement stmt = null;//sql语句接口
		FileInputStream fis = null;//文件输入字节流
		InputStreamReader isr = null;//字节流转成字符流
		BufferedReader br = null;//缓存输入字符流
		try {
			fis = new FileInputStream(sqlFile);
			isr = new InputStreamReader(fis);
			br = new BufferedReader(isr);
			String readStr = null;//缓存字符串,保存备份文件中的一行内容
			while ((readStr = br.readLine()) != null) {//逐行读取备份文件中的内容
				if (!"".equals(readStr.trim())) {//如果读取的内容不为空
					stmt = conn.createStatement();//创建sql语句执行的接口
					int count = stmt.executeUpdate(readStr);//执行sql语句
					stmt.close();//关闭接口
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			//倒序依次关闭所有IO流
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (isr != null) {
				try {
					isr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值