Solved

Set the position of the caret in a File

Posted on 2006-11-28
23
225 Views
Last Modified: 2010-03-31
Hi,
simple question,
I want to write an existing file, in a specific location,
for example :

                  BufferedWriter out =
                        new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path, true),"8859_1"));
                  out.newLine();
                  out.write("Hello World");

Hiow can I choose the location of the "Hello World" in the file ?
Thank u.

0
Comment
Question by:matthew016
  • 11
  • 8
  • 4
23 Comments
 
LVL 24

Expert Comment

by:sciuriware
Comment Utility
Use RandomAccessFile -> seek()

;JOOP!
0
 
LVL 24

Expert Comment

by:sciuriware
Comment Utility
You can't do this with buffered output, because the buffer has its own
strategy to keep things in memory.

Just create a File, then a RandomAccessFile(File, "rw");
then seek the position you like and write (may be overwrite).
Consider such a file as a byte/character array on disk.

;JOOP!
0
 
LVL 9

Author Comment

by:matthew016
Comment Utility
Thanks, what's the equivalent of :

out.newLine();

with the random access file ?
0
 
LVL 9

Author Comment

by:matthew016
Comment Utility
Also, I do not to specify encoding ?
iso, utf-8, ...

0
 
LVL 24

Expert Comment

by:sciuriware
Comment Utility
1) write((byte)'\n');
2) you got to do the coding yourself; you could write to a String array or byte array
and write that into the RandomAccessFile.

Btw.: this is a bad way to update text files.

;JOOP!
0
 
LVL 9

Author Comment

by:matthew016
Comment Utility


I want to insert this :

<!DOCTYPE configuration [
  <!ENTITY amp "&#x26;">
  <!ENTITY lt "&#x3C;">
  <!ENTITY minus "&#45;">
]>

into XML files, it must be just after the first line : <?xml version="1.0" encoding="ISO-8859-1"?>

                  File f = new File(path);
                  RandomAccessFile raf = new RandomAccessFile(f, "rw");

                  raf.seek(45);
   
                  raf.writeChars("<!DOCTYPE configuration [");
                  raf.writeChar((byte)'\n');
                  raf.writeChars("<!ENTITY amp \"&#x26;\">");
                  raf.writeChar((byte)'\n');
                  raf.writeChars("<!ENTITY lt \"&#x3C;\">");
                  raf.writeChar((byte)'\n');
                  raf.writeChars("<!ENTITY minus \"&#45;\">");
                  raf.writeChar((byte)'\n');
                  raf.writeChars("]>");
                  raf.writeChar((byte)'\n');
                  raf.close();

What is a bad way ?
I didn't follow u.

0
 
LVL 24

Accepted Solution

by:
sciuriware earned 250 total points
Comment Utility
              RandomAccessFile raf = new RandomAccessFile(new File(path), "rw");
               raf.seek(45);
               raf.writeChars("<!DOCTYPE configuration [\n<!ENTITY amp \"&#x26;\">\n<!ENTITY lt \"&#x3C;\">\n<!ENTITY minus \"&#45;\">\n]>\n");
               raf.close();
bad:
      well I did a lot of text (even source) updating, but I always read the entire text into a StringBuffer
      modified it and dumped it back.
You write 98 characters into that xml file. Mmmm ..., what's after that 98th character?
Keep on the safe side and don't try to save nano seconds, protect the integrety of your files.

;JOOP!

P.S.: I invested some time long ago in an Editor class that reads, edits and saves files just like an editor.
My best investment in software ever.

;!
0
 
LVL 9

Author Comment

by:matthew016
Comment Utility
Sorry, I don't understand wh
0
 
LVL 9

Author Comment

by:matthew016
Comment Utility
*at u are saying,
why do u ask me what's after the 98th car ?
0
 
LVL 9

Author Comment

by:matthew016
Comment Utility
it doesn't work,
It writes a lot of special carachters instead of the text
0
 
LVL 24

Expert Comment

by:sciuriware
Comment Utility
Believe me, what you are doing is wrong:
when a text within a textfile should be changed, then read the file, make the change and write it back.
This counts for files up to 10Mb.

And about character 98:

initial file:      |||||||||||||||||||pos 45||||||||||||||||||||||||||||||||||||||||||pos45+97|whatishere?||||||||||||||||||||||
if you succeed with your approach:
modified file: |||||||||||||||||||pos 45|changed data||||||||||||||||||||||||||||pos45+97|whatishere?||||||||||||||||||||||

Now, does the end of your text seamlessly connect to the data at pos 45+98?
And will it in the future? XML files may change in structure.

;JOOP!
0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 35

Assisted Solution

by:girionis
girionis earned 250 total points
Comment Utility
Using a StringBuffer would be easier.

try
        {
            BufferedReader in = new BufferedReader(new FileReader("<your file>"));
            StringBuffer sb = new StringBuffer();
            String line = in.readLine();
            sb.append(line).append("<!DOCTYPE configuration [\n").append("<!ENTITY amp \"&#x26;\">\n").append("<!ENTITY lt \"&#x3C;\">\n").append("<!ENTITY minus \"&#45;\">\n").append("]>\"\n)");
            while ((line = in.readLine()) != null)
            {
                sb.append(line);
            }
            in.close();
           
            BufferedWriter bw = new BufferedWriter(new FileWriter("<your file>"));
            bw.write(sb.toString());
            bw.flush();
            bw.close();
           
        }
        catch (Exception e)
        {
            System.out.println(e);
        }
0
 
LVL 24

Expert Comment

by:sciuriware
Comment Utility
That's what I said.

;JOOP!
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
I didn't say you didn't.
0
 
LVL 24

Expert Comment

by:sciuriware
Comment Utility
I didn't say you said I didn't ...

OK we agree, the questioners approach is wrong.
Yours is a good solution, which should be accepted and followed.

;JOOP!
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
I just provided some implementation code of how it can be done using a StringBuffer. The suggestion is yours. If the asker finds it useful I think a split would be fairer.
0
 
LVL 24

Expert Comment

by:sciuriware
Comment Utility
I'm already happy when all those random-write-in-text-programmers would stop.
There's lots of applications that will waste their files in the near future; time-bombs!
matthew016, do you understand?
Today the 'field' that you want to alter may be 98 characters long.
What will it be next week? How will they find out?
;JOOP!
0
 
LVL 9

Author Comment

by:matthew016
Comment Utility
Yep I understand ebcause I hardcode the number of cars after which it should append .

But the StringBuffer is the same thing ?
who says that we must write the doctype after the first line ?

Same problem occur here.
0
 
LVL 24

Expert Comment

by:sciuriware
Comment Utility
For your information, I use StringBuffer on java sources.
When I update certain line-parts (e.g. copyright notices, version strings) I do a context search.
It never fails.
If you blindly replace some characters without any check ............................. hope you don't work with guided missiles.

;JOOP!
0
 
LVL 9

Author Comment

by:matthew016
Comment Utility
How do u know I'm working on guided missiles  ?!  ^_-
0
 
LVL 24

Expert Comment

by:sciuriware
Comment Utility
I guessed.

;JOOP!
0
 
LVL 24

Expert Comment

by:sciuriware
Comment Utility
:)
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
:)
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

728 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now