gpt4 book ai didi

java - 读取文件,替换字符串并创建一个包含所有内容的新文件

转载 作者:行者123 更新时间:2023-11-30 07:00:23 34 4
gpt4 key购买 nike

我正在尝试替换 ?-在我的文本文档中,但只有 ArrayList<String>正在写入新文件,没有旧文件的所有行。我该如何解决?

File file = new File("D:\\hl_sv\\L09MF.txt");

ArrayList<String> lns = new ArrayList<String>();
Scanner scanner;
try {

scanner = new Scanner(file);

int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
if (line.contains("?")) {
line = line.replace("?", "-");
lns.add(line);

// System.out.println("I found it on line " + lineNum);
}
}
lines.clear();
lines = lns;
System.out.println("Test: " + lines);

FileWriter writer;
try {
writer = new FileWriter("D:\\hl_sv\\L09MF2.txt");
for (String str : lines) {
writer.write(str);
}

writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

最佳答案

我不明白为什么要将 存储在 List 中。我会在阅读时执行转换和打印。您不需要测试 ? 是否存在(如果不存在,替换不会改变任何内容)。而且,我还会使用 try-with-resources .有点像

File file = new File("D:\\hl_sv\\L09MF.txt");
try (PrintWriter writer = new PrintWriter("D:\\hl_sv\\L09MF2.txt");
Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
writer.println(line.replace('?', '-'));
}
} catch (Exception e) {
e.printStackTrace();
}

关于java - 读取文件,替换字符串并创建一个包含所有内容的新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30631828/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com