以文件恢复为例
1.首先定义一个文件恢复的方法restore,传入的参数为String类型的文件路径filePath
public static void restore(String filePath) {}
2.创建要恢复的文件对象
File sqlFile = new File(filePath);
3.声明所需要的对象
Statement stmt = null;
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();
int count = stmt.executeUpdate(readStr);
stmt.close();
}
}
最后需要倒序关闭所有的IO流
finally {
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;
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();
int count = stmt.executeUpdate(readStr);
stmt.close();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
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();
}
}
}
}