Append a file

Dear all
i'd like to append the txt content of a file called file2.txt to the end of a file called file1.txt. I used an FileOutputStream with the boolean argument as "true". But in the end, the content of file1.txt is erased/overwritten, just the lines of file2.txt are in file1.txt. Please can you tell me why my code isn't working the way i want?
public void doFile1 (String fileName) throws Exception {
          File file = new File(fileName );
          FileOutputStream fos = new FileOutputStream(file);
          PrintStream p = new PrintStream (fos);
          p.println ("Hi, i'm the first line");
          p.println ("and i'm, the second one, but still from file1.txt!");
          p.flush();
     public void doFile2 (String fileName) throws Exception {
          File file = new File(fileName);
          FileOutputStream fos = new FileOutputStream(file);
          PrintStream p = new PrintStream (fos);
          p.println ("And i'm a line from the second file. HA!");
          p.println ("fajfdsklfdl?sjdskjf?kl file2.txt");
          p.flush();
     //write Vector to file
     public void vectorToFile (String fileName, Vector v)  {
          try {
               Enumeration e;
               File file = new File(fileName);
               FileOutputStream fos = new FileOutputStream(file, true);  //has to be written at the end of file
               PrintStream p = new PrintStream (fos);
               e = v.elements();
               int size = v.size();
               while (e.hasMoreElements()) {
                    String s = (String) e.nextElement();
                    p.println (s);
                    p.flush();
                    //this.headerPrintStream = p;
          catch (FileNotFoundException f) {
               System.out.println ("!!!!!!error in writing temporary header file");
          //return this.headerPrintStream;
     public void appendFiles () throws Exception {
          doFile1 ("file1.txt");
          doFile2 ("file2.txt");
          Vector v = new Vector ();
          v = readFile ("file2.txt");
          vectorToFile ("file1.txt", v);

1) you should call p.close() instead of p.flush()(to
both flush and close the file).
2) these lines:
Vector v = new Vector (); // why allocate a Vector
here...
v = readFile ("file2.txt"); // just to let it be
garbage collected by dropping the reference here
should just simply be:
Vector v = readFile("file2.txt");[bold]
___l
^^^^
______V
[bold]
does this ring a bell. Except that assume the l to be
a little bigger in size.Shameful! I'm reporting this as abuse! That poor warnerja was being stalked and 'flipped off' by vincmac!

Similar Messages

  • How to merge/append two files in sequence using BPM

    Hi All,
    My senario is to append two files data into a  new file on target system, only if the two files are available on source system. In case one file on the source system, no need to process file. Data in the new file should be in sequence means 1st file data then 2nd file data.
    Please suggest me how can i achieve this functionality using BPM.
    Thanks & Regards
    Sreeni

    For the first part (two files required) design as per Prateek's suggestion
    Data in the new file should be in sequence means 1st file data then 2nd file data.
    create a data structure which will be a combined structure of File1 and File2....target structure should have first reference for File1 and then for FIle2....than having two MTs (File1 and File2) at the source and the target MT at the receiver create your mapping......this will ensure that File1 data occures first and then File2 data.
    Regards,
    Abhishek.

  • Append SFW file name in action

    Sorry if this has been answered before. I found a lot of similar questions but no answers.
    If I record an action that includes Save for Web, I can either leave the name unchanged (and the individual file name will be used when I play the action) or change the name (and that name will be used every time I play the action). But it does not let me append the file name.
    For example, I want to create 3 sizes of each image and have each one named filename_sm.jpg, filename_md.jpg and filename_lg.jpg.
    Currently, I export each size to a different folder (with the original file name), use NameChanger to append the name, then move the images to their final destination. I thought that, in its 12th incarnation, Photoshop would have a more efficient way of dealing with this issue.

    xbytor has provided Scripts that convert Actions to JavaScript named »ActionToJavascript.jsx« and »ActionFileToJavascript.jsx«.
    You should be able to find them on this site
    http://www.ps-scripts.com/
    And you can use »ScriptingListener.plugin« (by moving it into the »Automate«-Folder) to record what you do in Photoshop (not brush-work, though, I’m afraid, basically steps that would also record in an Action) to use in JavaScript later on.
    What's missing from the actions is a way to edit them, You can re-record a step but you cannot edit it to fine-tune it.
    The way I see it, you can either have it real simple and use Actions or somewhat more involved and use Scripts.
    Anyway, you could look over in the Feature Request Forum if the features you do miss have been requested in the past and add your support or create a new request.
    I guess it is a bit like with the gears of a car – you can probably get around never using the fourth gear if you never drive on highways, but for certain purposes it might be beneficial to use it after all.
    Same with Photoshop Scripts – you can be a proficient and efficient creator/editor of amazing images in Photoshop without using custom Scripts, but certain tasks (which may or may not be relevant to your work) run »smoother« with Scripts.

  • Append swf file - Spry.Utils.updateContent - not work

    I don't understand this
    When I try to add swf file to Spry Tabbed Panels content -
    everything is OK. Now - in tabbed panels content I want to insert
    data from external html files. In this external file I have swf
    file and text, and images. When I preview this html external file
    in browser - all data are displayed correctly. When I try append
    this file into tabbed panels content :
    <a href="#" onclick="Spry.Utils.updateContent('apDiv1',
    'products/products1.htm'); return false;">Append file</a>
    only swf file in a new window are display.
    If I delete swf content from external html file - everything
    is ok. But if in external append file is a swf content - IE display
    only swf file.
    Is there posible to append html file with swf file in this
    method in any way?

    Hi Elaine,
    The implementation of AC_FL_RunContent() suggests that it was
    only meant to be run *BEFORE* the page finishes loading. Because
    Spry data sets and regions load and redraw asynchronously, usually
    *after* the page finishes loading, they are not compatible. As
    we've mentioned above, if Spry triggers the call to
    AC_FL_RunContent(), it will most likely be *after* the onload event
    has fired, and since AC_FL_RunContent() uses document.write() it
    will result in the entire page being overwritten by the
    <object>/<embed> tag that it writes out.
    That all said, libraries like SWFObject were designed to be
    called even after the onload event fires, at least from what I can
    tell from their samples. If you need to extract data from a data
    set to create your SWFObject, you can simply attach an observer to
    your data set that will tell the swfobject to do what it is you
    want it to do. For example:
    <script type="text/javascript">
    var dsProducts = new Spry.Data.XMLDataSet("products.xml",
    "/products/product");
    // Register an observer on dsProducts so that any time it
    changes data or the current
    // row changes, it tells the swfobject what to do:
    dsProducts.addObserver(function(notificationType, notifier,
    data)
    if (notificationType != "onDataChanged" || notificationType
    != "onCurrentRowChanged")
    return;
    // Do something with the swfobject here:
    var curRow = dsProducts.getCurrentRow();
    // The following embedSWF call is only an example of how to
    get the "productURL" column
    // value for the current row and pass it to the swfobject.
    The rest of the args, are left as names to
    // show you what you should be passing.
    swfobject.embedSWF(curRow.productURL, replaceElemIdStr,
    widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj,
    parObj, attObj);
    </script>
    --== Kin ==--

  • How to append a file in a trigger?

    I'm writing from a table to a file, and have created a trigger that works great...however, I need to append the file so it doesn't overwrite the file every time the trigger fires.
    Here's the code...but I can't figure out how to append the file instead of just write to the file:
    CREATE OR REPLACE TRIGGER checkout_trg
    AFTER UPDATE OF movie_qty ON mm_movie
    FOR EACH ROW
    DECLARE
    fh UTL_FILE.FILE_TYPE;
    BEGIN
    IF :NEW.movie_qty=0 THEN
      fh:=UTL_FILE.FOPEN('ORA_FILES','chekcout.txt','w');
      UTL_FILE.PUT_LINE(fh, 'Date: '||sysdate||', Movie ID: '||:NEW.movie_id||', Quantity: '||:NEW.movie_qty);
      UTL_FILE.FCLOSE(fh);
    END IF;
    END;
    /

    > It's for an assignment...I think thye're just trying to show us what's possible.
    Just as it is possible to show a learner driver to jump a red light, drive on the wrong side of the road, or do doughnuts in an intersection...
    But none of this will make that learner driver a good driver. Never mind able to correctly handle high performance cars on the professional circuit.
    Sorry mate - what they are showing/teaching you is pure bs. A trigger is not the "same thing" as a callback event in client programming.
    And feel free to give them this URL and tell them that I think they are full of it. Let's see how they defend their non-real world, totally irrelevant and wrong assignments in this very forum.

  • How can I append excel file rather than replace it?

    Hi,
    I have the attached VI set to write data to Excel, One case structure sends the data to cell B6, the other sends the data to cell B7. The problem is, the data is deleted from one cell when new data is added to another.
    I think I want to be able to append the data without deleting other cells. Any ideas?
    Thank you
    Todd
    Attachments:
    Flow meter write to Excel question.vi ‏180 KB

    Toddzilla,
    There are a couple different ways to append to excel files.  A couple links that might get you going are:
    Can I Add New Data to an Existing Excel File Without Erasing Old Data?
    Append Data to an Excel Document Every Iteration Using Report Generation Toolkit
    Are you trying to write over cells B6 or B7, or are you trying to append within the cell itself?  
    Hopefully this can get you on the right track.  When I append to files I tend to insert rows or append to the end of the file.
    Scott A
    SSP Product Manager
    National Instruments

  • Date appended to file name

    Hi
    I want to append date to my attachement name, to achieve this I went to scheduling and scheduled my report and gave attachment name as my_file_%y%m%d as specified by Tim in his blog (http://blogs.oracle.com/xmlpublisher/2009/12/dynamic_delivery_file_naming.html), but it is just giving the characters as they are instead of year month date appended to file name, my output is excel and our environment is standalone BIP.
    Anyone help me on this.
    Edited by: user8937215 on Sep 2, 2010 7:04 AM

    Please check if the thread Re: Can I append date to the file name using Bursting helps

  • Append binary file

    I would like to append new binary values to the existing binary file. Write File.vi looks like a good candidate for this, and it has two inputs, pos. mode and pos. offset which looks like something useful for my task. Unfortunately whatever I put into pos offset input I got Error 4 �end of file� and whatever I put into pos. mode nothing changes in binary file. There is also no example on the web which makes any use of them.
    Please can you tell how I can simply append new binary values to existing binary file. I put vi. In attachment which will write binary file, but only once.
    Thanks,
    Zoran
    Solved!
    Go to Solution.
    Attachments:
    bin_file_write.llb ‏396 KB

    Will this work if I have a situation like this ?
    I have a DAQ VI which gives me about 32667 events in about 10 loops. I want to append these events onto a binary file after every iteration. I followed the message conversations regarding the append binary file but for some reason only the latest set of events are recorded. Will this work in a loop ?
    Kudos always welcome for helpful posts

  • Reading, comparing and appending two files is taking lot of time

    public static void main(String args[])
         BufferedReader bSource = null;
         String sSource="";
         String sSourceData="";
         BufferedReader bDestination = null;
         String sDestination="";
         String sDestinationData="";
         try
              bSource = new BufferedReader(new FileReader("C:/TEMP/Source.map"));
              while((sSource = bSource.readLine()) != null)
                   sSourceData+=sSource;
              bDestination = new BufferedReader(new FileReader("D:/TEMP/Destination.map"));
              while((sDestination = bDestination.readLine()) != null)
                   sDestinationData+=sDestination;
         catch(IOException ioe)
              System.out.println(ioe.getMessage());
         finally
              try
                   bSource.close();
                   bDestination.close();
              catch(Exception e)
         if(sDestinationData.contains(sSourceData))
              fDestinationFlag=false;
         else
              fDestinationFlag=true;
         if(fDestinationFlag)
              BufferedReader br2 = null;
              BufferedWriter bw2 = null;
              try
                   br2 = new BufferedReader(new FileReader("C:/TEMP/Source.map"));     
                   bw2 = new BufferedWriter(new FileWriter("D:/TEMP/Destination.map",true));
                   while((line2 = br2.readLine()) != null)
                        bw2.write(line2);
                        bw2.newLine();
                        bw2.flush(); 
              catch(IOException ioe)
                   System.out.println(ioe.getMessage());
              finally
                   try
                        br2.close();
                   catch(Exception e)
                   try
                        bw2.close();
                   catch(Exception e)
    }I am comparing the contents of the two files Source.map (containing 3 lines) and Destination.map (containing 5000+ lines). The contents of the Source.map gets appended in the Destination.map only if it does not contain the same.
    Now my program is doing the necessary, but it is taking lot of time. It's taking 1 min 26 seconds.
    Could anyone please tell me what do I modify in may program to make it execute much faster.

    1) Just compare the byte content - no need to convert to Strings.
    2) Compare a block (say 256K bytes) at a time - no need to read the whole file into memory.
    3) Compare the file lengths first - if they are different then the content cannot be the same.
    4) When appending one file to the other, set the 'append' flag in the constructor of FileOutputStream to true.

  • Write to spreadsheet append to file

    Hi,
    I have two 2D data from measurement like those:
    the first:
    -1.000000E+0    5.102000E-10
    -9.000000E-1    4.069000E-10
    -8.000000E-1    3.149000E-10
    -7.000000E-1    2.329000E-10
    the second:
    1.505356E-2    8.315681E+10
    1.556519E-2    8.639427E+10
    1.604228E-2    8.955526E+10
    I used "write to spreadsheet" function to write to the file, for the second one, i set the "append to file" to "True". However, it will append the data at the bottom of the file. How can I append them side by side like:
    -1.000000E+0    5.102000E-10   1.505356E-2    8.315681E+10
    -9.000000E-1    4.069000E-10     1.556519E-2    8.639427E+10
    -8.000000E-1    3.149000E-10      1.604228E-2    8.955526E+10
    -7.000000E-1    2.329000E-10
    Thank,
    Joyce
    Solved!
    Go to Solution.

    Hi Joyce,
    as a spreadsheet file is just a text file with some special formatting codes it will always append at the bottom...
    But you can:
    Load the first data, attach the new data in RAM (using any order you like), write a whole new spreadsheet file!
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • Appending XML file

    Can somebody help me?
    I have a program that creates an XML file but every time I run the program I want that file to be appended. I can append the file but with XML I need to append the file before the final closing tag.
    This is my code:
    <%@page contentType="text/html"%>
    <html>
    <head>
    <basefont face="Arial">
    </head>
    <body>
    <%@ page language="java" import="java.io.*" %><%
    %><%@taglib uri="/WEB-INF/taglib65.tld" prefix="go"%>
    <%@taglib uri="/WEB-INF/filetags.tld" prefix="file"%>
    <form method=GET action="output.jsp">
    <%
    String xposition = request.getParameter("position");
    String ynflteam = request.getParameter("nflteam");
    String zplayer = request.getParameter("player");
    %>
    <%
    if(xposition.equals("position")){
    %>
    <go:Back alert="Please Select The Player's Position!"/>
    <%
    }else if(ynflteam.equals("nflteam")){
    %>
    <go:Back alert="Please Select The Player's NFL Team!"/>
    <%
    %>
    <file:writeFile source="c:\\nfl.xml" append="true">
    <fantasyteam>
    <position><%= xposition %></position>
    <nflteam><%= ynflteam %> </nflteam>
    <playername><%= zplayer%></playername>
    </fantasyteam>
    </file:writeFile>
    <%
    out.println("Player: " zplayer " has been added to your team");
    %>
    <br><br>
    <input type="Submit" value="Continue">
    </FORM>
    </form>
    </body>
    </html>
    It creates the XML file but when I go to add another entry and view the file it won't display because the file was closed by the previous entry.
    Eg:
    <fantasyteam>
    <position>RB</position>
    <nflteam>New York Jets</nflteam>
    <player>Curtis Martin</player>
    </fantasyteam> ----- HERE THE XML FINISHES
    <fantasyteam> ---- HERE IS ANOTHER ENTRY BUT IT WON'T WORK DUE TO THE CLOSING </fantasyteam> TAG!
    <position>WR</position>
    <nflteam>New York Jets</nflteam>
    <player>Santana Moss</player>
    </fantasyteam>
    What I want the file to look like is:
    <fantasyteam>
    <position>RB</position>
    <nflteam>New York Jets</nflteam>
    <player>Curtis Martin</player>
    <position>WR</position>
    <nflteam>New York Jets</nflteam>
    <player>Santana Moss</player>
    </fantasyteam>
    Can anyone help?
    Thanks
    Michael

    Hi,
    I think there are two ways. When using DOM in your file:write-method, you must parse the old file, add th enew nodes and then write the change document in the file. By the other way, without DOM, read the old file in a StringBuffer, delete the end with String-operations, append your new nodes as String, also the close-tag and wirte the change StingBuffer in the file.
    Hope thats help.
    Roland

  • Can I append the file name from a Foreach Loop Container Enumerator into a SQL Server Statement?

    I would like to pass back via an Email the name of the file that was successfully FTP'ed to a remote server. And I was hoping to do this via an Execute SQL Task with the following SQL Statement...but I just don't know if it will append the Foreach Loop Container
    variable enumerator to the appended Email message that I am building in SQL Server or if I can and how I can...
    I sort of get the feeling that I can try and do this via Dynamic SQL...I just don't know if by building dynamic SQL if my Foreach Loop Container enumerator variable will be appended to my Email Message via the SQL Server UPDATE 
    @[User::FTPFHFileName]
    Or do I add a Data Flow Task and an OLE DB Command and pass the Foreach Loop Container enumerator variable to a Stored Procedure referenced in the OLE DB Command via a "?"
    Thanks for your review and am hopeful for a reply.

    Hello,
    It seems that the issue had been solved and thanks for your sharing. It will be very beneficial for other community members who have similar questions.
    I’d like to mark this issue as "Answered". Please also feel free to unmark the issue, with any new findings or concerns you may have.
    Regards,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • ImageX and appending .wim files VERY WEIRD Discovery!

    I have a PC with two hard drives. I used ImageX to image each drive to a .wim file independently.
    The first image was of the C:\ drive
    The second image was of the D:\ drive.
    I then used the following command to append the 2nd hard disk WIM file to the first hard disk WIM file.
    C:>Program Files\Windows AIK\Tools\PETools>imagex /append /boot C:\1stdrive C:\Users\MyUserName\Documents\zTestFolder\Prec690_HDisk2Install.wim "Win7"
    My thinking was that I could then deploy the image as 1 WIM file. But when I get to the familiar 'Install Now' screen, once I click 'Next', I immediately get the following message.
    'The product key entered does not match any of the Windows images available for installation. Enter a different product key.'
    So, for fun I decide to try something else.
    I use my 'Deploy' UFD and only put in the C_Drive install.wim in the proper default location.
    I then successfully install the O/S and it boots into Windows no problem!!!
    But, HERE is WHERE IT GETS WEIRD
    I do the Diskpart portion so disk 1 can now have an image applied to it.
    Then, I apply the HardDisk2.wim file and it is successful...ie it doesn't throw any errors. The command I used was imageX /apply F:\HardDisk2.wim 1 D:\
     But when I reboot, now the system no longer boots into Windows.
    Instead it provides error of: No boot device available!

    Hello,
    The Windows Desktop Perfmon and Diagnostic tools forum is to discuss performance monitor (perfmon), resource monitor (resmon), and task manager, focusing on HOW-TO, Errors/Problems, and usage scenarios.
    As the question is off topic here, I am moving it to the
    Where is the Forum... forum.
    Karl
    When you see answers and helpful posts, please click Vote As Helpful, Propose As Answer, and/or Mark As Answer.
    My Blog: Unlock PowerShell
    My Book:
    Windows PowerShell 2.0 Bible
    My E-mail: -join ('6F6C646B61726C406F75746C6F6F6B2E636F6D'-split'(?<=\G.{2})'|%{if($_){[char][int]"0x$_"}})

  • Appending in file and supplying file name at run time using File Adapter

    Hi,
    Can we use File Adapter to write in a file in append mode. i.e. a BPEL process opening a file appending some text and closing the file each time it called.
    Another query is can we create the file at run time with the supplied file name?

    In order to append to a file, we can use Append="true" in the interaction spec for the File/Ftp adapter.
    <jca:operation
    FileType="ascii"
    PhysicalDirectory="/home/adapter/output"
    FileNamingConvention="OutputFile.txt"
    NumberMessages="1"
    Append="true"
    >
    Filename we can specify in wsdl...

  • Why ehen appending text file to text area, all the text in 1 line..

    please hlp
          public void actionPerformed(ActionEvent e)
              TArea.setText("");
              try
              String StrNeeded;
              BufferedReader BR;
              BR=new BufferedReader(new InputStreamReader(new FileInputStream("Data.txt")));
              StrNeeded=BR.readLine();
                   while(StrNeeded!=null)
                   TArea.append(StrNeeded);
                   StrNeeded=BR.readLine();
              catch(Exception excep)
    }this is my code m problem is that,
    i read a text file that has many lines, when i read it, i append it into the textarea, but what happend was all the text in my text area is in 1 line only(the other line is also appended but it is appended in the sama line.. help me

    readLine removed the line feed from the end of the line.
    You should append a \n to the end of the line like this:TArea.append(StrNeeded + "\n");Also it's a bad idea to catch an exception and do nothing.
    Add printStackTrace in the catch block.

  • Append a file with date and name in the output file

    I am running a script which produce an output in excel file, I would like the server name and the date in the output file,  Both the servername and date has declared at the beginning of the script as 
    $server = test1
    $date = Get-Date -uformat %Y-%m-%d
    I am able to append either server or date but not both. Could you please help me out on this.
    I would like the output file as '
    server_report_date.xls

    I got this working by 
    "C:\Aravind\Scripts\$server-"+"Report-" +"$Date"+".xls"
    Thanks!!

Maybe you are looking for

  • Os x 10.8.3 bootcamp reverse scroll direction

    I just installed 10.8.3 on my retina and the new windows 8 driver with a fresh bootcamp install.  Good news is the bluetooth works to keyboard and trackpad, both my external thunderbolt monitors work, the resolution is now correct at 2880x1880. Only

  • INS0009: Unable to connect to the database with user SYS

    Hi all, I'm trying to create an OWB repository with OWB repository assistant (10.2.0.2.) on a 10.2.0.1. database (windows XP platform). I get the following error every time I fill in the connect info for the SYS user: INS0009: Unable to connect to th

  • /SAPTRX/IDOC_INPUT_EVMSTA IDoc posting only works for single BAPI call

    Although the settings and code imply that the function /SAPTRX/IDOC_INPUT_EVMSTA can handle multiple events in a single IDoc the fact is that the code does not have a refresh statement on the BAPI internal tables with the loop through the IDoc contro

  • Another mapping question

    Hi, I need help on mapping. I have a target field vbeln (with SAP delivery number), with this delivery number I need to get all delivery items. How can I get them? Points will be rewarded. Cheers.

  • Container and excel

    I have create an archive of some measurement in an excel worksheet with activeX. I want to view this archive without open excel. I want to use a container: but only a part of the worksheet is visible on the screen. I try to add scrollbar but I didn't