• RSS
  • Twitter
  • FaceBook

Security Forums

Log in

FAQ | Usergroups | Profile | Register | RSS | Posting Guidelines | Recent Posts

Java - File Writer

Users browsing this topic:0 Security Fans, 0 Stealth Security Fans
Registered Security Fans: None
Post new topic   Reply to topic   Printer-friendly version    Networking/Security Forums Index -> Programming and More

View previous topic :: View next topic  
Author Message
Nedzad
Just Arrived
Just Arrived


Joined: 20 Nov 2009
Posts: 1


Offline

PostPosted: Fri May 21, 2010 9:22 pm    Post subject: Java - File Writer Reply with quote

Hi all,
I have a question, how can i change one line in txt file with file writer in java?
I got txt file with for example 10 lines of strings, how can i edit line 5 to write something else.I was looking on Internet for solution, there was something about copy file into another and then return data.Is there other simpler solution?
Thanks in advance.
Back to top
View user's profile Send private message
Groovicus
Trusted SF Member
Trusted SF Member


Joined: 19 May 2004
Posts: 9
Location: Centerville, South Dakota

Offline

PostPosted: Fri May 21, 2010 10:05 pm    Post subject: Reply with quote

You can not arbitrarily pick a line in a file and change it. Capi will probably have a better explanation that I will, but here goes. A file is data written to a disk. There is no guarantee that it will be written to contiguous memory. When you look at a text file, you are looking at the result after all of the pieces have been pulled from memory. Therefore the system has no idea what "line 5" means. At any rate, in order to change something in a file, you need to read the file into memory.

In the case of a text file, all you need to do is read the file line by line and dump it into a String Array. Change the line of text that you want changed, then write everything back to the file, overwriting the previous data. It is pretty simple really.
Back to top
View user's profile Send private message Visit poster's website
capi
SF Senior Mod
SF Senior Mod


Joined: 21 Sep 2003
Posts: 16777097
Location: Portugal

Offline

PostPosted: Sat May 22, 2010 4:55 am    Post subject: Reply with quote

Agh Groovicus, now you forced me to reply! hehe

The problem here is essentially that, in the general case, you can't directly index a file by line number. A file, whether it be text or binary, is a collection of bytes. You can seek to a specific byte inside the file, you can read 10 bytes or overwrite 25 bytes, but you can't say "I want to replace line 7".

The reason for this isn't so much that the file might not be physically written contiguously on the disk (the operating system takes care of that for you). Rather, the reason is that files are indexed by (made out of) bytes, not text lines. Why? Amongst other things, because text lines are not constant in size.

In order to find out where a line ends and the other begins, someone needs to read the text characters from the beginning, looking for the newline sequence. The operating system doesn't do that for you, so you need to do it yourself. Then there's the problem of altering the line: unless you replace it with something with the same exact length in bytes, you will either overwrite part of the next line, or leave old junk behind.

As for doing what you want, you may take several approaches. One way to do it, as Groovicus noted, is to read the whole file first into an array of lines, process the array then write the whole thing to a new file (or replace the old one). Another way would be to take a streamed approach: read one line, process it if necessary, write it to the new file, read another line, process it if necessary, write it to the new file, etc. This is slightly more complex, but it has the added benefit of not having to buffer the entire file in memory, which means you can handle arbitrarily large files (as long as the lines of text aren't arbitrarily large Wink).

Of course, depending on exactly what you want to do, you may be able to take some shortcuts for specific cases. Say you only need to replace a specific sequence with another sequence of the same length. You could treat the file as a stream of characters; read the file from the beginning, counting newlines until you reach the desired line, then look for the offset in that line. The total number of characters you read gives you the offset you need to seek into the file in order to write the replacement sequence.

If you know that all the lines in the file are of a specific length, it's even easier; you don't even need to read the file. You could do the math (number_of_lines * line_length + offset_in_the_desired_line) to find the bytes you need to overwrite. Then just seek to the desired position and write your sequence, overwriting what's already there.
Back to top
View user's profile Send private message
Groovicus
Trusted SF Member
Trusted SF Member


Joined: 19 May 2004
Posts: 9
Location: Centerville, South Dakota

Offline

PostPosted: Sat May 22, 2010 9:09 am    Post subject: Reply with quote

Sorry capi. I know you spent a bit of time on that post. I am not sure that one can accomplish your method with Java though. I have not thought too much about it though, and since it is so easy to do it at a higher level of abstraction, I doubt I will think about it at all. Smile
Back to top
View user's profile Send private message Visit poster's website
capi
SF Senior Mod
SF Senior Mod


Joined: 21 Sep 2003
Posts: 16777097
Location: Portugal

Offline

PostPosted: Sat May 22, 2010 2:08 pm    Post subject: Reply with quote

Groovicus wrote:
Sorry capi. I know you spent a bit of time on that post.

Ah I was only kidding! No worries Smile


Groovicus wrote:
I am not sure that one can accomplish your method with Java though. I have not thought too much about it though, and since it is so easy to do it at a higher level of abstraction, I doubt I will think about it at all. Smile

Oh, which of the methods were you referring to? I suppose you mean the last couple of ones, where you seek into the file, yes? Well, those were meant more as examples of different approaches to specific cases, to open up the realm of possibilities a little bit. My first recommendations were the two more traditional methods (including your own), which would be easier to implement and the only ones that work for the general case.

The file seeking approaches do have a definite advantage in the specific cases they are meant to handle, though. Although they force you to think a bit more in terms of byte streams and positioning, they have the important advantage of being able to process arbitrarily large files in constant time -- that is of course for the last method; the one before it needs to scan until it finds the line to be modified, but you don't need to touch any further lines after that.

In any case I am admittedly not a Java expert (and don't want to be!), but I assume it should let you seek into a specific position of a file -- you can easily do it with Python, for example, which is also very high level (of course that's an unfair comparison, since Python is actually good Razz)
Back to top
View user's profile Send private message
Nedzad
Just Arrived
Just Arrived


Joined: 20 Nov 2009
Posts: 1


Offline

PostPosted: Tue May 25, 2010 12:00 pm    Post subject: Reply with quote

Thanks guys, this was very helpful Very Happy .
The most closer for me solution is to read txt lines into array and process it, cause i dont need large file.
Thanks again.
Back to top
View user's profile Send private message
montaj0211
Just Arrived
Just Arrived


Joined: 03 Mar 2011
Posts: 0


Offline

PostPosted: Fri Mar 11, 2011 12:20 pm    Post subject: Java - File Writer Reply with quote

We can use the class FileWriter and BufferedWriter to write to a file.Just check this code and put changes.Here is the code of java program to write text to a file:
Code:
import java.io.*;
class FileWrite
{
   public static void main(String args[])
  {
      try{
    // Create file
    FileWriter fstream = new FileWriter("out.txt");
        BufferedWriter out = new BufferedWriter(fstream);
    out.write("Hello Java");
    //Close the output stream
    out.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
}
Back to top
View user's profile Send private message
krugger
SF Mod
SF Mod


Joined: 08 Jun 2006
Posts: 16777209


Offline

PostPosted: Fri Mar 11, 2011 12:59 pm    Post subject: Reply with quote

Read this tutorial:
http://www.developer.com/java/other/article.php/1548681/Introduction-to-Memory-Mapped-IO-in-Java.htm

Java also supports mapped IO, just mmap it to memory for inplace editing. Also works for binary files. It uses FileChannel, RandomAccessFile and ByteBuffer.
Back to top
View user's profile Send private message
capi
SF Senior Mod
SF Senior Mod


Joined: 21 Sep 2003
Posts: 16777097
Location: Portugal

Offline

PostPosted: Fri Mar 11, 2011 1:55 pm    Post subject: Reply with quote

Indeed memory-mapped IO is an excellent and easy way to edit a file in-place. The only problem, as with any other kind of inline text editing, is that if you want to edit a single line, you need to make sure the new contents are the same length. Otherwise you'll leave junk at the end of the line, or overwrite the next one.

Or of course, you can just move all the data after the line "to the right" or "to the left", as necessary.
Back to top
View user's profile Send private message
Display posts from previous:   

Post new topic   Reply to topic   Printer-friendly version    Networking/Security Forums Index -> Programming and More All times are GMT + 2 Hours
Page 1 of 1


 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

Looking for more Windows Networking info?

Sign up to the WindowsNetworking.com Monthly Newsletter, written by Enterprise Security MVP Deb Shinder, containing news, the hottest tips, Networking links of the month and much more. Subscribe today and don't miss a thing!
View a sample newsletter.

Become a WindowsNetworking.com member!

Discuss your Windows Networking issues with thousands of other Windows Newtorking experts. Click here to join!

Community Area

Log in | Register

Readers' Choice

Which is your preferred data recovery solution?

Follow TechGenix on Twitter