我想讀的文本文件,然後我放進一個ArrayList,然後再通過ArrayList和「本」與「字代替任何出現* *「。然後我想把這個修改後的ArrayList放回到新編輯的文本中。讀取文件,替換詞,並寫入到一個新文件中的Java
的應用目前讀線到ArrayList中正確寫入新文件的工作。然而,replaceWords方法不會出現預期即,這是不被* *代替將被運行。任何幫助將不勝感激!
package com.assignment2s162305.answers;
import java.io.FileWriter;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
public class Question27 {
private List<String> lines = new ArrayList<String>();
// read original file to an ArrayList
public String[] readOriginalFile(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
// replace words with ****
public void replaceWords() {
Collections.replaceAll(lines, "this", "****");
System.out.println(lines);
}
// write modified ArrayList to a new file
public void writeToNewFile() throws IOException {
FileWriter writer = new FileWriter("output.txt");
for (String str : lines) {
writer.write(str);
}
writer.close();
}
}
package com.assignment2s162305.answers;
import java.io.IOException;
public class Question27Test {
public static void main(String[] args) {
Question27 question27object = new Question27();
String filename = "Hamlet2.txt";
try {
String[] lines = question27object.readOriginalFile(filename);
System.out.println("______ORIGINAL DOCUMENT______\n");
for (String line : lines) {
System.out.println(line);
}
System.out.println("\n\n");
question27object.replaceWords();
question27object.writeToNewFile();
} catch(IOException e) {
// Print out the exception that occurred
System.out.println("Unable to create "+filename+": "+e.getMessage());
}
}
}
謝謝這個固定。現在我讀了你的修復程序,我可以看到我要去哪裏錯了。 – kyussmondo