• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

how to insert a new line into a file using buffered writer?

 
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi, i am trying to write a program which stores names of people along with some of their details(like dob,phone number,address etc...) into a file..
a user is also allowed to remove an existing contact in a file..

the format i am using to store a single contact into the file is:

name=dob:petName:email:address

now when the user wants to remove a contact he enters the name to be removed..what i have tried to do is...
1>read the lines of the file one by one.
2>split the line at "=" using
.
now name is stored in parts[0]
3>check if name matches name to be removed.
4>if no match,append that line to a string(which will be written back to the file) else dont append that line.
5>continue until end of file.
6>now write back the string without the unwanted contact back into the file.
i have posted only a relevant part of the problem here:

suppose that file contents are as given below :

(file name:aa.txt)


i am trying to remove only the contact of the person named raju in the code below:





This part below is where i check if the contact is the one which is to be removed.if it is not to be removed,append it to the line that will be written back into the file at the end.


but in place of the new line character(\n),small rectangles(some junk) are getting printed out..how do i put the contacts in separate lines here?
 
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The \n is not a universal line separator. Use System.getProperty("line.separator"); instead.
 
sinatra roger
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Steve Luke wrote:The \n is not a universal line separator. Use System.getProperty("line.separator"); instead.


thanks...
 
Marshal
Posts: 74709
335
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There is a method in BufferedWriter which appends a new line to the file, using the system‑specific line terminator. It is obvious when you read the method names.
 
Steve Luke
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:There is a method in BufferedWriter which appends a new line to the file, using the system‑specific line terminator. It is obvious when you read the method names.



True, but the OP is building the entire output in memory first, then sending through the writer at once. I guess a better option would be to read a line, check if it should be saved, write the line. It would be more memory efficient.
 
Campbell Ritchie
Marshal
Posts: 74709
335
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It is better to use a StringBuilder than + on Strings inside a loop. You can append the line end String, which you get as you told OP the other day.
 
Rancher
Posts: 4067
56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:It is better to use a StringBuilder than + on Strings inside a loop. You can append the line end String, which you get as you told OP the other day.


If you're building up a single String at all, then yes, using a StringBuilder is the way to do it, far better than using + in a loop like that. But Steve just made what is probably an even better suggestion, writing to file as you go (presumably mediated by the BufferedWriter). That way if the file is really big, you never need to store the whole thing in memory at once.
 
Mike Simmons
Rancher
Posts: 4067
56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Also, you can use a PrintWriter rather than BufferedWriter (or, a PrintWriter wrapped around a BufferedWriter), and println() will automatically append the correct system-specific line separator.
 
sinatra roger
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:
There is a method in BufferedWriter which appends a new line to the file, using the system‑specific line terminator. It is obvious when you read the method names.



BufferedWriter.newLine() is the method mentioned here i guess..but what i am trying to do is read the entire contents of a file into memory(a single string which stores all lines of a file..the lines are separated by a line separator)..then write back this string back into the same file from which data was read. So i guess BufferedWriter.newLine() would not be possible here.


True, but the OP is building the entire output in memory first, then sending through the writer at once. I guess a better option would be to read a line, check if it should be saved, write the line. It would be more memory efficient.


Is there any possible way to do this? Because i am reading contents from a file and writing back into the same file..

Once a buffered writer to a file is declared, the contents of the file would be cleared right? Then how would it be possible to read the contents of the file?
So i first read all the useful contents of the file into memory then create a BufferedWriter to write into the file, which will automatically clear all contents of the file,
then writ the contents into the file


The steps to write into the file as soon as a line is read would be:

1 > Read a line from the file.

2> Check if the line is to be written back into the file.

3> if the line is to be discarded, ignore the line(dont write back into the file)

4> if the line is to be written back, use a writer to write into the file :

but this step would require the use of a BufferedWriter as below :

BufferedWriter writer = new BufferedWriter(new FileWriter("aa.txt"));

After this the entire contents of the file would be cleared.

Then the lines not yet read would be lost.

Even appending the lines back into the file(BufferedWriter writer = new BufferedWriter(new FileWriter("aa.txt",true));) would not be possible as lines would then be repeatedly written back into the file...


So is there any other technique where I can write back into the same file without clearing the contents yet to be read?

If so please give me some details about it..

Im yet to learn about the StringBuilder..I will try to use it as soon as I study it.
 
Steve Luke
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
My strategy would probably be to read from one file, write to a temp file. Then when done, delete the original and move the temp file to the same path (and name) as the original.
 
sinatra roger
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Steve Luke wrote:My strategy would probably be to read from one file, write to a temp file. Then when done, delete the original and move the temp file to the same path (and name) as the original.


Would that be more efficient than reading and writing from a variable?

I had this idea in mind..but opted not to implement in this manner for reasons some experienced guys told me..i don't fully understand them but thought it would be better to follow the advice.

What they told me was that creating new files always depended on permissions or something of that sort..and also how files can be modified by second party..
 
Campbell Ritchie
Marshal
Posts: 74709
335
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you suffer such permission problems, and cannot create a file, you will suffer a FileNotFoundException, which you must handle (it is “checked”). You can put your file‑copying method call inside a loop, and handle the Exception by trying a different location for your file.
On the other hand, you said you were going to write a file; that suggests to me you have read‑and‑write permission in that folder already.
 
sinatra roger
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:If you suffer such permission problems, and cannot create a file, you will suffer a FileNotFoundException, which you must handle (it is “checked”). You can put your file‑copying method call inside a loop, and handle the Exception by trying a different location for your file.
On the other hand, you said you were going to write a file; that suggests to me you have read‑and‑write permission in that folder already.



Is the temp file method as suggested earlier a better practice compared to reading and writing data from the variable as done in the code above?

 
Campbell Ritchie
Marshal
Posts: 74709
335
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Don’t know. I think the temp file idea is a good one, however.
 
Mike Simmons
Rancher
Posts: 4067
56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I would say the temp file strategy is generally better - it definitely uses less memory, and probably gets the result completed faster. And it's probably more resilient if something goes wrong. For example, what happens if there's a hardware problem sometime during this process? Or if the power goes out, or someone hits ctrl-C or kill -9 to kill your process? With the original strategy, there's a period of time where you have started overwriting the old file, but have not finished writing the new copy of the file. If you lose power here, then when you restart, you have a half-written file, and no copy of the original data. You may have lost important data as a result. With the temp file, you always have a backup copy of the original - up until the very end, when you delete the original. If you lose power right after that, then at least you have a complete copy of the modified data - it just has the wrong file name. That's pretty easy to recover from, just rename the file manually.

These same arguments apply if there's a file permissions problem. If you find you don't have permission to do what you need to do, well, that's unfortunate - but at least you still have the original data. You can then go and fix the permissions problem and re-run. All better now.
 
Mike Simmons
Rancher
Posts: 4067
56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:If you suffer such permission problems, and cannot create a file, you will suffer a FileNotFoundException


Often it would be an IOException rather than FileNotFoundException. But the rest of the post still applies.
 
sinatra roger
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks for all the tips...
 
Campbell Ritchie
Marshal
Posts: 74709
335
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You’re welcome
 
reply
    Bookmark Topic Watch Topic
  • New Topic