Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Deleting a line from a file  RSS feed

 
Shyam Prasad Murarka
Ranch Hand
Posts: 209
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Readers,
How do I delete a line from a file? I tried this:


  • Copied the original file to a temp file skipping out the unwanted line
  • Then deleting the original file
  • Renaming the temp file to original file

  • But since the original file has another refernce outside the method it is not being deleted. i think i am not being able to explain I'll write the code:



    And the original file has a reference outside the method so its not being deleted which is causing problems. Actually i myself don't know what is wrong and so am guessing the errors.
     
    Avi Abrami
    Ranch Hand
    Posts: 1141
    1
    Java Oracle
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Shyam,
    A suggestion. Don't send the "File" object, send the name of the file (as a "String") instead. In other words, change your method to:

    And in the body of the method create a "File" object using the supplied name. That way there will be no external references to the "File", so when the method finishes executing, the file should be deleted (I hope!)

    Good Luck,
    Avi.
     
    Shyam Prasad Murarka
    Ranch Hand
    Posts: 209
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Dear Avi,
    Thanks for your suggestion but I found that something else was wrong. I used to open a stream on that file (somewhere else in the program) BUT never closed it. That's why those files were not deleted.
     
    It is sorta covered in the JavaRanch Style Guide.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!