Appending "something" at the beginning of a file

Hello,
I am trying to append a character to the beginning of a file, doesnt seem to work with RandomFileAccess. I first called the seek() methond
seek(0); //zero to send the file pointer to the front 
write((byte) myCharValue);apparently it overwrites the value at the front instead of adding for example:
before running the code the file has: "Java is Cool!"
after running the code the file has: "xava is Cool!"
Any Ideas?
Thanks

1. Create a new file.
2. Write out whatever you wanted to insert at the beginning.
3. Copy the data from the old file and append it to the new file.
4. Close the files.
5. Delete the old file.
6. Rename the new file.

Similar Messages

  • Appending data to the beginning of a file

    How do you write data to the first line of a file without overwriting the data which is already present?
    Data before:
    888826759 100011021
    888826767 100011026
    888826916 100011024
    888826916 100011023
    888826940 100011029
    888826940 100011028
    888857389 100011020
    888871480 100011029
    What I want data to look like after:
    ABC
    888826759 100011021
    888826767 100011026
    888826916 100011024
    888826916 100011023
    888826940 100011029
    888826940 100011028
    888857389 100011020
    888871480 100011029
    I'm trying this, but it doesn't work as it overwrites the first piece of data in the file
    file.seek(0);              
    file.writeBytes("ABC");so that the output is:
    ABC826759 100011021
    Edited by: drakester on Oct 12, 2007 10:59 AM

    You might be able to write the file into one of the Collection Lists that maintain order (like LinkedList, but there are others), add the first line, and then rewrite the file from the list. You might also find the Collections methods reverse and rotate could be useful if you add the data at the end of the list.
    You could also create an array and fill the 2nd through last elements with the file lines, insert your data as the first element, then write the file from the array.
    Ther are a number of variations on the above approaches.

  • Append a line at the beginning of a file via UTL_FILE

    Hello,
    is there a way to append a line to the beginning of a file instead of at the end of an existing file via UTL_FILE?
    Thanks in advance,
    Geert

    No, you would have to create a new file.

  • How would I erase the beginning of a file?

    I want to be able to erase the beginning of a file, while writing to the end...WITHOUT reading the whole file and writing it again because that would be a waste of resourses. Obviously I know that option is available.
    My situation is that I am adding lines to a log file, and I want to remove any entries that are X hours old. Logging a lot of information would mean that every few seconds, an entry is older than X hours and needs to be removed. It doesnt have a set number of lines so I can't just recycle the file by doing something like: if at line number Y, start at line 1 and remember the current line number.
    Adding to the top of the file, pushing the others lines down, and making cuts at the end would also work, but the same situation arises, how do I add to the beginning of the file, without having to copy the entire file to add the entry to the top.
    The reason I don't want to read the whole file is because having to read the whole file and write the whole file when an entry is made is time consuming and wastes CPU and memory, especially when the logs are coming in several lines a second.

    I would think it could easily be done. say you want to erase the first 10 bytes, why cant you just say move the start of the file up 10 bytes. Somewhere in the filesystem the start of the file is stored. I found underlying file copying that claims this in FileChannel's transferTo and transferFrom:
    This method is potentially much more efficient than a simple loop that reads from this channel and writes to the target channel. Many operating systems can transfer bytes directly from the filesystem cache to the target channel without actually copying them.
    If I can't just chop, I'll have to copy quickly at scheduled intervals.
    This is code I ran to test the above quote:
        public static void main(String[] args) throws Exception{
            args = new String[2];
            BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter File Name:");
            args[0] = input.readLine();
            System.out.println("Enter test (0-2):");
            args[1] = input.readLine();
            long time = System.currentTimeMillis();
            int version = Integer.parseInt(args[1]);
            switch (version) {
                case 0:
                    BufferedReader in = new BufferedReader(new FileReader(args[0]));
                    PrintWriter out = new PrintWriter(new FileWriter("tempfile.txt"));
                    in.readLine();//skip line.
                    for (String line = in.readLine();line != null;line = in.readLine()) {
                        out.println(line);
                    in.close();
                    out.close();
                    break;
                case 1:
                    RandomAccessFile raf = new RandomAccessFile(args[0],"rw");
                    String line = raf.readLine();
                    long offset = raf.getFilePointer();
                    byte[] b = new byte[1024];
                    int bytes = 1024;
                    long index = 0;
                    System.out.println("index = " + raf.getFilePointer());
                    System.out.println("index = " + line.length());
                    while(bytes == 1024) {
                        bytes = raf.read(b);
                        index = raf.getFilePointer();
                        raf.seek(index - bytes - offset);
                        raf.write(b,0,bytes);
                        raf.seek(index);
                    raf.setLength(raf.length()-offset);
                    raf.close();
                    break;
                case 2:
                    RandomAccessFile raf2 = new RandomAccessFile(args[0],"rw");
                    String line2 = raf2.readLine();
                    long offset2 = raf2.getFilePointer();
                    FileChannel f = raf2.getChannel();
                    FileChannel g = f.position(0);
                    g.transferTo(offset2,raf2.length() - offset2,f);
                    raf2.setLength(raf2.length()-offset2);
                    raf2.close();
                    break;
            System.out.println(System.currentTimeMillis() - time);
        }and had these results
    166MB Log File
    Linux Mandrake 900Mhz
    Case 0 = 32914 ms
    Case 1 (1k byte[]) = 15043 ms
    Case 1 (16k byte[]) = 6988 ms
    Case 1 (1MB byte[] = 6113 ms
    Case 2 = 6188 ms
    :-/ guess this proves that the FileChannel can't chop

  • How to delete the beginning of a file?

    Hi,
    is there a way to delete the beginning of a file, or do I have to copy the rest of the file and create a new one and then delete the old one?
    Lets say my file contains "ThisIsMyFile" and I want to delete "This", so that my new file contains "IsMyFile", how can I do this?
    thanx

    You have to copy.

  • Xtra character appearing at the begining of a file written by my java pgm

    Hi,
    I am trying to write an object to an output file (which is a HTML document). But when the object is written at the
    begining of the file the following character appears
    ' �� '
    Is there a way to supress this character when the file is written ?
    My java program is running in a Sun Solaris machine and the file is created in the same directory.
    Thanks
    Bala.

    You have to give a lot more info... Are you trying to
    write the object as an object (ie serialize it) or are you
    simply trying to write the contents (data held in) this
    object to an HTML file? Some code would help too.....
    If you are simply wanting the contents written
    be sure you are not trying to use an ObjectOutputStream...
    If you are trying to write the Object (ie serialize it) then
    you have to remember that there are chances of
    non-printable characters being written...

  • Write filename to the beginning of that file.

    I need help on the following:
    While reading and validating a file in Java, HOW can I
    1. GRAB the FILENAME of the file I received,
    2. Open the file and WRITE the FILENAME at the BEGINNING of the file?
    Thank you in advanced.

    You can get the filename by using java.io.File.getName();
    As far as sticking it into the front of your file, you should read the whole old file (hopefully it's not too big), then write it all back out again to the same file, only write the name string first

  • Print data to the beginning of a file

    Hi,
    I have written this code to wite data to a textfile:
    PrintWriter FeedStream = new PrintWriter(new FileOutputStream(feed_path, true));
    FeedStream.println(text);
    FeedStream.close();The code works fine but it writes the data at the end of the file whereas I want it at the beginning of the file. How to solve this?
    Thanks in advance,
    leonard

    Well, the reason is that I want to print the data in another application and saving the data this way is more convenient.
    E.g.
    application 1 prints this to a file:
    L1 Test=45
    L2 Temp=10
    then the same application maybe has to write more data to the file at another time, and adding:
    L1 Test=39
    L2 Temp=12
    However application 2 that monitors the file every 6h should analyse the data from the newst to the oldest. For the conveniance when parsing the file with application 2 I want to add the data to the beginning of the file.

  • To add space at the begining of a file

    Hi,
      i have a requirement, when you transfer data to a file it should start writing data from 10th place.
    ex: data p_ext LIKE rlgrap-filename.
         data: var1(9)  type c value 'test data'.
         data: hold(100) type c.
         p_ext = '/devabap/if/daily/out/test1.rg'.
    open dataset p_ext for output in text mode encoding default.
    concatenate c_blank
                       var1
                       into hold
                       separated by cl_abap_char_utilities=>horizontal_tab.
    transfer cont to p_ext.
    close dataset p_ext.
    When i do this and check the file contents in AL11.
    i can see the contents like
    #test data.
    but i want to know how this can that be changed to like
                     #test data.
    Regards,
    Raghavendra.

    Hi ,
      When you use concatenate using separating , the separating string  does not come in the first place , it just comes between the values you are concatenating .
    so to acheive your result , you should again concatenate  cl_abap_char_utilities=>horizontal_tab , to your result before you transfer it to the file.
    concatenate cl_abap_char_utilities=>horizontal_tab cont into cont.
    or you can do is use the shift command after the concatenate operation.
    Here is a sample
    shift cont by 10 places RIGHT.
    Regards
    Arun
    Edited by: Arun R on Jan 22, 2009 1:29 PM

  • Appending string to the start of a file problem

    Hi guys,
    I've got an xml file which i want to add a dtd to. So i'm using RandomAccessFile to seek the start of the file and write to it, but its seems to be overwriting a small part of my file. My code to this is below:
             try {
             RandomAccessFile f = new RandomAccessFile(xmlMap,"rw");
                f.seek(0);
            //write DTD definition to start of file
             f.writeChars("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+"\n"+
                     "<!DOCTYPE map SYSTEM \"mapDTD.dtd\">"+"\n");
             f.close();
             } catch(IOException e) {
                  System.out.println("ERROR with file name, game exiting");
                  System.exit(1);
             }If i take in this xml file:
    <map width="19" height="19" goal="6" name="Hallways of Dooom">
         <random-item type='lantern' amount='5' />
         <random-item type='health' amount='10' />
         <tile x="0" y="0" type="floor" />
         <tile x="1" y="0" type="floor">
              <renderhint>floor:wood</renderhint>
         </tile>
         <tile x="2" y="0" type="floor" />
         <tile x="3" y="0" type="wall" />
         <tile x="4" y="0" type="wall" />
         <tile x="5" y="0" type="wall">
              <renderhint>wall:bricks,cracked</renderhint>
         </tile>it gets overwritten as :
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE map SYSTEM "mapDTD.dtd">
         <tile x="0" y="0" type="floor" />
         <tile x="1" y="0" type="floor">
              <renderhint>floor:wood</renderhint>
         </tile>
         <tile x="2" y="0" type="floor" />
         <tile x="3" y="0" type="wall" />
         <tile x="4" y="0" type="wall" />
         <tile x="5" y="0" type="wall">
              <renderhint>wall:bricks,cracked</renderhint>
         </tile>I want it so it is :
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE map SYSTEM "mapDTD.dtd">
    <map width="19" height="19" goal="6" name="Hallways of Dooom">
         <random-item type='lantern' amount='5' />
         <random-item type='health' amount='10' />
         <tile x="0" y="0" type="floor" />
         <tile x="1" y="0" type="floor">
              <renderhint>floor:wood</renderhint>
         </tile>
         <tile x="2" y="0" type="floor" />
         <tile x="3" y="0" type="wall" />
         <tile x="4" y="0" type="wall" />
         <tile x="5" y="0" type="wall">
              <renderhint>wall:bricks,cracked</renderhint>
         </tile>
         <tile x="6" y="0" type="wall" />
         <tile x="7" y="0" type="wall" />
         <tile x="8" y="0" type="wall">
              <renderhint>wall:rock,cracked</renderhint>
         </tile>If anyone can see what's going wrong and how i can correct, i would greatly appreciate them saying so.
    Thanks a lot.

    javaUser wrote:
    Hi guys,
    I've got an xml file which i want to add a dtd to. So i'm using RandomAccessFile ...That's your mistake. Don't use random access file. It wasn't built for this situation and shouldn't be used for this situation. Do the right thing: rewrite the whole file.

  • Insert a line into the beginning of a file without overwriting data

    I would like to dynamically alter/add new headers to a csv file as needed. The code I have below overwrites the previously written data an amount equal to each new header added each time I call the vi below. Any suggestions on how to do this without reading in the file each time? I want to avoid the processing time of reading in the file between processing new data.
    Thanks!
    Attachments:
    R900 - Log Data Stream to File.vi ‏22 KB

    Yes, but you can still write everytime, you dont need to read the file back.
    /Y
    LabVIEW 8.2 - 2014
    "Only dead fish swim downstream" - "My life for Kudos!" - "Dumb people repeat old mistakes - smart ones create new ones."
    G# - Free award winning reference based OOP for LV

  • Why does iPod on iPhone4 cut off the beginning of audio files?

    First time user of Apple and iTunes and iPhone4. I transfer my audio files onto my iPhone, play them in iPod and it cuts off the first 10 or more seconds or so. The files play perfectly well in every other device and player. Why does this happen in iTunes/iPhone/iPod? How to fix this?
    Thanks.

    You might want to cross post this in the Premiere Elements forum:
    http://forums.adobe.com/community/premiere/premiere_elements

  • How to append content in begining of text file?

    i want to append content in the begining of text file.
    (usually append flag will append content in end of the file)
    is there any class in java support this need?
    if there is no class for this...anybody can give logic to implement
    venu

    Duplicate post
    http://forum.java.sun.com/thread.jspa?threadID=577639

  • Output on existing file at the begining??

    Hi,
    I have a problem about outputing.
    I want to write some texts at the begining of existing file.
    eg... file A
    "Hello
    then i want to insert some texts at the begining
    e.g. insert "YOU"
    then file A
    will become
    "YOU HELLO
    any idea?
    thank alot

    In order to make room for new data at the beginning of a file it is neccessary to shift the original files content towards the end of the file. This cannot be done without copying (read/write) the whole content of the file.
    But as you mentioned the term log-file have a look at other log-files written by applications. The newest entry is always at the end of the file. The reason for this is that people encounterd the same problem you have right now.
    As a matter of fact, if I read any file with log-entries in my editor I jump to the end of the file right away and start reading the entries backwards from there. People are used to it, just append your log-entries to the end of the file.

  • How to find out the format of a file?

    Is there any way to find out the format of a file?
    By format I mean binary, text, .doc, .rtf, etc. Please kindly help

    The unix file command:
    file *
    foo.doc ms-office file / word
    bar.png png image, 32x32 pixels, no transparency
    moo.hhml html text
    note that as in the last - file names are ignored, it works by checking the beginning of each file's data against it's database, and as in #2 it can sometimes see a lot more than just the file format.
    Don't know of a windows port, you could try cygwin

Maybe you are looking for

  • ABAP Objects and BADI

    HI Can anyone give me the link for ABAP Objects and BADI'S. I would like to have ABAP Objects with Example as well as BADIS. Please tell me as iam new to those. Thanks in advance

  • Can I stop a text from being read by the wrong person

    Can I stop an unread text message

  • Urgent solution needed please

    Hi everyone, I am having a problem when i am trying to upload image to MysqlUSING jsP USER INTERFACES. I am using mozilla as a browser on Mandrake Linux platform. I am calling a bean Images.java which when run in konsole mode its working fine and ima

  • Installation Problems with Creative ZEN an Win XP SP3 (germ

    Hi, first of all, i am german so my english isn't hte best... i bought a creative ZEN 4GB. i installed all the stuff on the installation-cd restarted my system plugged the ZEN in my USB-Port WIN XP mentioned a new device and wanted to install an MTP

  • Looping for write_form

    Hi, I am working on smart forms. I have used some queries queries in my print program to populate my data in internal table say iafvc. While using write_form, I am using following loop: (Note that I am using 'Append' for function parameter in exporti