import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class Test { public static void main(String[] args) { readFile(); } /** * 字符串转换 * @param from * @return */ private static String translateStr(String from) { return "truncate table `thc_rcm`."+from+"`;"; } /** * 读入TXT文件 */ public static List<String> readFile() { List<String> list = new ArrayList<>(); int count = 0; Set<String> set = new HashSet<>(); String pathname = "/Users/guchunchao/workspace-sst/Test/src/d.txt"; // 绝对路径或相对路径都可以,写入文件时演示相对路径,读取以上路径的input.txt文件 //防止文件建立或读取失败,用catch捕捉错误并打印,也可以throw; //不关闭文件会导致资源的泄露,读写文件都同理 //Java7的try-with-resources可以优雅关闭文件,异常时自动关闭文件;详细解读https://stackoverflow.com/a/12665271 try (FileReader reader = new FileReader(pathname); BufferedReader br = new BufferedReader(reader) // 建立一个对象,它把文件内容转成计算机能读懂的语言 ) { String line; //网友推荐更加简洁的写法 while ((line = br.readLine()) != null && !line.trim().isEmpty()) { // 一次读入一行数据 // System.out.println(line); // String[] codeValue = line.split(","); // String sql = "insert into `thc_passport`.`city` values('" + codeValue[0] + "','"+ codeValue[1] + "');"; System.out.println(++count + " " +translateStr(line)); // set.add(sql); } } catch (IOException e) { e.printStackTrace(); } finally { } list.addAll(set); return list; } /** * 写入TXT文件 */ public static void writeFile() { BufferedWriter out = null; try { File writeName = new File("/Users/guchunchao/workspace-sst/Test/src/e.txt"); // 相对路径,如果没有则要建立一个新的output.txt文件 writeName.createNewFile(); // 创建新文件,有同名的文件的话直接覆盖 FileWriter writer = new FileWriter(writeName); out = new BufferedWriter(writer); List<String> list = readFile(); for (int i = 0; i < list.size(); i++) { out.write(list.get(i) + " "); // 即为换行 } out.flush(); // 把缓存区内容压入文件 } catch (IOException e) { e.printStackTrace(); try { out.close(); } catch (IOException ex) { ex.printStackTrace(); } } finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }