我有一个文本文件,其格式如下:
ab
cd
ef
gh
ij
..
我想在“ef”之后删除字符串,我的意思是在运行我的程序后,文本文件结构如下:
ab
cd
ef
我正在使用netbeans IDE并使用java代码。有人可以帮忙吗? 这是我尝试过的代码,但它只是在字符串中将字符串保留在“ef”之前,但我不知道如何做其他代码!
BufferedReader br = new BufferedReader(new FileReader("E:\\info.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (!(line.equals("ef"))) {
sb.append(line);
// sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
System.out.print(everything);
// System.out.print(sb);
} finally {
br.close();
}
答案 0 :(得分:0)
以下是更正文件的示例
final String fileName = "E:\\info.txt";
String everything = "";
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (!(line.equals("ef"))) {
sb.append(line).append("\n");
// sb.append(System.lineSeparator());
line = br.readLine();
}
sb.append(line);
everything = sb.toString();
System.out.print(everything);
}
final File file = new File(fileName);
file.delete();
try (FileWriter writer = new FileWriter(fileName)) {
writer.write(everything);
}
答案 1 :(得分:0)
您可以像以下示例中一样使用Apache commons-io FileUtils:
private final String FILE_NAME = "E:\\info.txt";
public void test() throws IOException {
File file = new File(FILE_NAME);
List<String> strings = FileUtils.readLines(file);
int ef = strings.indexOf("ef");
List<String> stringBeforeEF = strings.subList(0, ef);
FileUtils.writeLines(file, stringBeforeEF);
}