我想用我的 java 程序读取同一文件夹中的文本文件。我有一个 readFile() 用于逐行读取文件的内容。然后 setName() 将替换部分内容。我编译程序并运行没有错误。但是文件的内容根本没有改变。
谢谢
public StringBuffer readFile(){ //read file line by line
URL url = getClass().getResource("test.txt");
File f = new File(url.getPath());
StringBuffer sb = new StringBuffer();
String textinLine;
try {
FileInputStream fs = new FileInputStream(f);
InputStreamReader in = new InputStreamReader(fs);
BufferedReader br = new BufferedReader(in);
while (true){
textinLine = br.readLine();
if (textinLine == null) break;
sb.append(textinLine);
}
fs.close();
in.close();
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb;
}
public void setName(String newName){
StringBuffer sb = readFile();
int pos = sb.indexOf("UserName=");
sb.replace(pos, pos+newName.length(), newName);
}