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.

Similar Messages

  • 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.

  • 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.

  • Can I append date to the file name using Bursting

    Hi All,
    I know that we can append date to the file using %y, %m and %d for
    Email
    FTP
    WEBDAV
    But is there any way of appending the date to the file name if I am bursting my file to a shared location.
    I tried that %y, %m and %d but that doesn't work for bursting.
    Please reply
    Thanks,
    Ronny

    If this requirment is for EBS, please refer the following blog
    http://blogs.oracle.com/BIDeveloper/2010/08/xdoburstrpt_passing_parameters.html
    For standalone see the following delivery sql query as example.
    select
    d.department_name KEY,
    'Standard' TEMPLATE,
    'RTF' TEMPLATE_FORMAT,
    'en-US' LOCALE,
    'PDF' OUTPUT_FORMAT,
    'FILE' DEL_CHANNEL,
    'C:\Temp' PARAMETER1,
    d.department_name||'_'||to_char(sysdate,'mmddyyyy')|| '.pdf' PARAMETER2
    from
    departments d
    Thanks
    Ashish

  • 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.

  • Appending Data to the MSWord Using java

    Hi,
         I need  to append data to the MSWord doc Using a java Program.The data contains both text and image.While appending data the size of the doc is increasing but the data is not Visible.
       I'm using Streams to read and write into the MSWord
    doc.
       Can anyone solve this problem and also tell me is there any alternative ie any external jar files are required?
    I'm working on Netweaver 2004s ide.
                                                  Thanks in Advance,
                                                   Venkat

    Hi Venkat ,
    Try This Code .....!!!!!!!!!!!!!!!!1
    import com.linar.jintegra.AuthInfo;
    import msword.*;
    public class WordExample {
      public static void main(java.lang.String[] args) {
        String oldfilestr = "c:
    temp
    test.doc";
        try {
          // DCOM authentication: Make sure Nt Domain, Nt User, Nt Password are valid credentials.
          // Uncomment this line if WordExample.java remotely accesses Word:
          // com.linar.jintegra.AuthInfo.setDefault("NT DOMAIN", "NT USER", "NT PASSWORD");
          // Specify host name or IP address of Word machine as parameter if
          // WordExample.java remotely accesses Word.
          // Application doc = new Application("123.456.789.0");
          Application app = new Application();
          java.lang.System.out.println("The version is: " + app.getVersion());
          java.lang.System.out.println("The path is: " + app.getPath());
          app.setVisible(true);   // Nice to see what is happening
          Documents docs = app.getDocuments();
          // For Word 2003, use:
          _Document document = docs.open(
            oldfilestr,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null
          // For Word XP, use:
          // _Document document = docs.open(
          //   oldfilestr,
          //   null,
          //   null,
          //   null,
          //   null,
          //   null,
          //   null,
          //   null,
          //   null,
          //   null,
          //   null,
          //   null,
          //   null,
          //   null,
          //   null
          // For Word 2000, use:
          // _Document document = docs.open(
          //   oldfilestr, // FileName,
          //   null,       // ConfirmConversions
          //   null,       // ReadOnly
          //   null,       // AddToRecentFiles
          //   null,       // passwordDocument
          //   null,       // password template
          //   null,       // revert
          //   null,       // write password document
          //   null,       // write password template
          //   null        // format
          Range rg = document.getContent();
          Find fd = rg.getFind();
          Thread.sleep(2000);
          // Replace (default replaces 1 phrase at a time)
          // For Word XP or 2003, use:
          fd.execute(
            "ow",
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            "igh",
            null,
            null,
            null,
            null,
            null
          // For Word 2000, use:
          // ff.execute(
          //   "ow", // FindText
          //   null,  // MatchCase
          //   null,  // MatchWholeWord
          //   null,  // MatchWildcards
          //   null,  // MatchSoundsLike
          //   null,  // MatchAllWordForms
          //   null,  // Forward
          //   null,  // Wrap
          //   null,  // Format
          //   "igh", // ReplaceWith
          //   null
          Thread.sleep(2000);
          app.quit(new Integer(WdSaveOptions.wdSaveChanges), null, null);
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          // Release all the COM objects:
          com.linar.jintegra.Cleaner.releaseAll();
    Thanks & Regards,
    Venkat

  • 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.

  • How can i retrieved data into the infocube from archived files

    hi,
    i have archived cube data and i have to load data into the cube from archived files.
    so now i want to find archived files and how to load data into the cube.
    thanks

    Hi.....
    Reloading archived data should be an exception rather than the general case, since data should be
    archived only if it is not needed in the database anymore. When the archived data target is serving also as a
    datamart to populate other data targets, Its recommend that you load the data to a copy of the original
    (archived) data target, and combine the two resulting data targets with a MultiProvider.
    In order to reload the data to a data target, you have to use the export DataSource of the archived data
    target. Therefore, you create an update rule based on the respective InfoSource (technical name 8<data
    target name>). You then trigger the upload either by using ‘Update ODS data in data target’ or by
    replicating the DataSources of the MYSELF source system and subsequently scheduling an InfoPackage
    for the respective InfoSource
    If you want to read the data for reporting or
    control purposes, you have to write a report, which reads data from the archive files sequentially.
    Alternatively, you can also use the Archiving Information System (AS). This tool enables you to define an
    InfoStructure, and create reports based on these InfoStructures. The InfoStructures define an index for
    the archive file data. At the moment, the archiving process in the BW system does not fill the
    InfoStructures during the archiving session automatically. This has to be performed manually when
    needed.
    Another way of displaying data from the archive file is by using the ‘Extractor checker’ (TCODE RSA3).
    Enter the name of the export DataSource of the respective data target (name of the data target preceded
    by ‘8’), and choose the archive files that are to be read. The extractor checker reads the selected archive
    files sequentially. Selection conditions can be entered for filtering but have to be entered in in internal
    format
    It will remain same in the change log table.
    Check this link :
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/b32837f2-0c01-0010-68a3-c45f8443f01d
    Hope this helps you...........
    Regards,
    Debjani............

  • 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

  • Saving the data into the tab limited text file

    Dear Friends ,
    please help me at the earliest possible , i want to store the data into an text file which is tab limited ,previously i was able to the same into the excel sheet using the jakarta HSSF POI , an open source library to store the data into the EXCEL sheet , now friends please tell me whether is there any other open source to store the data into the tab limited text file what i mean by tablimited is the data is to be saved as
    Name        Email-id        phone          streeet          city
    sri            @some.com     9434           jahdui          hye
    asdf         @.com           3455           sdgsdf         retlike this so please suggest me
    thank you in advance,
    bye
    sriharsha

    Consult the docs for BufferedWriter and from there.
    regards
    Christian
    import java.io.*;
    public class Test
         public static void main(String[] args)
              BufferedWriter writer;
              String[][] s = { {"Name","Email-id","phone","streeet","city"},
                        {"sri","@some.com","9434","jahdui","hye"},
                        {"asdf","@.com","3455","sdgsdf","ret"}};
              try {
                   writer = new BufferedWriter(new FileWriter("out.txt"));
                   for (int j=0; j< s.length; j++) {
                        for (int i = 0; i < s[j].length; ++i) {
                             writer.write(s[j]+"\t");
                        writer.newLine();
                   writer.close();
              } catch (IOException e) {
                   e.printStackTrace();

  • Append data into the file in application server

    Hi Friends,
    I have an issue where i have a job which has three different stepst for same program. If i run the job the program will create a file in the application server and append the other two steps in the same file without overwriting the file or creating a new file.
    My problem is like its creating three different files in application server for that particular job since it has three steps . Its not appending into one particular file .
    I am using the FM 'Z_INTERFACE_FILE_WRITE' where i have used the pi_append in the exportng parameter . ITs working when i specify the file in local system. It is appending correctly when i run the report normally to apppend into local system.
    But when i schedule a job to append the file in application server its creating three different files.
    Kindly help me if anyone is aware of this issue
    Thanks in advance
    Kishore

    Hi,
    Please use open dataset to write and append files.Please check the logic of Z FM which you are using .
    To open and write into a file  use
    OPEN DATASET FNAME FOR OUTPUT.
    To append data into existing file use
    OPEN DATASET FNAME FOR APPENDING.
    To write into file:
    v_file = file path on application server
      OPEN DATASET v_file FOR output.
      IF sy-subrc NE 0.
    write:/ 'error opening file'.
      ELSE.
       TRANSFER data TO v_file.
      ENDIF.
    CLOSE DATASET v_file.
    For appending :
    OPEN DATASET v_file fOR APPENDING.(file is opened for appending data  position is set to the end of the file).
    Thanks and Regards,
    P.Bharadwaj

  • Append data to the End of an Excel file

    How can I add new data (of a new aquisition) to an existing excel file without erasing old data? I'd like to add the new data aquisition under the last data aquisition. I have not the excel toolkit.
    I add here two file, the block diagram (i'm new in labview world  ) and what i see in excel when i run my VI. With the program I wrote, i can just save every aquisition in different excel file. 
    I hope i have been clear, thank you for your time.
    L.
    Attachments:
    how to save data acquisition in excel.jpg ‏51 KB
    data acquisition_excel.jpg ‏20 KB

    On the Write To Spreadsheet File function, there is a boolean input to append to file.  Set that to TRUE.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • Appending data(Image and Text) to a file written with RTFWriter2.

    I have file witten using RTFWriter2 which contains image and text.I nedd to modify the contents of that file at runtime through browsing and selecting the JFileChooser and append the data to existing selected file.
    I write inot the file for the first time using FileOutputStream("filename",ture)
    where true stands for appending data to current file,if does noes have any/not.
    But this does not work when i write the file using RTFWriter2,and i have to use this RTFWriter2 b'coz writing an image to a file is not done by any other way.
    If there is any do let me know and if not then what is the solution to this problem of appending data to existing file written by RTFWriter2.
    Your repkeis will be appreciated.Thank You.

    Mubin_Ahmed wrote:
    Hi,
    I want to write an application which can be used to read a file that contains both images and text.
    It must separate the images and text and write them in separate files..
    Can anyone help me with this please...
    My email id is [email protected]
    Thanks in advance...This forum is to use as a resource for your questions, not a place to enlist someone to program for you. If you have specific questions on what to do, not: "I've not a clue, so explain the wold to me." But specific questions on how to get your code to work or points about Java, then people from all over the world will be happy to help you in the context of the forum, and not through your private e-mail. E-mail defeats the basic purpose of having public forums for learning and exchange of information.

  • 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...

  • Data from the outputstream to a file in the server.

    Hello everyone,
    I have put the data in the outputstream. I need to place the data in a pdf and put it in a location in the unix box. Any suggestion? Below is the code i have written so far.
    public ByteArrayInputStream inputStream;
    public ByteArrayOutputStream pdfFile;
    public ServletOutputStream os;
    DataObject sessionDictionary = (DataObject)pageContext.getNamedDataObject("_SessionParameters");
    HttpServletResponse response = (HttpServletResponse)sessionDictionary.selectValue(null,"HttpServletResponse");
    try {
    os = response.getOutputStream();
    String contentDisposition = "attachment;filename=PrintPage.pdf";
    response.setHeader("Content-Disposition",contentDisposition);
    response.setContentType("application/pdf");
    XMLNode xmlNode = (XMLNode) am.invokeMethod("getEmpDataXML"); //This method invokes the required data from the view object
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    xmlNode.print(outputStream);
    inputStream = new ByteArrayInputStream(outputStream.toByteArray());
    pdfFile = new ByteArrayOutputStream();
    }catch(Exception e)
    throw new OAException("Hello "+e.getMessage(), OAException.ERROR);
    Thank You in advance.
    Pk

    hi Swetha,
    Go through the below links and these will solve your problem
    [How to Upload and Download Files in a Web Dynpro for Java Application|http://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/9076a593-2b08-2d10-2890-9a7078246ec4?QuickLink=index&overridelayout=true]
    [Storing data in a Text File in server  |Re: Storing data in a Text File.;
    Hope these links are useful
    regards
    Mahesh

Maybe you are looking for

  • Where is the highlight pop up search gone?

    With the older version when you would hi lite a word on a web page, a box would pop up with a 1/2 " which included google and when you clicked on it, a new page of the item would pop up. It doesn't seem to work with beta 4 . CAN SOMEONE HELP ME FIND

  • Should I update to 10.7.2 and Safari 5.1.1?

    I've spent a lot of time over the last few months reading about the problems people have been having with Lion and Safari.  As a result, when I decided to try Lion, I did so by first installing it on an external hard drive.  When that seemed to work

  • Hidden drop down lists

    I am trying to achieve the effect on this website http://www.thedesignersrepublic.com/ if you click on WORK on the right to display the drop down list and then click one of the options, you will see a list of sub headings appear.....any ideas of an e

  • Grid Control installation for 11G: is 10g grid required ?

    Dear All, We are currently using the local dbconsole for the monitoring and doing administrative work on our 11g database. My limited experience and observation indicates that 11G does not have its own enterprise Grid control yet and it requires the

  • Parent members not being updated when running AGG

    I have a scenario where eventhough the bottom level members change the parent members are not being updated when we run an agg For example if the bottom level member was 150 and we run the aggregate the numbers are fine. If the bottom level member wa