首先,我想做的是通过 Scanner 返回一个涉及文件文档的值,而不传递给另一个单词。这是我的源代码:
public static void deleteLine() throws IOException{
File mainFile = new File("H:\\EcD\\data.txt");
File tempFile = new File("H:\\EcD\\tempFile");
Scanner input = new Scanner(mainFile);
String lineNumberToDelete = "4";
while(input.hasNextLine()){
if(!input.next().startsWith(lineNumberToDelete))
System.out.println(input.nextLine());
}
input.close();
}
我没有使用任何未声明的变量,所以我认为只写下方法就可以了。实际上我的主要目的是从设计如下的文本字段中删除特定行:
1) Line 1 Code
2) Line 2 Code
3) Line 3 Code
4) Line 4 Code
5) Line 5 Code
最佳答案
改成这样,你的问题就解决了。
public static void deleteLine() throws IOException{
File mainFile = new File("H:\\EcD\\data.txt");
File tempFile = new File("H:\\EcD\\tempFile");
Scanner input = new Scanner(mainFile);
String lineNumberToDelete = "4";
while(input.hasNextLine()){
String line = input.nextLine();
if(!line.startsWith(lineNumberToDelete))
System.out.println(line);
}
input.close();
}
然后将 System.out.println
替换为写入目标文件。
关于Java 扫描文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22237214/