所以我要做的是扫描一个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文件中,都会创建带有字符串的新文件 .
1 回答
基本上,你刚刚以错误的方式使用扫描仪 . 你需要这样做: