How to inset text between a text file using random access file.

1 view
Skip to first unread message

Praveen

unread,
Jun 17, 2009, 5:00:54 AM6/17/09
to Technical Discussion
My need is to insert (it should not over write the text after the
pointer position) some text after a specified position, by using
random access file.

Rajnish

unread,
Jun 24, 2009, 1:31:47 AM6/24/09
to Technical Discussion
Please elaborate a bit more on what is your problem.

Rajnish

unread,
Jun 24, 2009, 2:51:32 AM6/24/09
to Technical Discussion
Hi Praveen

As per I know you can not insert but only overlapp.
This is only possible by creating a new file with previous contents
and insering your own.

Let us wait for comments by others.

Rajnish
> > random access file.- Hide quoted text -
>
> - Show quoted text -

Amit Goyal

unread,
Jun 24, 2009, 3:47:30 AM6/24/09
to technical-...@googlegroups.com
Hi Praveen,

I have an idea to do this.....

public void insertStringInFile(File inFile, int lineno, String lineToBeInserted) throws Exception {
// temp file
File outFile = new File("temp.tmp");

// input
FileInputStream fis = new FileInputStream(inFile);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));

// output
FileOutputStream fos = new FileOutputStream(outFile);
PrintWriter out = new PrintWriter(fos);

String thisLine = "";
int i =1;
while ((thisLine = in.readLine()) != null) {
if(i == lineno) {
out.println(lineToBeInserted);
}
out.println(thisLine);
i++;
}
out.flush();
out.close();
in.close();

inFile.delete();
outFile.renameTo(inFile);
}
I think this will help you.

Thanks,
Amit Goyal
--
Amit Goyal
Sr. Software Engineer
Imfinity India Pvt. Ltd.
Noida
9911459717
E-mail: anilg...@gmail.com
          anilg...@yahoo.com
          ami...@imfinity.com

Rajnish

unread,
Jun 24, 2009, 4:13:12 AM6/24/09
to Technical Discussion
Hi

Amit you are right... the same could be done with index in file by
reading character by character.
But the main thing is that we have to tweek the JAVA API a bit (means
our own logic) rather than something provided by JAVA API.

What do you think?
> E-mail: anilgoy...@gmail.com
>           anilgoy...@yahoo.com
>           ami...@imfinity.com- Hide quoted text -
Reply all
Reply to author
Forward
0 new messages