Results 1 to 3 of 3
  1. #1
    Ionos is offline Member
    Join Date
    Jun 2013
    Rep Power

    Default Read/Write from specific line

    Hello guys!I have a question for the read and write method in file.
    In my code for writing i m using PrintWriter and for reading Scanner.
    So i m saving data to file and when is need it i m reading from the file.
    but i also have to delete specific data from it.

    Is there a way to delete a specific line from the file?
    When i google my problem i found that is better to save your data to temporary
    file and then to the final.Why this method is better?


  2. #2
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    The Netherlands
    Rep Power

    Default Re: Read/Write from specific line

    You can use a LineNumberReader. That will tell you the line number that you're on. Or you can count them manually. Or you can parse the line looking for something specific. All depends on the criteria of which line is to be found.

    To delete a line you would have to write all the other lines to a temp file and move that back to the original file. You can't modify a file while you're reading it.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  3. #3
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Tucson, AZ
    Rep Power

    Default Re: Read/Write from specific line

    To read a specific line, if the lines are all the same length, you can use simple arithmetic to seek directly to the line you want. If they're different lengths, you have to either maintain an index or start at the beginning and count lines to find the one you want.

    To delete a line, you have to rewrite the file starting from that line. The reason for saving to a temporary file is that if something goes wrong during the write, your original file is still intact. If you write the temp file, delete the original, and then rename the temp file to the original, a valid version of your file exists on disk at every step.
    Get in the habit of using standard Java naming conventions!

Similar Threads

  1. How to read a specific line and word in a txt file?
    By MjM8082 in forum New To Java
    Replies: 1
    Last Post: 09-07-2012, 07:10 AM
  2. Read a specific line or a .txt
    By skaterboy987 in forum New To Java
    Replies: 2
    Last Post: 10-18-2011, 02:04 AM
  3. Replies: 3
    Last Post: 06-26-2011, 11:00 AM
  4. Write to a specific line in a file
    By phantom06 in forum New To Java
    Replies: 1
    Last Post: 02-05-2011, 06:32 PM
  5. read a specific line in an input file
    By sara12345 in forum Advanced Java
    Replies: 7
    Last Post: 01-03-2010, 10:40 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts