How to Read from two file and write to another file --Please help !!

Hi all,
Please suggest me where i'm goin goin wrng.
I have 2 flat files. one of them is the main file(Ann.dat) has a about 150,000 lines (each line has unique ID from 00001 to 45000) of data and the the other(Miss.dat) has a just a list of IDs that are no longer in use & have to be deleted from the first file(NewAnn.dat). (Note that Ann.dat is a tab delimitted file and Miss.dat is just a list of all invalid IDs)
Below is my code. It doesn't do what I'm supposed to. Please suggest me or help me with a code to do it. What I'm trying to do is read each of the lines from the 2 files compare the ID in ann.dat with all the IDs in Miss.dat & if it doesn't match with the ID in Miss.dat write the whole line to NewAnn.dat. And do the rest with all the lines in Ann.dat.
It could be a real dumb question. since i'm not a software professional, I consider myself to be newbie to programming. I desperately need your help.
import java.io.*;
import java.util.*;
public class anntemp{
     public static void main(String[] args)
          String keyAnn ="";
          String keyMis="";
          String recAnn =null;
          String recMis =null;
          try{               
          FileReader fr=new FileReader("C:\\Tom\\Ann.dat");
          BufferedReader br=new BufferedReader(fr);
          int couter=0;
          while ((recAnn = br.readLine())!=null)
               couter++;
               keyAnn = recAnn.substring(0, recAnn.indexOf("\t"));
          FileReader fr1=new FileReader("C:\\Tom\\Miss.dat");
          BufferedReader br1=new BufferedReader(fr1);
          while((recMis = br1.readLine())!=null){
          keyMis = recMis.substring(0, recMis.indexOf("\t"));
               if(keyAnn.equals(keyMis)){
     FileWriter fw=new FileWriter("C:\\Tom\\NewAnn.dat",true);
     BufferedWriter bw=new BufferedWriter(fw);
     PrintWriter pw=new PrintWriter(bw);
     StringBuffer writeValue = new StringBuffer();
     writeValue.append(recAnn);
                                             pw.println(writeValue.toString());
     pw.flush();
          }catch (Exception expe){
               System.out.println("In Exception ");
               expe.printStackTrace();
Thank you all in advance,
br

I think you need to close the files when you are done in the inner loop. Plus I think you'll be overwritting the file in the inner loop if more than one match. It might be easier to read the unused id file into a map at the start, and then loop up the id's from the master file in the map. You can put the unused id's in as the keys, and a Boolean.TRUE as the value (value won't matter). Then just check if the map contains the key for the id read from the master file. That should cut down on disk activity. This assumes the unused id file is smallish.

Similar Messages

  • How to read from one file and write into another file?

    Hi,
    I am trying to read a File and write into another file.This is the code that i am using.But what happens is last line is only getting written..How to resolve this.the code is as follows,
    public String get() {
         FileReader fr;
         try {
              fr = new FileReader(f);
              String str;
              BufferedReader br = new BufferedReader(fr);
              try {
                   while((str= br.readLine())!=null){
                   generate=str;     
              } catch (IOException e1) {
                   e1.printStackTrace();
              } }catch (FileNotFoundException e) {
                   e.printStackTrace();
         return generate;
    where generate is a string declared globally.
    how to go about it?
    Thanks for your reply in advance

    If you want to copy files as fast as possible, without processing them (as the DOS "copy" or the Unix "cp" command), you can try the java.nio.channels package.
    import java.nio.*;
    import java.nio.channels.*;
    import java.io.*;
    import java.util.*;
    import java.text.*;
    class Kopy {
         * @param args [0] = source filename
         *        args [1] = destination filename
        public static void main(String[] args) throws Exception {
            if (args.length != 2) {
                System.err.println ("Syntax: java -cp . Kopy source destination");
                System.exit(1);
            File in = new File(args[0]);
            long fileLength = in.length();
            long t = System.currentTimeMillis();
            FileInputStream fis = new FileInputStream (in);
            FileOutputStream fos = new FileOutputStream (args[1]);
            FileChannel fci = fis.getChannel();
            FileChannel fco = fos.getChannel();
            fco.transferFrom(fci, 0, fileLength);
            fis.close();
            fos.close();
            t = System.currentTimeMillis() - t;
            NumberFormat nf = new DecimalFormat("#,##0.00");
            System.out.print (nf.format(fileLength/1024.0) + "kB copied");
            if (t > 0) {
                System.out.println (" in " + t + "ms: " + nf.format(fileLength / 1.024 / t) + " kB/s");
    }

  • How do I read from one table and write to another identical table?

    I am very new to Oracle. I am trying to do something that should be very simple.
    I am trying to read from one table in SQL and then write to another
    Identically formatted table. I keep getting various errors. Could someone please
    post some vey simple code that will work so that I can play around with it?
    Any help would be greatly appreciated.
    Thanks,
    Ron

    Thanks, but I must be missing something.
    I have two tables, SONGLIST and SETLIST.
    The second line by itself works just fine on either table.
    Here is the code I used following your seggestion, along with it's error message.
    Hope you can help. Thanks again...
    INSERT INTO SETLIST
    SELECT TITLE FROM SONGLIST WHERE ROTATION <> 'X'
    ORA-00947: not enough values

  • How can I extract certain pages from my document and save as another file?

    How can I extract certain pages from my document and save as another file?

    You would need Adobe Acrobat to do that, not Adobe Reader.

  • Read from Oracle DB and Write to MySQL

    Hi All,
    I am fairly new to database administration, so please bear with me if this is something that is simple or not achievable at all -
    SetUp:
    I have an Oracle DB on one dedicated Server, to which I only have a read_only access.
    I have a MySQL database setup on a windows server 2008, both are on the company network and accessible to internal employees only.
    Problem Statement:
    I need to read certain tables from Oracle DB and push the records to MySQL database.
    I have a stored procedure which was doing this but from one Oracle Schema to another, which is running fine, now I need to use the same stored procedure but read from one database (Oracle) and write to another database (MySQL), is there a way to do this through the stored procedure, I know I can write a java program to do this, but need to do it through a stored procedure.
    Appreciate any help in this regards.

    c5b4a91d-d35a-43ba-ac96-6d1821541d33 wrote:
    Hi All,
    I am fairly new to database administration, so please bear with me if this is something that is simple or not achievable at all -
    SetUp:
    I have an Oracle DB on one dedicated Server, to which I only have a read_only access.
    I have a MySQL database setup on a windows server 2008, both are on the company network and accessible to internal employees only.
    Problem Statement:
    I need to read certain tables from Oracle DB and push the records to MySQL database.
    I have a stored procedure which was doing this but from one Oracle Schema to another, which is running fine, now I need to use the same stored procedure but read from one database (Oracle) and write to another database (MySQL), is there a way to do this through the stored procedure, I know I can write a java program to do this, but need to do it through a stored procedure.
    Appreciate any help in this regards.
    Start here:  http://docs.oracle.com/cd/E11882_01/server.112/e25494/ds_concepts.htm#i1007709

  • Reading 8kb tiff image and then writing into backend. please help

    Hi All, Please Help ..
    My aim is to read a tiff image which of 8kb 1732x717 size, and then store it into backend.
    what I did is read the image into bufferedImage and then used tiffencodeparam with compression_none but the problem is size is too much after encoding.
    code sample
    BufferedImage image = ImageIO.read(tiff_filename); to read tiff image
    to write tiff image
    TiffEncodeParam p = new TiffEncodeParam();
    p.setCompression(TiffEncdeParam.COMPRESSION_NONE);
    FileOutputStream out = new FIleOutputStream(tiff_filename);
    ImageEncoder e = ImageCodec.createImageEncoder(""TIFF,out,p);
    e.encode(image);
    out.close();

    I got all my pictures AND everything else back, folders, ratings, keywords etc
    Fortunately I had a backup of the entire iPhoto library folder, it was about 3 months old (I know shame on me) so I didn't want to just use the entire backup folder and lose 3 months of photos.
    So I just copied the AlbumData.xml file and the Library6.iPhoto file. PRESTO all my pictures were back WITH all the folders,keywords etc, etc intact!! (up till the 3 month old backup point).
    Then I just re-imported the missing 3 months worth of pictures from the original folder in the iphoto library folder. So all I had to recreate was 3 months worth of customization. WHEW!!
    Reading through the discussions it seems there is a fair number of users where iPhoto would go empty, but they knew the images were still on the computer. I am not a programmer, but it seems silly to me the their are files that get re-written everytime iPhoto closes....computers crash. and then what happens to the files? Mine got corrupted, lesson learned BACKUP more frequently!!
    Thanks to Old Toad who steered me to the Library6.iPhoto as a possible troublemaker in another thread!

  • I was updating to OS5 and instead my iPhone went back to factory settings. Now the iPhone doesnt read my sim card and cannot be configured. Please help

    I was updating to OS5 and instead my iPhone went back to factory settings. Now the iPhone doesnt read my sim card and cannot be configured. Please help

    Nothing happened, i managed to get my computer to recognise it and now restoring... but it says 3 hours remaining?! Will i lose everything?

  • How to read XML file and write into another XML file

    Hi all, I am new to JAVAXML.
    My problem is I have to read one XML file and take some Nodes from that and write these nodes into another XML file...
    I solved, how to read XML file
    But I don't know how to Write nodes into another XML.
    Can anyone help in this???
    Thanks in advance..

    This was answered a bit ago. There was a thread called "XML Mergine" that started on Sept 14th. It has a lot of information about what it takes to copy nodes from one XML Document object into another.
    Dave Patterson

  • How to retrieve characters like '£' from the database and write to xml file

    Hi ,
    I have a requirement to retrieve the data from database and write to files in XML format.
    I am able to do so successfuly by using XMLElement tag and writing to file through UTL_File package.
    All characters like <&@^ get converted properly, but when it comes to multibyte chars like '£', they are not able to get converted as it is.
    Can somebody please advise me how to go ahead.
    Regards

    Thanks odie.
    The nls_charset for my database is WE8ISO8859P1 and database version is Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - 64bi.
    The data (with pound sign) is sitting in one of the columns of the table and when i query it directly, I am able to view it properly.
    However when I use the below code to retrieve in XML format and print it to file, it gets changed. This file is also passed to one of the application GUI where this XML gets processsed and it is not visible properly.
    below id the sample abstract of code I am using.
    Declare
    l_file UTL_FILE.FILE_TYPE;
    l_clob CLOB;
    l_buffer VARCHAR2(32767);
    l_amount BINARY_INTEGER := 32767;
    l_pos INTEGER := 1;
    Begin
    SELECT XMLElement("case",
    XMLElement("comments",
    XMLElement("comment",
    XMLElement("comments",a.COMMENTS)
    ).getClobVal() val1 into l_clob
    FROM TO_COMMENTS a
    l_file :=
    UTL_FILE.fopen (XMLDIR,
    test.xml,
    'w',
    32767);
    LOOP
    DBMS_LOB.read (l_clob,
    l_amount,
    l_pos,
    l_buffer);
    UTL_FILE.put_line (l_file, l_buffer);
    l_pos := l_pos + l_amount;
    END LOOP;
    EXCEPTION
    WHEN NO_DATA_FOUND THEN
    DBMS_OUTPUT.NEW_LINE('Reached end of file');
    END;
    The comments column given contains the character like pound.
    And once the file is generated and i see using the vi editor, the char is not viewable properly like £
    And when the same is passed to GUI application to be processed, its not viewable propely in GUI from IE as well like �.

  • HOW TO RETRIEVE A LONG RAW COLUMN FROM A TABLE AND WRITE TO OS FILE

    Good evening.
    Please how can I read a long raw datatype from a table and insert into an operating system file using PL/SQL.
    Thank you.

    What does this have to do with LONG RAW? It is about UTL_FILE and not especially great code.
    The question is how to retrieve and write LONG RAW and that is quite a different matter.
    First you must convert it to BLOB.
    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:13213885403654
    Then you can write it out to the file system
    http://www.morganslibrary.org/reference/utl_file.html
    Look at the "Extract Blob" demo

  • How can I read, millions of records and write as *.csv file

    I have to return some set of columns values(based on current date) from the database (could be million of record also) The dbms_output can accomodate only 20000 records. (I am retrieving thru a procedure using cursor).
    I should write these values to a file with extn .csv (comma separated file) I thought of using a utl_file. But I heard there is some restriction on the number of records even in utl_file.
    If so, what is the restriction. Is there any other way I can achive it? (BLOB or CLOB ??).
    Please help me in solving this problem.
    I have to write to .csv file, the values from the cursor I have concatinated with "," and now its returning the value to the screen (using dbms_output, temporarily) I have to redirect the output to .csv
    and the .csv should be in some physical directory and I have to upload(ftp) the file from the directory to the website.
    Please help me out.

    Jimmy,
    Make sure that utl_file is properly installed, make sure that the utl_file_dir parameter is set in the init.ora file and that the database has been re-started so that it will take effect, make sure that you have sufficient privileges granted directly, not through roles, including privileges to the file and directory that you are trying to write to, add the exception block below to your procedure to narrow down the source of the exception, then test again. If you still get an error, please post a cut and paste of the exact code that you run and any messages that you received.
    exception
        when utl_file.invalid_path then
            raise_application_error(-20001,
           'INVALID_PATH: File location or filename was invalid.');
        when utl_file.invalid_mode then
            raise_application_error(-20002,
          'INVALID_MODE: The open_mode parameter in FOPEN was
           invalid.');
        when utl_file.invalid_filehandle then
            raise_application_error(-20002,
            'INVALID_FILEHANDLE: The file handle was invalid.');
        when utl_file.invalid_operation then
            raise_application_error(-20003,
           'INVALID_OPERATION: The file could not be opened or
            operated on as requested.');
        when utl_file.read_error then
            raise_application_error(-20004,
           'READ_ERROR: An operating system error occurred during
            the read operation.');
        when utl_file.write_error then
            raise_application_error(-20005,
                'WRITE_ERROR: An operating system error occurred
                 during the write operation.');
        when utl_file.internal_error then
            raise_application_error(-20006,
                'INTERNAL_ERROR: An unspecified error in PL/SQL.');

  • CAN AN EXCEL XLSM FILE READ FROM A CSV AND WRITE BACK TO THE SAME XLSM -VBA

    Hey Carlos- Here's the repost. 
    Could an XLSM file read a line from a CSV file in "A1" and depending on what was in the first column in the XLSM, search the CSV file and find the indexed item in the second column or third? I've done it before with standard VLookup functions and it was cumbersome and very slow, and for some reason, everytime I would save the file it would take forever although the xls file was a single sheet.
    i've attacthed a sketch of what I'm talking about, because it's hard to explain and I think the sketch explains it better. Here it is, sorry if it is blurry, it looked fine before I posted:

    ok, use this version, I changed it a bit. To accommodate the issue with the single cell, I moved the main procedures to a function for a more efficient use.
    Sub xlsmCsvLookup()
        'have both your xlsm and your csv files open
        'in the xlsm file, select a range of cells to look up
        'run the script to search all selected cells and get the values from the csv file
        Dim csvDataRange As Range 'csv file data column
        Dim selRange As Range 'to hold selected cells
        Dim foundRange As Range
        'get the source range
        Set csvDataRange = Workbooks("Book2.csv").Sheets(1).Range("a:a") ' replace "Book2" with yourCSVfile.csv
        'check for selection, only one cell, ceck that cell and exit, otherwise loop thru selection
        If Selection.Count > 1 Then
            'loop thru all selected cells, ignore empty cells
            For Each selRange In Selection.SpecialCells(xlCellTypeConstants)
                findSelection selRange, csvDataRange
            Next
        Else
            findSelection ActiveCell, csvDataRange
        End If
        Set foundRange = Nothing
        Set selRange = Nothing
        Set csvDataRange = Nothing
    End Sub
    Function findSelection(selRange, csvDataRange)
            'try to find it in the csv file
            Set foundRange = csvDataRange.Find(selRange) 'if found, assign it to foundRange
            'if no match highligh cut
            If foundRange Is Nothing Then
                selRange.Interior.ColorIndex = 34
            Else
                'if found, get the value in next cell
                selRange.Offset(0, 1) = foundRange.Offset(0, 1)
            End If
    End Function

  • How to read a mixed text and binary random-access file?

    I have a PDF file which I want to decode. The format is a mixture of binary data and text. What I need is to position the file to a particular position, and then to read from that point as a stream either a set of binary bytes or straight ASCII text. I can't see how to do this (if in fact it's possible).
    I can open the file as a SeekableByteChannel and position it, but opening a stream repositions the file to the beginning - just what I don't want.
    Is there any way of opening a stream from part-way through a file?

    I think that I gave this topic a rather misleading title. What it really should be is "How to turn a random access file into a stream"?
    I realise that I can open an InputStream and skip the relevant number of characters - but this is highly inefficient on a large file where I will skipping about within the file. I need a stream so that I can apply other stream functions to it - buffering in memory will I suspect be too big.

  • How to read from two boards at the same time

    I have two NI DAQ Boards, a PCI 6034E and a PCI 6025E I want to make one a master and one a slave and read from both at the same time. Do they need jumpers between them
    from one board to the other or does the motherboard bus take care of that? I can find software to handle this but I can't find anything on the way the hardware should be configured, is there a cable I need between them?

    Hi,
    We have a couple of great tutorials on this:
    http://zone.ni.com/devzone/conceptd.nsf/webmain/6DC991028566309886256F990080A720
    http://zone.ni.com/devzone/conceptd.nsf/webmain/2638A8DA4E4CFD1F86256D250070C093?opendocument
    -Sal

  • TS3999 HELP my work calender has vanished from the icloud and i cant find it PLEASE HELP I AM DESPERATE!

    HELP! I have my calender on my iphone saved and updated on the icloud, today it has vanished!!!!!!!!!!!!!!
    No idea how or why, please help!

    Go to settings>icloud and turn off calendars.  Then turn on again.  That might bring them back.
    If not, test the account by using a browser to log into icloud.com and go to the calendar page.  If not there, then for whatever reason, they're gone.  You might try performing a restore from an icloud backup, if you have that turned on.

Maybe you are looking for

  • Workflow 2010 set list item permissions

    I have a sharepoint 2013 list set up with two kinds of users (Approver and Employees) needing access: Approvers - need full control on the list/site Employees - can only have edit/read access to their own list item or entry I'm using SPD 2013 with wo

  • How to set and retrive the index log path stored by parameter LOG_DIRECTORY

    how to set and retrive the index log path stored by parameter LOG_DIRECTORY.

  • Vga for t5240

    hi . we have server sun sparc t5240. we have no vga in server. is possible we operate the server graphically . thanx.

  • FORMS - FRM-40735 ERROR

    Hi. I've created a new application which provides the customer's commercial analysis. There are 3 text-items in my form where user fill them with the following: Establishment, Customer_id and the Period(in days) for the consulting. After that the 'ke

  • Error Message when importing pdf documents.

    When trying to import pdf document to form central, I receive an error message stating that form central could not import pdf documents because it contains no form fields. I don't know what the error message is referring to. Can someone  help with th