今天,我正在制作一个关于BufferedReader的程序。该程序是使用BufferedReader替换一行。但是当我运行该程序时,它崩溃没有任何错误或异常。我很困惑。这是我的代码:
import java.io.*;
import java.util.*;
public class FileReplace {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String path = "/w2.txt";
Scanner input = new Scanner(System.in);
File file = new File(path);
if(file.exists()) {
System.out.println("This file is valid.");
System.out.println("REPLACE WHAT?");
String OriText = input.nextLine();
FileReader filepath = new FileReader(path);
BufferedReader fileword = new BufferedReader(filepath);
String[] keyW = new String[4];
for (int i = 0; i<4; i++) {
keyW[i] = fileword.readLine();
System.out.println(keyW[i]);
}
if(isExist(OriText,keyW)) {
System.out.println("Found! REPLACE WITH WHAT?");
String Inputword = input.nextLine();
try(PrintWriter out = new PrintWriter(path);){
for(int i = 0; i<keyW.length; i++) {
String textto = replaceWord(keyW, OriText, Inputword)[i];
out.println(textto);
}
System.out.print("REPLACED!");
}
}
}else {
System.out.println("This file is invalid.");
System.exit(1);
}
input.close();
}
public static boolean isExist(String a, String[] keyW) {
boolean status = false;
for(int i = 0; i<keyW.length; i++) {
if(keyW[i]==a) {
status = true;
}
}
return status;
}
public static String[] replaceWord(String[] keyW, String a,String b) {
int index = 0;
for(int i = 0; i<keyW.length; i++) {
if(keyW[i] == a) {
index = i;
}
}
keyW[index] = b;
return keyW;
}
}
这是文件:
w2.txt
hello
Die Frau
HelloWorld
Beginnen
当我运行程序时,结果是
This file is valid.
REPLACE WHAT?
hello
hello
Die Frau
HelloWorld
Beginnen
我无法进入下一步。有人可以帮我解决这个问题吗?不管怎样,谢谢。