2017-01-22 68 views
1

所以我想要做的是扫描一个txt文件的String,如果找到String,新的txt文件需要被创建并且String写入它。 String,要搜索的txt文件的名称和将要/可以创建的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文件中,都会创建带有字符串的新文件。

回答

0

基本上,你刚刚用错了方式使用扫描仪。你需要做的,以这种方式:

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(); 
+0

我其实是有'字符串进行扫描= scan.nextLine();'在里面在某些时候,我一定已经删除了它,而编辑没有意识到它。 非常感谢您的支持,并且让您的工作更有意义! –

相关问题