请参阅下面的代码:我可以在文件的一行中编写一个键和一个字符串。如果密钥已经存在,我想通过创建一个新文件来覆盖它,并用我的源文件的内容填充它。最后,我将删除旧文件并重命名我的临时文件。但它不起作用。如您所见,我打印用于删除和重命名方法的布尔值。两者都返回为“false”。
我在其他一些线程中读到,我必须关闭所有与我的文件接触的读者和作家才能重命名或删除它。
你看出我的错了吗?
(请注意,有些评论是用德语写的)
public static boolean dini_Set(String filepath, String key, String value) throws IOException
{
if(key.length() <= 0 || value.length() <= 0) return false;
String pfilepath = rootdirectory.concat(filepath);
File pfile = new File(pfilepath);
//dini_Remove(filepath.concat(".part"));
if(dini_Exists(filepath) == false) return false;
// Checkt ob der Key schon existiert
FileReader fr = new FileReader(pfilepath);
BufferedReader br = new BufferedReader(fr);
String ausw;
boolean foundkeybool = false;
while((ausw = br.readLine()) != null)
{
String foundkey = ausw.substring(0,ausw.indexOf("="));
//System.out.println(foundkey);
if(foundkey.equals(key))
{
foundkeybool = true;
System.out.println(foundkeybool);
// Key exists and content has to be overwritten
String newline = key.concat("=").concat(value);
String tmpdir = rootdirectory.concat("tmp.tmp");
File tmp = new File(tmpdir);
tmp.createNewFile();
String currentLine;
FileWriter fw = new FileWriter(tmpdir);
BufferedWriter bw = new BufferedWriter(fw);
br.close();
fr.close();
fr = new FileReader(pfilepath);
br = new BufferedReader(fr);
while((currentLine = br.readLine()) != null)
{
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
System.out.println(trimmedLine);
if(trimmedLine.equals(ausw))
{
System.out.println("Austauschen: "+newline);
bw.write(newline);
}
else
{
bw.write(currentLine);
System.out.println("Lassen: "+currentLine);
}
bw.newLine();
}
br.close();
fr.close();
bw.close();
fw.close();
tmp.setWritable(true);
pfile.setWritable(true);
// boolean removed = dini_Remove(filepath);
boolean removed = pfile.delete();
System.out.println("Datei wurde gelöscht: "+removed);
boolean renamed = tmp.renameTo(pfile);
System.out.println("Datei umbenannt: "+renamed);
break;
}
}
// if key does now exists we can create a new one
if(foundkeybool == false)
{
FileWriter fw = new FileWriter(pfilepath,true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(key.concat("=").concat(value));
bw.newLine();
bw.close();
}
return true;
}