import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
//写的比较易懂,适合初学者参考
public class adminisDemo {
public static void main(String[] args) throws Exception{
//初始化FileInputStream,确定需要读取的文件地址
FileInputStream is=new FileInputStream("C:\\Users\\admin\\Desktop\\行政区划代码.txt");
//初始化InputStreamReader指定读取编码格式
InputStreamReader isr=new InputStreamReader(is, "UTF-8");
//初始化FileOutputStream,确定需要写入的文件地址
FileOutputStream os=new FileOutputStream("C:\\Users\\admin\\Desktop\\administrative.sql");
//初始化OutputStream指定写入编码格式,保证读取和写入的编码格式一致
OutputStreamWriter osw=new OutputStreamWriter(os,"UTF-8");
//初始化BufferedReader缓冲流
BufferedReader br = new BufferedReader(isr);
//初始化BufferedWriter缓冲流
BufferedWriter bw = new BufferedWriter(osw);
//声明String类型变量str存储读取的数据
String str;
bw.write("create database adminq_db;");
bw.newLine();
bw.write("use adminp_db;");
bw.newLine();
bw.write("create table sys_admin(");
bw.newLine();
bw.write("id int(10) auto_increment comment'主键',");
bw.newLine();
bw.write("codes int(10) comment'行政区划码',");
bw.newLine();
bw.write("name varchar(100)not null comment'行政区名称',");
bw.newLine();
bw.write("primary key(id)");
bw.newLine();
bw.write(");");
bw.newLine();
//循环读取写入
while((str=br.readLine())!=null) {
String sb=str;
//截取0-6位的值
String st = sb.substring(0,6);
//截取6之后的值
String s = sb.substring(6);
//判断后四位的值是否为0000
boolean bl = st.endsWith("0000");
//去除读取文件的空格
String t= s.trim();
//判断后四位的值是否为0000,若为true则将值转换为null写入
if(bl) {
bw.write("insert into sys_admin(codes,name) values("+"null"+","+"'"+t+"'"+");");
//换行写入
bw.newLine();
}else {
bw.write("insert into sys_admin(codes,name) values("+st+","+"'"+t+"'"+");");
bw.newLine();
}
}
System.out.println("文件写入完成");
//关闭流
br.close();
bw.close();
}
}