简体   繁体   中英

file delete and rename not working

Here is the code but it does not delete storedIp file and rename tempFile to storedIP. Both file exist

               String host=ipParsing(hostName);
               File tempFile= new File("tempFile.txt");
               File strFile = new File("StoredIp.txt");
        BufferedReader bufferReader = new BufferedReader( new FileReader(strFile));
        BufferedWriter bw = new BufferedWriter(new FileWriter(tempFile));
                String line;
        while ((line = bufferReader.readLine()) != null)   {
             if(host.equals(line))
                        {
                            found=true;
                            line="";
                        }
                            bw.write(line);
                        if(!line.equals(""))
                            bw.newLine();
                  }
       bw.close();
       bufferReader.close();
               strFile.delete();
               tempFile.renameTo(new File ("StoredIP.txt"));

Well, a call to File.delete() does not necessary delete the file. As the JavaDoc says: be sure to check the return value.

Ignoring this (like you did) is a common source of errors.

One occasion where this delete/renameTo easily goes awry, is when the files are in use . A solution seen consists of using an additional lock file. Too complicated for such a simple thing.

Using an embedded database , like java's own Derby, which is not that difficult. The database needs no extra provision. There are good tutorials with simple example code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM