【发布时间】: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