java - Unable to rename file -


i trying exercise of deleting lines file not starting particular string. idea copy desired lines temp file, delete original file , rename temp file original file.

my question unable rename file!

tempfile.renameto(new file(file)) 

or

tempfile.renameto(inputfile) 

do not work.

can tell me going wrong? here code:

/**  * intention have method delete (or create  * new file) deleting lines starting particular string. *  */ package com.dr.sort;  import java.io.bufferedreader; import java.io.file; import java.io.filenotfoundexception; import java.io.filereader; import java.io.filewriter; import java.io.ioexception; import java.io.printwriter;  public class removelinesfromfile {      public void removelinesstartswith(string file, string startswith, boolean keeporigfile) {         string line = null;         bufferedreader rd = null;         printwriter wt = null;         file tempfile = null;          try {             // open input file             file inputfile = new file(file);              if (!inputfile.isfile()) {                 system.out.println("error: " + file + " not valid file.");                 return;             }              // create temporary file              tempfile = new file(file + "_output");              //read input file , write tempfile              rd = new bufferedreader(new filereader(inputfile));             wt = new printwriter(new filewriter(tempfile));             while ((line = rd.readline()) != null) {                 if (line.substring(0, startswith.length()).equals(startswith)) {                     wt.println(line);                     wt.flush();                 }              }             rd.close();              if (!keeporigfile) {                  inputfile.delete();                  if (tempfile.renameto(new file(file))) {                     system.out.println("ok");                 } else {                     system.out.println("not ok");                 }             }          }          catch (filenotfoundexception ex) {             ex.printstacktrace();         } catch (ioexception ex) {             ex.printstacktrace();         }          {             if (tempfile != null && tempfile.isfile()) {                 wt.close();             }         }      } } 

i guess need close printwriter before renaming.


Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c++ - Using OpenSSL in a multi-threaded application -

All overlapping substrings matching a java regex -