[英]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.