[英]Read file, replace string and create a new one with all content
我要更换?
在我的文本文档中带有-
,但是只有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();
}
}
我不明白您为什么要将这些lines
存储在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();
}
检查以下代码:
if (line.contains("?")) {
line = line.replace("?", "-");
lns.add(line);
}
如果当前行有?,则仅添加当前行(带有替换行)。 在其中,忽略其他行。 对其进行重组以始终添加现有行。
if (line.contains("?")) {
line = line.replace("?", "-");
}
lns.add(line);
此外,该部分
if (line.contains("?"))
扫描line
以查找?,然后执行代码
line.replace("?", "-");
做同样的事情,但是这次也替换了吗? 与-。 你不妨扫描line
只有一次:
lns.add(line.replace("?", "-"));
请注意,如果文件很大,创建仅用于容纳新行的ArrayList会浪费大量内存。 更好的模式是在阅读相应的行之后立即编写每行,并根据需要进行修改。
在while循环中,您具有if语句,用于检查将更改后的行添加到数组的行。 您还需要将未更改的行添加到数组。
这应该可以解决您的问题:
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);
}
以前,您仅将行添加到ArrayList中(如果其中包含“?”)。 字符。 您需要将行添加到ArrayList中,无论它是否包含“?”
如果我尝试使用要实现的功能,我会使用其他方法,请检查此方法并告诉我这是否对您有帮助:)
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();
}
}
希望这会有所帮助。 快乐的编码:)
如果可以使用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.