How to append to a file

hi here is my code. i wanted to appended the string to the file with out rewriten over it.
and how do i make it do a new line.
import java.io.* ;
import java.awt.*;
import java.util.*;
import java.text.*;
import java.lang.Byte.*;
import java.awt.Event.*;
//===================================================================
class BinRead3{
//used writer class instead uses dataoutput stream for now
BufferedWriter out;
void open(String filename)
Opens the file to be written to
@param String the filename of the file
POST: file can be written to
public void open(String filename){
try
out = new BufferedWriter(new FileWriter(filename));
catch (IOException e)
System.out.println("open file to write error");
//create the log File File
void addEntry(String entry)
Writes an entry to the file
@param String the entry to be written
POST: entry written to file
public void addEntry(String entry){
//write Error or what ever to the File
try{
out.write(entry);
catch(IOException e2){
     System.out.println("Error trying to write to the file");
void close()
Closes the file
POST: the file can not be written to
public void close(){
try {
out.close();
catch (IOException e2)
System.out.println("Error closing file");
}//End of Close
public static void main( String args[] ) {
     // Construct an instance of the Timer class
          BinRead3 bRead = new BinRead3();
bRead.open("LogFile.log");
bRead.addEntry("this is error testing");
bRead.addEntry("this is error testing3");
bRead.close();
}//End of file Import log
//===================================================================

FileWriter has a number of constructors. One of then is
FileWriter(String fileName, boolean append)
passing true as the second parameter will not overwrite existing content. This information is available in the j2se sdk documentation bundle downloadable from java.sun.com

Similar Messages

  • How to append to zip files

    I would like to know how to append to a zip file, I know how to write a zip file and I can put as many entries in the first time but if I run my program again and try to add a file to the same zip file it erases what was already in it. I use ZipOutputStream(new FileOutputStream), I have tried the FileOutputStream append but it does not seem to work for zip files, I have tried RandomAccessFile on my zip file but that just seems to add the bytes to the file that already in the zip file, and makes the file unopenable, corrupt. If you can help, please tell me how.

    You actually have to open the previous zipped file, read it's entries and their data and then rewrite a new zip file with these entries and their data. You can then delete your first file and rename the new one so the effect is that you have "appended" zip files to the existing archive.
    Here is an example which I pieced together from a larger bit of code that I have. This would need to be in a try/catch but this should give you a start.
    /** This method adds a new file to an existing zip file. It * includes all the zipped entries previously written.
    * @param file The old zip archive
    * @param filename The name of the file to be Added
    * @param data The data to go into the zipped file
    * NOTE: This method will write a new file and data to an archive, to
    * write an existing file, we must first read the data frm the file,
    * then you could call this method.
    public void addToArchive(File file, String filename, String data)
         ZipOutputStream zipOutput = null;
    ZipFile zipFile = null;
    Enumeration zippedFiles = null;
    ZipEntry currEntry = null;
    ZipEntry entry = null;
    zipFile = new ZipFile( file.getAbsolutePath() );
         //get an enumeration of all existing entries
    zippedFiles = zipFile.entries();
         //create your output zip file
    zipOutput = new ZipOutputStream( new FileOutputStream ( new File( "NEW" + file.getAbsolutePath() ) ) );
    //Get all the data out of the previously zipped files and write it to a new ZipEntry to go into a new file archive
    while (zippedFiles.hasMoreElements())
    //Retrieve entry of existing files
    currEntry = (ZipEntry)zippedFiles.nextElement();
    //Read data from existing file
    BufferedReader reader = new BufferedReader( new InputStreamReader( zipFile.getInputStream( currEntry ) ) );
    String currentLine = null;
    StringBuffer buffer = new StringBuffer();
    while( (currentLine = reader.readLine() ) != null )
    buffer.append( currentLine);
    //Commit the data
    zipOutput.putNextEntry(new ZipEntry(currEntry.getName()) ) ;
    zipOutput.write (buffer.toString().getBytes() );
    zipOutput.flush();
    zipOutput.closeEntry();
    //Close the old zip file
    zipFile.close();
    //Write the 'new' file to the archive, commit, and close
    entry = new ZipEntry( newFileEntryName );
    zipOutput.putNextEntry( entry );
    zipOutput.write( data.getBytes() );
    zipOutput.flush();
    zipOutput.closeEntry();
    zipOutput.close();
         //delete the old file and rename the new one
    File toBeDeleted = new File ( file.getAbsolutePath() );
    toBeDeleted.delete();
         File toBeRenamed = new File ( "NEW" + file.getAbsolutePath() );
    toBeRenamed.rename( file );
    Like I said I haven't tested this code as it is here but hopefully it can help. Good luck.

  • How to append two CSV files using ftp

    Hi
    Please let me know the FTP command to append the two .CSV files into one .CSV file.
    e.g.
    Let me explain:
    one CSV file has the fields F1 , F2, F3 , F4 and has 5 records
    another CSV file has the same sequence of fields F1, F2, F3, F4 and has 10 records
    after appending both the files , I must get 15 records.
    Thanks
    Alok

    Ok I will try out.
    I am illustrating my requirement as follow
    File#1 (type .CSV)
    F1     F2     F3     F4
    100   566    89     86   
    235   256    56     12
    File#2 (type .CSV)
    F1     F2     F3     F4
    56     56     98     102
    12     23     36      523
    23      56     56    89
    Now we want to Append File#1 to File#2 as follow: 
    F1    F2    F3     F4
    100   566    89     86   
    235   256    56     12   
    56     56     98     102
    12     23     36      523
    23      56     56    89
    Please suggest now that which command would be appropiate.
    Alok

  • How to append poi excel files?

    Hi All,
    I am using POI excel files and this is my code to create an excel sheet.
    for(i=0;i<i<files.length();i++)
    String excel=excelFiles[i]
    Date date=  new Date();
      int  rowCount= 45;
    Sample samp=new Sample();
    samp.createWorkbookForLogReport(excel,date,rowCount);
        private HSSFWorkbook createWorkbookForLogReport(String excel,Date date,int rowCount) throws IOException {
            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet sheet = wb.createSheet("new sheet");
            int idx = 0; // rows index
            HSSFRow row = sheet.createRow((short)idx);
            idx++;
            String[] attributessss =
            { "ExcelName", "Date and Time", "RowCount" };
            for (int j = 0; j < attributessss.length; j++) {
                attribute = attributessss[j];
                row.createCell((short)j).setCellValue((String)attribute);
                row = sheet.createRow((short)idx);
                row.createCell((short)0).setCellValue((String)excelFiles);
                row.createCell((short)1).setCellValue(date);
                row.createCell((short)2).setCellValue(rowCount);
                idx++;
            return wb;
    the parametres are continuously changing i am able to write once in the excel file.but couldnt able to append the same excel file.is there any possibility to append the single excel file for changing records.

    is it Not possible?

  • How to append existed jar file?

    do existed jar file be append again?
    example:
    a.jar // existed jar file
    xyz // forlder that want append to a.jar

    you mean you want to add a directory full of class files to the existing .jar file?
    check the .jar file usage options.
    c:\> jar -helpDiablo

  • Append to Zip file

    Hi everyone,
    I have created a zip file (test.zip), but i cant figure out how to append a text file to it.
    Can anybody help?

    http://java.sun.com/j2se/1.5.0/docs/api/java/util/zip/ZipInputStream.html#createZipEntry(java.lang.String)

  • How to append records in a file, through file adapter.

    Hi All,
    How to append records in a file, through file adapter.
    I have to read data from database and need to append all records in a file.
    Thanks in Advance.

    Hi,
    I think you have a while loop to hit the DB in your Process (As you said you have to fetch data from DB 10 times if 1000 rec are there)
    First sopy your DB O/P to one var
    and from second time append to previous data.(Otherwise you can directly use append from starting instead of copy and append)
    When loop completes you can transform to File adapter Var.
    Otherwise you can configure yourFileadapter such that it will aapend current records to previous records.
    You can use 'Append= true' in your file adapter wsdl.
    It will append previous records to current records in the same file.
    Regards
    PavanKumar.M

  • How to append time stamp to TDMS file

    hello all, i would like to append time stamp to a tdms file as the 1st column of the file... the pattern should look like this.. can anyone suggest how to create such a file?
    Time
    Data
    0.001
    2.5545
    0.002
    2.653
    0.003
    1.215
    0.004
    2.6586
    Now on LabVIEW 10.0 on Win7

    I got the below oepratin to do.. i used a Write to Measurement File.vi and selected tdms format and it worked out... however, when i read the same file using read measurement file.vi and selected tdms option in ti, i am observing that on the x-axis graph, i get real-time stamp instead of decimals... i want x-axis as decimals instead of timestamp, and when i selected decimals in waveform graph properties --> display format--> x-axis, i could not select decimal instead of time-stamp... can anyone please let me know how to get what i intend to do?
    Now on LabVIEW 10.0 on Win7
    Attachments:
    Untitled 2.vi ‏68 KB

  • 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 to read appended objects from file with ObjectInputStream?

    Hi to everyone. I'm new to Java so my question may look really stupid to most of you but I couldn't fined a solution by myself... I wanted to make an application, something like address book that is storing information about different people. So I decided to make a class that will hold the information for each person (for example: nickname, name, e-mail, web address and so on), then using the ObjectOutputStream the information will be save to a file. If I want to add a new record for a new person I'll simply append it to the already existing file. So far so good but soon I discovered that I can not read the appended objects using ObjectInputStream.
    What I mean is that if I create new file and then in one session save several objects to it using ObjectOutputStream they all will be read with no problem by ObjectInputStream. But after that if in a new session I append new objects they won't be read. The ObjectInputStream will read the objects from the first session after that IOException will be generated and the reading will stop just before the appended objects from the second session.
    The following is just a simple test it's not actual code from the program I was talking about. Instead of objects containing different kind of information I'm using only strings here. To use the program use as arguments in the console "w" to create new file followed by the file name and the strings you want save to the file (as objects). Example: "+w TestFile.obj Thats Just A Test+". Then to read it use "r" (for reading), followed by the file name. Example "+r TestFile.obj+". As a result you'll see that all the strings that are saved in the file can be successfully read back. Then do the same: "+w TestFile.obj Thats Second Test+" and then read again "+r TestFile.obj+". What will happen is that the strings only from the first sessions will be read and the ones from the second session will not.
    I am sorry for making this that long but I couldn't explain it more simple. If someone can give me a solution I'll be happy to hear it! ^.^ I'll also be glad if someone propose different approach of the problem! Here is the code:
    import java.io.*;
    class Fio
         public static void main(String[] args)
              try
                   if (args[0].equals("w"))
                        FileOutputStream fos = new FileOutputStream(args[1], true);
                        ObjectOutputStream oos = new ObjectOutputStream(fos);
                        for (int i = 2; i < args.length ; i++)
                             oos.writeObject(args);
                        fos.close();
                   else if (args[0].equals("r"))
                        FileInputStream fis = new FileInputStream(args[1]);
                        ObjectInputStream ois = new ObjectInputStream(fis);
                        for (int i = 0; i < fis.available(); i++)
                             System.out.println((String)ois.readObject());
                        fis.close();
                   else
                        System.out.println("Wrong args!");
              catch (IndexOutOfBoundsException exc)
                   System.out.println("You must use \"w\" or \"r\" followed by the file name as args!");
              catch (IOException exc)
                   System.out.println("I/O exception appeard!");
              catch (ClassNotFoundException exc)
                   System.out.println("Can not find the needed class");

    How to read appended objects from file with ObjectInputStream? The short answer is you can't.
    The long answer is you can if you put some work into it. The general outline would be to create a file with a format that will allow the storage of multiple streams within it. If you use a RandomAccessFile, you can create a header containing the length. If you use streams, you'll have to use a block protocol. The reason for this is that I don't think ObjectInputStream is guaranteed to read the same number of bytes ObjectOutputStream writes to it (e.g., it could skip ending padding or such).
    Next, you'll need to create an object that can return more InputStream objects, one per stream written to the file.
    Not trivial, but that's how you'd do it.

  • How to append paragraph in text file of TextEdit application using applescript

    how to append paragraph in text file of TextEdit application using applescript and how do i save as different location.

    christian erlinger wrote:
    When you want to print out an escape character in java (java is doing the work in client_text_io ), you'd need to escape it.
    client_text_io.put_line(out_file, replace('your_path', '\','\\'));cheersI tried replacing \ with double slash but it just printed double slash in the bat file. again the path was broken into two lines.
    file output
    chdir C:\\DOCUME~1\
    195969\\LOCALS~1\\Temp\
    Edited by: rivas on Mar 21, 2011 6:03 AM

  • How to append report to log file?

    Hai,
    how to append the sqlplusw sql query output to a file.
    If we use spool, every time the file will be overwritten with new content and it won't append.
    Note:
    In batch program using >> this we can write content in to a file.
    But in sqlplus how to append the query output to same file.

    hello egyptian god of the sun,
    you didn't mention that you were using 9i. if that is the case, one way i can think of... if you're using unix (which again i assume as you mention batch scripts '>>') is to save your sql script in a .sql file and execute it within a shell script but redirecting output to your log file. you can append as you normally would.

  • Importing from XML to Excel - need to know how to append to existing Excel file

    Hello,
    I have several XML files that I will need to import into one Excel spreadsheet. I have been able to figure out how to import an XML file to an Excel file but when I import a second XML file, the contents of the second XML overwrite the Excel spreadsheet.
    I am looking for an option to append. Thanks in advance
    private void XmlToExcel(string xmlFilePath, string excelFilePath)
    object misValue = System.Reflection.Missing.Value;
    DataSet Trans_ds = new System.Data.DataSet();
    Trans_ds.ReadXml(xmlFilePath);
    Excel.Application excel = new Excel.Application();
    excel.Application.Workbooks.Add(true);
    System.Data.DataTable table = Trans_ds.Tables[0];
    Worksheet worksheet = (Worksheet)excel.ActiveSheet;
    Range excelRange = (Excel.Range)worksheet.get_Range("A" + worksheet.Rows.Count, Type.Missing);
    int lastRow = excelRange.get_End(XlDirection.xlUp).Row;
    int ColumnIndex = 0;
    int rowIndex = lastRow++;
    foreach (System.Data.DataColumn col in table.Columns)
    ColumnIndex++;
    excel.Cells[lastRow, ColumnIndex] = col.ColumnName;
    foreach (DataRow row in table.Rows)
    rowIndex++;
    ColumnIndex = 0;
    foreach (DataColumn col in table.Columns)
    ColumnIndex++;
    excel.Cells[rowIndex + 1, ColumnIndex] = row[col.ColumnName];
    worksheet.StandardWidth = 20.0;
    worksheet.SaveAs(excelFilePath, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);
    excel.Quit();
    releaseObject(worksheet);
    releaseObject(excel);

    See if this helps.  I opened the old excel file and added the new rows into the existing workbook.
    private void XmlToExcel(string xmlFilePath, string excelFilePath, Boolean append)
    object misValue = System.Reflection.Missing.Value;
    DataSet Trans_ds = new System.Data.DataSet();
    Trans_ds.ReadXml(xmlFilePath);
    Excel.Application excel = new Excel.Application();
    Excel.Workbook Bk = excel.Workbooks.Add(true);
    System.Data.DataTable table = Trans_ds.Tables[0];
    Excel.Worksheet worksheet = (Excel.Worksheet)excel.Worksheets[1];
    Excel.Range excelRange = (Excel.Range)worksheet.get_Range("A" + worksheet.Rows.Count, Type.Missing);
    int lastRow = excelRange.get_End(Excel.XlDirection.xlUp).Row;
    int ColumnIndex = 0;
    int rowIndex = lastRow++;
    foreach (System.Data.DataColumn col in table.Columns)
    ColumnIndex++;
    excel.Cells[lastRow, ColumnIndex] = col.ColumnName;
    foreach (DataRow row in table.Rows)
    rowIndex++;
    ColumnIndex = 0;
    foreach (DataColumn col in table.Columns)
    ColumnIndex++;
    excel.Cells[rowIndex + 1, ColumnIndex] = row[col.ColumnName];
    worksheet.StandardWidth = 20.0;
    if (append == false)
    worksheet.SaveAs(excelFilePath, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);
    else
    //open old workbook
    Excel.Workbook oldworkbook = (Excel.Workbook)excel.Workbooks._Open(
    excelFilePath,
    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
    Type.Missing, Type.Missing);
    //get first sheet in workbook
    Excel.Worksheet oldxlSht = (Excel.Worksheet)oldworkbook.Worksheets[1];
    //get column A of old worksheet to find last row in sheet
    Excel.Range xlRange = (Excel.Range)oldxlSht.get_Range(
    "A" + oldxlSht.Rows.Count, Type.Missing);
    int LastRow = xlRange.get_End(Microsoft.Office.Interop.Excel.XlDirection.xlUp).Row;
    int newrow = LastRow + 1;
    //get last row of new worksheet
    xlRange = (Excel.Range)worksheet.get_Range(
    "A" + oldxlSht.Rows.Count, Type.Missing);
    LastRow = xlRange.get_End(Microsoft.Office.Interop.Excel.XlDirection.xlUp).Row;
    // copy rows of new worksheet to old worksheet
    xlRange = (Excel.Range)worksheet.Rows["1:" + LastRow, Type.Missing];
    xlRange.Copy(oldxlSht.Rows[newrow, Type.Missing]);
    oldworkbook.Save();
    excel.Quit();
    releaseObject(oldxlSht);
    releaseObject(worksheet);
    releaseObject(excel);
    jdweng

  • How do I append a txt file? When I re-open, I cant append to the file.

    Trying to append a txt file but cant because of the header.
    How do i print to the file without the header?
    The Add Record Class
        private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {                                      
            int lengthIsbn = txtIsbn.getText().length(); //get lengths for validation
            int lengthSupplierno = txtSupplierno.getText().length();
            int lengthLastorderdate = txtLastorderdate.getText().length();
            if (lengthIsbn == 11){
                if (lengthSupplierno == 4){ //check validation
                    if (lengthLastorderdate == 8){      //Three If's because one can only have one error which cannot be specific!
                        // if passed validation then continue the add
                        bookRecord record;
                        try{
                            record = new bookRecord(
                                    txtIsbn.getText(),
                                    txtTitle.getText(),
                                    txtAuthor.getText(),
                                    Float.parseFloat(txtPrice.getText()),
                                    Integer.parseInt(txtSupplierno.getText()),
                                    txtLastorderdate.getText());
                            Output.writeObject(record);
                            System.out.println(record); // print record to check progress
                        } catch(IOException b){
                            JOptionPane.showMessageDialog(this, "Cannot Add Record Due To Input/Output Error!", "IO Error", JOptionPane.ERROR_MESSAGE);
                        } catch(NumberFormatException d){
                            JOptionPane.showMessageDialog(this, "Cannot Add Record Due To Incorrect Formatting Of Data In Text Boxes, Please Check That Price And Supplier No Are Numeric!", "Number Format Error", JOptionPane.ERROR_MESSAGE);
                        } catch(NullPointerException e){
                            JOptionPane.showMessageDialog(this, "Cannot add Record Due To Absence Of Database!", "Null Pointer Error", JOptionPane.ERROR_MESSAGE);
                    } else {JOptionPane.showMessageDialog(this, "Last Order Date Must Be In This Format (01/01/01)", "Validation Error", JOptionPane.ERROR_MESSAGE);}
                } else {JOptionPane.showMessageDialog(this, "Supplier No Must Be A Four Digit Integer", "Validation Error", JOptionPane.ERROR_MESSAGE);}
            } else {JOptionPane.showMessageDialog(this, "ISBN Must Have 11 Characters", "Validation Error", JOptionPane.ERROR_MESSAGE);}
        }                    I dont know whats wrong...

    1) You append to a file by passing true for the append argument to the constructor for the FileOutputStream or FileWriter.
    2) I have no idea what you mean by this: Trying to append a txt file but cant because of the header. How do i print to the file without the header?
    3) You're saying it's a txt file, but you're calling Output.writeObject(record). If Output is an ObjectOutputStream, (that is, you're serializing record) then it's not a text file.
    4) Variable names conventionally start with lowercase in Java, so Output should be output. (Unless Output is a class name and writeObject is a static method.)

  • How to append Target File(reciever side) .

    Hi PI Gurus,
    I have a scenario where i need to append the target file. It goes like this:
    files(idoc's) keep coming from the source at any time of the day.
    target file is sent only once in a day. The target file is appended each time a new source file recieved.
    Need to do this without using BPM.
    Pls help me  out.
    Thanks in advance.

    Hi Pankaj,
    Kindly go through the following link which will help you surely:
    http://help.sap.com/saphelp_nwpi711/helpdata/en/44/6830e67f2a6d12e10000000a1553f6/content.htm
    In the receiver file adapter, go to the Processing tab page. Then  Select the File Construction Mode as Append. Look at the link for the other configurations in the adapter.
    You can also take a look at the scenario 2 in the following link:
    http://wiki.sdn.sap.com/wiki/display/XI/MorewiththeFileAdapter
    Hope it helps you!!!!!
    Thanks
    Biswajit
    Edited by: 007biswa on Feb 21, 2011 5:39 PM

Maybe you are looking for

  • Assign the Asset "Tag Number" at PO receipt stage

    Our customer has a requirement to enter the Asset Tag Number for an item when the purchase order is receipted (or even at inspection stage for 4-way match PO's). The tag number entered, should then flow through to the FA module. Does anyone know if t

  • How to execute ODI scenarios from command line in Unix

    Hi Friends, I am using ODI 11g. I want to execute ODI senarios using the command line argument in Unix. Please let me know how to proceed with this. Thanks, Lony

  • New iphone 4s shut off and will not turn on or charge

    I just upgraded to an iphone 4s yesterday. I installed 6 OS last night. Woke up this morning and took 5 pictures of my kids and sent a text. I went back a few hours later to check for return text and the phone is not responding. I have tried plugging

  • ITunes 10.5 on Win7x64 will not sync my iPhone 4 (IOS5) with Wi-Fi .

    Diagnostics shows red-light for Internet (my Internet works on all other).  I have tried everything on this thread: https://discussions.apple.com/thread/3383549?start=0&tstart=0 After a week of this I am out of "ideas".  Please help.

  • Hyperin analyzer unable to list the databases from  Essbase

    Hi , We are using Hyperion Analyzer 7.2 , I have an issue while connecting to Essbase databases. As mentioned int he document I went Administrator tools go to Repostiory tab , File-> New -> database connection-> Essbase Now I gave the credentials of