【问题标题】:Scan text file for a string, if found, create new txt file with that string扫描文本文件中的字符串,如果找到,使用该字符串创建新的 txt 文件
【发布时间】:2017-06-07 04:38:24
【问题描述】:

所以我要做的是扫描一个 txt 文件以查找 String,如果找到 String,则需要创建一个新的 txt 文件并将 String 写入其中。 String、待搜索的txt文件的名称和将/可以创建的txt文件都将通过命令行输入。

public class FileOperations {

  public static void main(String[] args) throws FileNotFoundException {
    String searchTerm = args[0];
    String fileName1 = args[1];
    String fileName2 = args[2];
    File file = new File(fileName1);
    Scanner scan = new Scanner(file);

    while (scan.hasNextLine()) {
      if (searchTerm != null) {
        try {
          BufferedWriter bw = null;
          bw = Files.newBufferedWriter(Paths.get(fileName2), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
          bw.write(searchTerm);
          bw.close();
        } catch (IOException ioe) {
          ioe.printStackTrace();
        }


      }
      scan.nextLine();
    }
    scan.close();
  }
}

我试图做的是创建一个 while 循环来扫描原始文本文件中的字符串,如果找到该字符串,则创建一个 txt 文件并将该字符串输入其中。

当前发生的情况是扫描了原始文件(我使用 System.out.println 进行了测试),但是无论 String 是否在原始 txt 文件中或不是。

【问题讨论】:

    标签: java bufferedwriter


    【解决方案1】:

    基本上,您只是以错误的方式使用了扫描仪。你需要这样做:

    String searchTerm = args[0];
    String fileName1 = args[1];
    String fileName2 = args[2];
    File file = new File(fileName1);
    
    Scanner scan = new Scanner(file);
    if (searchTerm != null) { // don't even start if searchTerm is null
        while (scan.hasNextLine()) {
            String scanned = scan.nextLine(); // you need to use scan.nextLine() like this
            if (scanned.contains(searchTerm)) { // check if scanned line contains the string you need
                try {
                    BufferedWriter bw = Files.newBufferedWriter(Paths.get(fileName2));
                    bw.write(searchTerm);
                    bw.close();
                    break; // to stop looping when have already found the string
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    }
    scan.close();
    

    【讨论】:

    • 我实际上在某个时候有String scanned = scan.nextLine();,我一定是在编辑时删除了它而没有意识到它。非常感谢你,这很有效,现在更有意义了!
    猜你喜欢
    • 2013-07-21
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    • 2016-05-14
    • 1970-01-01
    相关资源
    最近更新 更多