Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Reading and writing to a text file at particular position

Posted on 2011-03-18
11
704 Views
Last Modified: 2012-05-11
I have a text file and I want to read and write a particular string at a specific position in the file.Like for example after " class:" word I want to write "AAA" in the next line.How can I do it using Java.
0
Comment
Question by:vgsrikanth
  • 5
  • 4
  • 2
11 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 35166843

Judging by discussions below it looks like there is no good way to do it,
you want probably re-write the whole stuff  to a new file insert a line at some point
and then  delete the old one and rename the new one to the old name

http://stackoverflow.com/questions/289965/inserting-text-into-an-existing-file-via-java

http://www.javaprogrammingforums.com/file-i-o-other-i-o-streams/5953-write-ascii-specific-position-file.html
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35166873
If you want to replace the stuff (not insert) you probably can manage to do something with RandomAccessFile,
though that should be done with great care. I'd rather re-write
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35166890


This example shows a lot of manipulations with RandomAccessFiles:
http://download.oracle.com/javase/tutorial/essential/io/rafs.html
0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

Author Comment

by:vgsrikanth
ID: 35166932
If you dont mind, can you please give me a piece of code on how to go about
0
 

Author Comment

by:vgsrikanth
ID: 35166960
I am reading the file and when I come across "class:" line I have to append a line of text like "AAA" in the next line of "class:".I dont want to write to a new file but want to read a existing file and make modifications to it.Can you please give me the code in Java.Thank you in advance.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35167084
I don't think you can append some stuff to the existing file in the middle of it - you'll have to re-write it.
File does not have empty spaces in there, so if you add some bytes to a line,
then you'll overwrite the following bytes. At most, you can replace some bytes, but you cannot add in the middle
of the file. Well, let's say, I never did it, and don't know how to do it.
 
0
 
LVL 7

Expert Comment

by:rodness
ID: 35167353
You cannot do this in Java, or any programming language.

A text file is simply a sequence of character bytes.  You CANNOT INSERT new characters at a specific point in the file WITHOUT OVERWRITING data after that point.

Even manipulation with RandomAccessFile is not going to do what you want, because it is only capable of writing data at a particular location of the file, but this DOES NOT INSERT data, it only overwrites the file data.

The only workable solution is to read in the file and write it back out again, modifying (changing/inserting/deleting) what you want to modify at the appropriate points in the file.
0
 

Author Comment

by:vgsrikanth
ID: 35167575
Can someone give me the code in Java on how to read the file, store it in say byte array and checking the byte array for the string "class:" adding the new text "AAA" in the next line of "class:" and writing on to a new file.Thank you for your help.
0
 
LVL 7

Accepted Solution

by:
rodness earned 500 total points
ID: 35167746
The problem with doing this is that unless your file is guaranteed small enough to fit into available memory, you cannot assume that this will work.  THIS IS NOT A GOOD GENERAL SOLUTION.


With that said...


% more filename.txt
Blah blah blah...
Class:
blah blah blah.

% more Foo.java
import java.io.*;

class Foo {
        public static void main(String[] args) throws Exception {
                // find the file length, create the appropriate byte array
                File file = new File( "filename.txt" );
                byte[] bytes = new byte[ (int) file.length() ];
                
                // read the file into the byte array.
                FileInputStream fis = new FileInputStream( file );
                fis.read( bytes );
                fis.close();
                
                // put the file contents into a StringBuilder
                StringBuilder sb = new StringBuilder( new String( bytes ) );
                
                // find the location of the line to insert after, plus
                // the length of the line itself.
                String token = "Class:";
                int offset = sb.indexOf( token ) + token.length();
                
                // insert what you want to insert at this point:
                sb.insert( offset, "AAA" );
                
                // write it out to the same file.
                FileOutputStream fos = new FileOutputStream( file );
                fos.write( sb.toString().getBytes() );
                fos.close();
        }
}
% javac Foo.java
% java Foo
% more filename.txt
Blah blah blah...
Class:AAA
blah blah blah.

Open in new window


Note I have not bothered with error checking.  This is just an example.


Foo.java
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35167790
What would be still normal and sufficiently general solution is to do obvious
thing - open your file, open another empty file, read your file line by line,
write to the new file line by line
once you see "class" add "AAA" and then write this modified  line or additional line if you need
and then continue re-writing up to the end.
There is nothing better than the good old straightforward way...
0
 

Author Comment

by:vgsrikanth
ID: 35167986
Thank you all for sharing your thoughts and rodness for your code.It is working.
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
difference of if loops 23 62
login jsp example 24 65
Error in @AspectJ Based AOP with Spring 2 18
Java: The Public Class Main 4 32
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
The viewer will learn how to implement Singleton Design Pattern in Java.

856 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question