java按行读取txt并形成sql小工具

写这个小文档的目的:线上sql每次导入很烦,然后想做伸手党找一个poi的样例直接读取Excel生成sql的小工具
然而一些jar包版本及其他冲突等,导致不是很契合,因此写了一个不需要任何导入包案例,不智能,但是用来完成sql生成还是尚可,请各位大佬放过~

Tips:Excel复制到记事本和Notepad++时,每列之间有一个table制表的空格,我们正好将其全局所有替换为我们的代替字符eg:#34,然后代码里即可将其split

1
public static void main(String[] args) { 2 3 /** 4 * 这里将Excel中表格数据复制到Notepad++和记事本中都可,记得另存为本地文件时选择utf-8编码 5 * 6 * 会在txt文件相同目录下生成一个和文件名类似的testSql.txt文件 7 */ 8 String readFilePath = "E:/tools/test.txt"; 9 String writeFilePath = readFilePath.substring(0, readFilePath.indexOf(".")) + "Sql.txt"; 10 String templateSql = "INSERT INTO `T66_CN_ENG_TEST` VALUES (NULL, '##1', '##2', '##3', '##4', NOW(), NULL);"; 11 createSql(readFilePath, writeFilePath, templateSql); 12 13 } 14 15 public static void createSql(String readFilePath, String writeFilePath, String templateSql) { 16 File file = new File(readFilePath); 17 InputStreamReader isr = null; 18 BufferedReader reader = null; 19 BufferedWriter out = null; 20 try { 21 System.out.println("读取文件内容start"); 22 isr = new InputStreamReader(new FileInputStream(file), "UTF-8"); 23 reader = new BufferedReader(isr); 24 File writeFile = new File(writeFilePath); 25 writeFile.createNewFile(); 26 out = new BufferedWriter(new FileWriter(writeFile)); 27 28 String tempString = null; 29 int line = 1; 30 31 while ((tempString = reader.readLine()) != null) { 32 33 System.out.println("line " + line + ": " + tempString); 34 35 String initSql = templateSql; 36 String[] values = tempString.split("##"); 37 for (int i = 0; i < values.length; i++) { 38 initSql = initSql.replace("##" + (i + 1), values[i].replaceAll(" ", "")).trim(); 39 } 40 41 // 这里不通用,针对此次需求写的,替换符和txt中替换符可能不等,根据自己需求增量设计吧 42 if (values.length == 3) { 43 initSql = initSql.replace("##4", ""); 44 } 45 46 System.out.println("line " + line + ": " + initSql); 47 System.out.println("-------------------------------------"); 48 out.write(initSql + "\r\n"); 49 50 line++; 51 } 52 } catch (IOException e) { 53 e.printStackTrace(); 54 } finally { 55 if (out != null) { 56 try { 57 out.flush(); // 把缓存区内容压入文件 58 out.close(); 59 out = null; 60 } catch (Exception e1) { 61 e1.printStackTrace(); 62 } 63 } 64 if (reader != null) { 65 try { 66 reader.close(); 67 reader = null; 68 } catch (IOException e2) { 69 e2.printStackTrace(); 70 } 71 } 72 if (isr != null) { 73 try { 74 isr.close(); 75 isr = null; 76 } catch (Exception e3) { 77 e3.printStackTrace(); 78 } 79 } 80 } 81 }

猜你喜欢

转载自www.cnblogs.com/liuye007/p/9338349.html