Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

need simple example of updating a text file

 
Robin Clark
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am reading an input file and updating one line. The way that I am trying is not working. I can read the input file and create the output file correctly, but I can't rename the output file to the input file's name. Here is my code:

When I try to rename the file, it returns a false value. I think there must be a much simpler way to accomplish this task. Can someone help me?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, there are two questions here. First, the easy one: why can't you rename the new file? Because the old one of that name is still there. Delete the old one first (or rename the old, rename the new, then delete the old, to be extra safe) and this should work fine.
Other question: a much simpler way. Basically what you're doing is using users.txt as a flat-file database. The simpler way would be, first, to abstract the whole "flat file database" concept out behind a "UserDatabase" interface with methods like "addUser", "updatePhoneNumber," etc. Then implement this in terms of your flat file, and call it from your servlet.
When everything's working, then you probably want to think about using a real relational database -- at least if the "users" list is more than a few dozen names.
 
Robin Clark
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes! Deleting the file did the trick. After I get this down and dirty prototype working, I am going to clean up the code as you suggest. Right now it is a mess because I am rushing through things that I don't understand properly.
I really appreciate the help.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Something to think about ... how safe do you want this operation to be? Years ago IBM's CMS operating system did something like this when rewriting any existing file:
* write the new file to a temp name, close it
* rename original file to a backup name
* rename the temp file to the original name
* erase the backup file
Think about what is left if you have some kind of failure during any one of these steps. It seems like a lot of work but if your data is critical it may be worth it!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic