[英]Read file, replace string and create a new one with all content
I am trying to replace ?
我要更换
?
with -
in my text document but just the ArrayList<String>
is being written in the new file without all lines of the old one. 在我的文本文档中带有
-
,但是只有ArrayList<String>
被写入新文件,而没有旧文件的所有行。 How can I fix that? 我该如何解决?
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();
}
}
I don't understand why you're storing the lines
in a List
to begin with. 我不明白您为什么要将这些
lines
存储在List
中。 I would perform the transform and print while I read. 我在阅读时会执行转换和打印。 You don't need to test for the presence of the
?
您无需测试是否存在
?
(replace won't alter anything if it isn't present). (如果不存在,则替换不会改变任何内容)。 And, I would also use a
try-with-resources
. 而且,我还将使用
try-with-resources
。 Something like 就像是
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();
}
Examine this code: 检查以下代码:
if (line.contains("?")) {
line = line.replace("?", "-");
lns.add(line);
}
You are only adding the current line (with the replacement) if it had a ? 如果当前行有?,则仅添加当前行(带有替换行)。 in it, ignoring other lines.
在其中,忽略其他行。 Restructure it to always add the existing line.
对其进行重组以始终添加现有行。
if (line.contains("?")) {
line = line.replace("?", "-");
}
lns.add(line);
Additionally, the part 此外,该部分
if (line.contains("?"))
scans line
to look for a ?, and then the code 扫描
line
以查找?,然后执行代码
line.replace("?", "-");
does the same thing, but this time also replacing any ? 做同样的事情,但是这次也替换了吗? with -.
与-。 You may as well scan
line
just once: 你不妨扫描
line
只有一次:
lns.add(line.replace("?", "-"));
Note that creating an ArrayList just to hold the new lines wastes a fair amount of memory if the file is large. 请注意,如果文件很大,创建仅用于容纳新行的ArrayList会浪费大量内存。 A better pattern would be to write each line, modified if necessary, right after you read in the corresponding line.
更好的模式是在阅读相应的行之后立即编写每行,并根据需要进行修改。
Within your while loop you have an if statement checking the line which adds the altered line to the array. 在while循环中,您具有if语句,用于检查将更改后的行添加到数组的行。 You also need to add the unaltered lines to the array.
您还需要将未更改的行添加到数组。
This should fix your issue: 这应该可以解决您的问题:
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);
}
else{
lns.add(line);
}
Previously, you were only adding the line to your ArrayList if it contained a "?" 以前,您仅将行添加到ArrayList中(如果其中包含“?”)。 character.
字符。 You need to add the line to the ArrayList whether or not it contains "?"
您需要将行添加到ArrayList中,无论它是否包含“?”
I would use a different approach if I'm trying to work on the functionality you want to implement, please check this approach and tell me if this helps you :) 如果我尝试使用要实现的功能,我会使用其他方法,请检查此方法并告诉我这是否对您有帮助:)
public void saveReplacedFile() {
//1. Given a file in your system
File file = new File("D:\\hl_sv\\L09MF.txt");
try {
//2. I will read it, not necessarily with Scanner, but use a BufferedReader instead
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
//3. Define a variable that will hold the value of each line
String line = null;
//and also the information of your file
StringBuilder contentHolder = new StringBuilder();
//why not get your line separator based on your O.S?
String lineSeparator = System.getProperty("line.separator");
//4. Check your file line by line
while ((line = bufferedReader.readLine()) != null) {
contentHolder.append(line);
contentHolder.append(lineSeparator);
}
//5. By this point, your contentHolder will contain all the data of your text
//But it is still a StringBuilder type object, why not convert it to a String?
String contentAsString = contentHolder.toString();
//6. Now we can replace your "?" with "-"
String replacedString = contentAsString.replace("?", "-");
//7. Now, let's save it in a new file using BufferedWriter :)
File fileToBeSaved = new File("D:\\hl_sv\\L09MF2.txt");
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileToBeSaved));
bufferedWriter.write(replacedString);
//Done :)
} catch (FileNotFoundException e) {
// Exception thrown if the file does not exist in your system
e.printStackTrace();
} catch (IOException e) {
// Exception thrown due to an issue with IO
e.printStackTrace();
}
}
Hope this is helpful. 希望这会有所帮助。 Happy coding :)
快乐的编码:)
If you can use Java 8 then your code can be simplified to 如果可以使用Java 8,则可以将代码简化为
try (PrintStream ps = new PrintStream("D:\\hl_sv\\L09MF2.txt");
Stream<String> stream = Files.lines(Paths.get("D:\\hl_sv\\L09MF.txt"))) {
stream.map(line -> line.replace('?', '-')).forEach(ps::println);
} catch (IOException e) {
e.printStackTrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.