package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class readsql {
public static void main(String[] args) {
String readpath ="c:/readme.sql";//读取文件路劲
String writepath="c:/write.sql";//写入文件路径
StringBuffer
content=readTxtFile(readpath);//提取readme.sql文件内容提取含有insert语句
返回在content中
writeTxtFile(writepath,content.toString());//将content内容写入write.sql文件中
}
// 读取文件
public static StringBuffer readTxtFile(String readpath)
{
StringBuffer sb = new StringBuffer() ;
try {
String encoding = "GBK";
File file = new File(readpath);
if (file.isFile() && file.exists()) { //
判断文件是否存在
InputStreamReader read = new InputStreamReader(new
FileInputStream(file), encoding);// 考虑到编码格式
BufferedReader bufferedReader = new
BufferedReader(read);
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null) {
String lineTxtnew=lineTxt+"\\r\\n";
if (lineTxtnew.length()>=11 && "insert
into".equals(lineTxtnew.substring(0, 11))) {
sb = sb.append(lineTxt).append("\n\r");
}
}
read.close();
System.out.println("Read successfully");
} else {
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
return sb;
}
//写入文件
public static void writeTxtFile(String writepath,String
content){
File file = new File(writepath);
try (FileOutputStream fop = new
FileOutputStream(file)) {
if (!file.exists()) {
file.createNewFile();
}
byte[] contentInBytes =
content.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
System.out.println("Write
successfully");
} catch (IOException e) {
e.printStackTrace();
}
}
}