因此,我要尝试扫描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文件中,都将创建带有字符串的新文件。
基本上,您只是以错误的方式使用了扫描仪。您需要通过以下方式进行操作:
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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句