生成大量插入语句,并将语句写入txt文件中


import java.io.*;

/**
 * Created by czz on 2019/9/23.
 */
public class TTest {
    /**
     * 生成大量插入语句,并将语句写入txt文件中
     * 本例为生成一千条以上的ip地址数据插入数据库
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception{
        String filename = "c:"+File.separator+"e.txt";
        File file = new File(filename);
        StringBuilder sb = new StringBuilder();
        for (int i=2;i<255;i++){
            String ip = "192.168.52."+i;
            String str = "insert into iptable (nicname,ip,ip,mask) values ('test','"+ip+"','255.255.255.0');
";
            sb.append(str);
        }

        for (int i=2;i<255;i++){
            String ip = "192.168.53."+i;
            String str = "insert into iptable (nicname,ip,mask) values ('test','"+ip+"','255.255.255.0');
";
            sb.append(str);
        }

        for (int i=2;i<255;i++){
            String ip = "192.168.54."+i;
            String str = "insert into iptable (nicname,ip,mask) values ('test','"+ip+"','255.255.255.0');
";
            sb.append(str);
        }

        for (int i=2;i<255;i++){
            String ip = "192.168.55."+i;
            String str = "insert into iptable (nicname,ip,mask) values ('test','"+ip+"','255.255.255.0');
";
            sb.append(str);
        }

        String ss = sb.toString();
        System.out.println(ss);
        byte[] b = ss.getBytes();  //将字符串转换成字节数
        OutputStream out = null;![](https://img2018.cnblogs.com/blog/1480523/201910/1480523-20191016181410606-1043685942.png)


        try {
            out = new FileOutputStream(file);  //实例化OutpurStream
            out.write(b);    //写入
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            if (out != null){
                try {
                    out.close();    //关闭
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}

大家有兴趣也可以关注我的公众号查看文章。

原文地址:https://www.cnblogs.com/caozz/p/createText.html