Saving multiple records into text file

Can I save multiple records into a text file at one go?
My application has a list of data displayed there and when the user clicks on the save button it will save all the records on the screen.
It works but it only saves the last record.
Here are my codes
// this is to display the list of data
private JLabel[] subjects=new JLabel[20];
private JLabel[] subTotal=new JLabel[20];
private JLabel[] codes=new JLabel[20];
private JLabel[] getTotal=new JLabel[20];
String moduleCodes;
String getPrice;
double price;
int noOfNotes;
public testapp(Subjects[] subList)
int j=0;
            double CalTotal=0;
          for (int i=0; i<subList.length; i++)
               subjects[i] = new JLabel();
               subTotal[i] = new JLabel();
               codes=new JLabel();
               getTotal[i]=new JLabel();
               if (subList[i].isSelected)
                    System.out.println(i+"is selected");
                    subjects[i].setText(subList[i].title);
                    subjects[i].setBounds(30, 140 + (j*30), 400, 40);
                    subTotal[i].setText("$"+subList[i].price);
                    subTotal[i].setBounds(430,140+(j*30),100,40);
                    codes[i].setText(subList[i].code);
                    getTotal[i].setText(subList[i].price+"");
                    CalTotal+=subList[i].price;
                    contain.add(subjects[i]);
                    contain.add(subTotal[i]);
                    j++;
                    moduleCodes=codes[i].getText();                              
                    getPrice=getTotal[i].getText();
                    noOfNotes=1;
// this is where the records are saved
     public void readRecords(String moduleCodes,String getPrice,int notes)throws IOException
          price=Double.parseDouble(getPrice);
          String outputFile = "testing.txt";
          FileOutputStream out = new FileOutputStream(outputFile, true);      
     PrintStream fileOutput = new PrintStream(out);
          SalesData[] sales=new SalesData[7];
          for(int i=0;i<sales.length ;i++)
               sales[i]=new SalesData(moduleCodes,price,notes);
               fileOutput.println(sales[i].getRecord());
          out.close();

I suggest writing a method that takes a SalesData[]
parameter and a filename. Example:
public void writeRecords(SalesData[] data,
String filename) throws IOException
BufferedWriter out = new BufferedWriter(new
FileWriter(filename, true));
for (int i = 0; i < data.length; i++)
out.write(data.getRecord());
out.newLine();
out.close();
And it's good to get in the habit of doing things like closing resources in finally blocks.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Similar Messages

  • Saving multiples objects into a file

    I want to create a single file that has multiples things inside, like pictures (png) and texts. Does someone knows how it will be the structure of the binary file?
    I'm programming a draw software like photoshop, where my layers are BufferedImages. Theses bufferedImages must be saved into a file to re-open later and edit.
    Please I want just ideas....
    thanks

    If the objects that you store in your file are fairly independent of each other, one thing that comes
    to mind is to make your file a zip file of component files. That way you can use standard tools to examine
    it and edit it if you wish.
    Another thing to note is that if your file is largely a series of images, some image file formats,
    like tiff , jpeg and gif allow you to store sequences of images in one file.
    Here's a demo that creates a tiff file holding four images, then reads the file and displays the images.
    Stardard software like Kodak's "Imaging Preview" will allow you to flip through the images in the file.
    By the way, if you don't have readers/writers for format tiff, you can get them here.
    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.imageio.*;
    import javax.imageio.stream.*;
    import javax.swing.*;
    public class IOExample {
        public static void main(String[] args) throws IOException {
            String urlPrefix = "http://www3.us.porsche.com/english/usa/carreragt/modelinformation/experience/desktop/bilder/icon";
            String urlSuffix = "_800x600.jpg";
            int SIZE = 4;
            BufferedImage[] images = new BufferedImage[SIZE];
            for(int i=1; i<=SIZE; ++i)
                images[i-1] = ImageIO.read(new URL(urlPrefix + i + urlSuffix));
            File file = new File("test.tiff");
            file.delete();
            int count = writeImages(images, file);
            if (count < SIZE)
                throw new IOException("Only " + count + " images written");
            images = null;
            images = readImages(file);
            if (images.length < SIZE)
                throw new IOException("Only " + images.length + " images read");
            display(images);
        public static void display(BufferedImage[] images) {
            JFrame f = new JFrame("IOExample");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel p = new JPanel(new GridLayout(0,1));
            for(int j=0; j<images.length; ++j) {
                JLabel label = new JLabel(new ImageIcon(images[j]));
                label.setBorder(BorderFactory.createEtchedBorder());
                p.add(label);
            f.getContentPane().add(new JScrollPane(p));
            f.setSize(400,300);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        //suffix is "jpeg", "gif", "png", etc... according to your service providers
        public static ImageWriter getWriter(String suffix) throws IOException {
            Iterator writers = ImageIO.getImageWritersBySuffix(suffix);
            if (!writers.hasNext())
                throw new IOException("no writers for suffix " + suffix);
            return (ImageWriter) writers.next();
        public static ImageReader getReader(String suffix) throws IOException {
            Iterator readers = ImageIO.getImageReadersBySuffix(suffix);
            if (!readers.hasNext())
                throw new IOException("no reader for suffix " + suffix);
            return (ImageReader) readers.next();
        public static int writeImages(BufferedImage[] sources, File destination) throws IOException {
            if (sources.length == 0) {
                System.out.println("Sources is empty!");
                return 0;
            } else {
                ImageWriter writer = getWriter(getSuffix(destination));
                ImageOutputStream out = ImageIO.createImageOutputStream(destination);
                writer.setOutput(out);
                writer.prepareWriteSequence(null);
                for(int i=0; i<sources.length; ++i)
                    writer.writeToSequence(new IIOImage(sources, null, null), null);
    writer.endWriteSequence();
    return sources.length;
    public static BufferedImage[] readImages(File source) throws IOException {
    ImageReader reader = getReader(getSuffix(source));
    ImageInputStream in = ImageIO.createImageInputStream(source);
    reader.setInput(in);
    ArrayList images = new ArrayList();
    GraphicsConfiguration gc = getDefaultConfiguration();
    try {
    for(int j=0; true; ++j)
    images.add(toCompatibleImage(reader.read(j), gc));
    } catch(IndexOutOfBoundsException e) {
    return (BufferedImage[]) images.toArray(new BufferedImage[images.size()]);
    public static String getSuffix(File file) throws IOException {
    String filename = file.getName();
    int index = filename.lastIndexOf('.');
    if (index == -1)
    throw new IOException("No suffix given for file " + file);
    return filename.substring(1+index);
    //make compatible with gc for faster rendering
    public static BufferedImage toCompatibleImage(BufferedImage image, GraphicsConfiguration gc) {
    int w = image.getWidth(), h = image.getHeight();
    int transparency = image.getColorModel().getTransparency();
    BufferedImage result = gc.createCompatibleImage(w, h, transparency);
    Graphics2D g = result.createGraphics();
    g.drawRenderedImage(image, null);
    g.dispose();
    return result;
    public static GraphicsConfiguration getDefaultConfiguration() {
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice gd = ge.getDefaultScreenDevice();
    return gd.getDefaultConfiguration();

  • Problem with data saving into text file

    Hi,
    The problem I am facing wihile saving the data into text file is that everytime when I am slecting the path from front panel, the data which is being saved is appended with the previous data, i.e. not only in the new text file, the new set of data is saved but also, if there is any previuos run for the program, the corresponding data is also present in that text file.
    However, when I change the same 'control'(file path) to 'constant' in the block diagram, and add the file path, there is no such problem. Basically, changing the "File path" from constant in the block diagram to control (so that it is displayed in the front panel) is causing the problem.
    Please help!
    Thanks 
    Solved!
    Go to Solution.
    Attachments:
    front panel.JPG ‏222 KB
    Block Diagram.JPG ‏70 KB
    Block diagram with File Path as Constant.JPG ‏74 KB

    Your shift register on the For loop is not initialized. It will retain the value of the string from the last time it executed. Initialize that and it should solve your problem.
    Mark Yedinak
    "Does anyone know where the love of God goes when the waves turn the minutes to hours?"
    Wreck of the Edmund Fitzgerald - Gordon Lightfoot

  • How do I add multiple text block records from text file?

    The data manager documentation (page 151) for MDM 5.5 SP3 indicates that one or more new text blocks can be added to the Text Blocks object table from files. It is noted that the files must be plain text files.
    I use notepad and create a text file with two lines as follows:
    Test 1
    Test 2
    When I try to add the text blocks following documentation mentioned above, it only adds one record for the Data Group I have chosen and the record contains the entry "Test 1" from the first line in the text file.
    How can I add multiple records to the data group from a file?

    From my testing it appears that you need to have one text file per text block record in Data Manager.
    I wrote VBA macro to so that I could input my text blocks into an Excel spreadsheet and then the macro will take the contents of each cell in a highlighted column and create one text file per cell.
    Then using Data manager, I can select all of the text files at once and it will import them, creating one record per text file.

  • Splitting of a CSV File with Multiple Records into Multiple XML File

    Dear All,
    <b> I am doing a Scenario of CSV to XML Files. I am using BPM for the same. My incoming CSV File has got multiple records. I want to break this Multiple records into Multiple XML Files having one record each.</b>
    Can someone suggest how can I break this rather Split this into Multiple XML Files.
    Is Multimapping absoltely necesaary for this. Can't we do this without Multimapping. Can we have some workaround in the FCC parameters that we use in the Integration Directory.
    Kindly reply ASAP. Thanks a lot to all in anticipation.
    Pls Help.
    Best Regards
    Chakra and Somnath

    Dear All,
    I am trying to do the Multimapping, and have 0....unbounded also. Someways it is not working.
    <b>
    Smitha please tell me one thing...Assigning the Recordsets per Message to 1, does it mean that it will write multiple XML Files as I want.</b>
    Also I am usinf Set to Read only. So once the File is read it becomes RA from A. Then will it write the other Records.
    I have to use a BPM because there are certain dependencies that are there for the entire Process Flow. I cannot do without a BPM.
    Awaiting a reply. Thanks a lot in anticipation.
    Best Regards
    Chakra and Somnath

  • How do I add multiple images into one file?

    I'm sure this is something that's been covered in another post (or even in the help portal) but I think my wording in my search terms are not correct or... I don't know, because I just can't find what I'm looking for.
    I want to know how to add multiple images into one file/one image, both horizontally and/or vertically. To give you an idea of what I mean, check out :
    http://www.best10apps.com/apps/comic-story,531596060.html
    If you scroll down, you'll see a heading entitled : Screenshots of Comic Story. Notice how there's 3 pictures (divided by borders). 2 of those pictures are side by side, and 1 of them is below the first 2 pictures.
    I want to know how to add different pictures/images and put them into one picture.

    One way is to create template PSD files and populate them with your images using Photoshops scripts.
    Photo Collage Toolkit UPDATED June 12, added Picture Package Support via PasteImageRoll and BatchPicturePackage scripts.
    The package includes four simple rules to follow when making Photo Collage Template PSD files so they will be compatible with my Photoshop scripts.
    There are eleven scripts in this package they provide the following functions:
    TestCollageTemplate.jsx - Used to test a Photo Collage Template while you are making it with Photoshop.
    CollageTemplateBuilder.jsx - Can build Templates compatible with this toolkit's scripts.
    LayerToAlphaChan.jsx - Used to convert a Prototype Image Layer stack into a template document.
    InteractivePopulateCollage.jsx - Used to interactively populate Any Photo Collage template. Offers most user control inserting pictures and text.
    ReplaceCollageImage.jsx - use to replace a populated collage image Smart Object layer with an other image correctly resized and positioned.
    ChangeTextSize.jsx - This script can be used to change Image stamps text size when the size used by the populating did not work well.
    PopulateCollageTemplate.jsx - Used to Automatically populate a Photo Collage template and leave the populated copy open in Photoshop.
    BatchOneImageCollage.jsx - Used to Automatically Batch Populate Collage templates that only have one image inserted. The Collage or Image may be stamped with text.
    BatchMultiImageCollage.jsx - Used to Automatically Batch Populate Any Photo Collage template with images in a source image folder. Easier to use than the interactive script. Saved collages can be tweaked.
    BatchPicturePackage.jsx - Used to Automatically Batch Populate Any Photo Collage template with an image in a source image folder
    PasteImageRoll.jsx - Paste Images into a document to be print on roll paper.
    Documentation and Examples

  • Scaning multiple pages into one file on a 4630

    Using HP 4630 printer, windows 8.1, wireless connection.
    Want to scan multiple pages into one file.
    Per user manual, I work from the computer not the printer.
    When first page is scanned am asked if I want to save, I click yes and name file.
    When I scan second page am again asked if I want to save, my file name appears, I am told it already exists and asks if I want  to keep or replace it.
    Whichever one I click, only the second page is saved.
    What am I doing wrong?
    Question: How do I scan mutiple pages into a single document?
    This question was solved.
    View Solution.

    I accept this solution with many thanks!  It was so obvious and I didn't see it.  The User Manual should mention this.

  • Concatenate multiple records into one single record

    Hello everyone,
    Can anyone guide me how to merge multiple records into one single record
    like......... I am getting the data in the file like
    aaaaa/bbbbbbb/ccccccccccc/dddddddddddd/eee
    ffffff/gggg/hhhhhhhhhhhhhh
    /123/4567/55555/99999999/kaoabfa/eee
    fffff/kkkkkkkk/llllllllllllllllllllllll
    when i use gui_upload I am getting the data into the internal table in the above format.
    My main intension is to split the record at / to multiple lines and dowload it into another file.
    What i am planning to do is... if the line does not start with / then i want to concatenate the multiple lines into single line and then split it into multiple records. Can anyone guide me how to achieve this.

    Yes, it should work.
    In my example
    Loop at itab.
    concatenate i_text itab into i_text.
    endloop.
    You change that loop for the loop of your internal table with the file records
    So if you have this three records
    'aaaa/bbb/ccc'
    '/dddd/efg'
    'hijk/lmn'
    i_text will look like this at the end
    'aaaa/bbb/ccc/dddd/efghijk/lmn'
    then in this part of the code
    split i_text at '/' into table itab2.
    itab2 will have the records looking like this
    aaaa
    bbb
    ccc
    dddd
    efghijk
    lmn'

  • Writing records to text file

    Hi. I have a query that retrieves data in a table. however when writing into text file, I have some troubles aligning the records.
    In below example, how would align the data against its header?? thanks!
    As you see my data below is messed up =(
    Ex.
    Reference No. Name Phone No.
    012-066-121127-00227 MARIE LIM JOSEPH     2921786     
    013-318-130222-04992 NANCY SMITH     0170005486

    989873 wrote:
    Hi. I have a query that retrieves data in a table. however when writing into text file, I have some troubles aligning the records.
    In below example, how would align the data against its header?? thanks!
    As you see my data below is messed up =(
    Ex.
    Reference No. Name Phone No.
    012-066-121127-00227 MARIE LIM JOSEPH     2921786     
    013-318-130222-04992 NANCY SMITH     0170005486you need to fix your code;
    consider using LPAD or RPAD as appropriate

  • Is there any way to download smartform into text file

    is there any way to download smartform into text file

    Hi,
    No you cant save a smart form into text file but you can store it in a XML file.
    Goto menu Utilities --> select More Utilities --> select Upload/Download --> click Download and give the path to save the backup for smartform.
    Now you smartform is saved to XML file at your PC.
    Also you can upload this smartform.
    Hope this helps you.
    Regards,
    Tarun

  • How to concatenate multiple records into one

    Hi everybody:
    I want to know if exist some way to concat multiple records into one without using cursors. For example, I have a table named "Authors" like this:
    Lan|Author
    English|Ernest Hemingway
    Spanish|Octavio Paz
    Spanish|Mario Vargas Llosa
    English|Sinclair Lewis
    Spanish|Gabriel García Márquez
    And I want to get this:
    Author
    Octavio Paz, Mario Vargas Llosa, Gabriel García Márquez
    I have worked with SQL Server and I can do something like this:
    CREATE FUNCTION dbo.MyConcat (@lan varchar(10))
    RETURNS varchar(5000) AS
    BEGIN
    declare @retvalue varchar(5000)
    set @retvalue=''
    select @retvalue = @retvalue + Author +',' from Authors where lan = @lan
    return substring(@retvalue,1,len(@retvalue)-1)
    END
    ie, do not use cursors to concatenate records. However, with ORACLE, I have to do someting like this.
    FUNCTION MyConcat(P_Lan IN VARCHAR2) RETURN VARCHAR2 IS
    v_ret VARCHAR2(4000);
    v_element VARCHAR2(4000);
    v_cursor sys_refcursor;
    BEGIN
    OPEN v_cursor FOR SELECT Author FROM Authors where Lan = P_Lan
    LOOP
    FETCH v_cursor INTO v_elemento;
    EXIT WHEN v_cursor%NOTFOUND;
    IF v_ret IS NULL THEN
    v_ret := v_element;
    ELSE
    v_ret := v_ret || ', ' || v_element;
    END IF;
    END LOOP;
    RETURN v_ret;
    END;
    Exist some other way to do this?
    Best Regards
    Jack

    Tks both for answer... I forgot to mention that I am using Oracle 10g. I read about LISTAGG() but this function is available for Oracle 11g release 2.
    I wil read about the other techniques than Hoek mention
    Best Regards.
    Jack

  • I received pictures in a dozen emails and saved each picture into one file in .pages.  I did not import the photos before doing this and now iPhoto won't recognize the pictures because they are in a .pages file.  How do I get the pics to iPhoto?

    I received a dozen pictures in a few emails and I saved them all into one file in pages.  I just copied and pasted.  I do not have the originals any longer.  Iphoto will not permit me to import the pictures as it does not recognize a .pages file, nor can I simply click and drag from the pages document to iphoto nor from pages to the desktop to iphoto.  How can I save each picture I guess back into a jpeg and then import them into iphoto or have i lost them to a pages document forever?  This is urgent as I need the pictures made into a book on iphoto for work by Friday!!!  Please advise!  Thank you.

    Greetings,
    Locate the Pages document wherever it's located on your computer and click once on it to highlight it.
    Go to File > Duplicate to make a backup copy of the file.
    Click once again on the file to highlight it.
    Go to File >  Get Info
    In the "Name & Extension" category remove the ".pages" extension and put in ".zip".
    Close the info window and double-click the now renamed pages file (zip file now).It will decompress into a folder which contains all the base components including all the images you added.  These can be dragged onto the iPhoto icon to import them.
    Hope that helps.

  • Insert multiple records into a table(Oracle 9i) from a single PHP statement

    How can I insert multiple records into a table(Oracle 9i) from a single PHP statement?
    From what all I've found, the statement below would work if I were using MySQL:
         insert into scen
         (indx,share,expire,pitch,curve,surface,call)
         values
         (81202, 28, 171, .27, 0, 0, 'C' ),
         (81204, 28, 501, .25, 0, 0, 'C' ),
         (81203, 17, 35, .222, 0, 0, 'C' ),
         (81202, 28, 171, .27, 2, 0, 'C' ),
         (81204, 28, 501, .20, 0, 1, 'C' ),
         (81203, 28, 135, .22, 1, 0, 'C' )
    The amount of records varies into the multiple-dozens. My aim is to utilize the power of Oracle while avoiding the i/o of dozens of single-record inserts.
    Thank you,
    Will

    You could look at the INSERT ALL statement found in the documentation here:
    http://download.oracle.com/docs/cd/B10501_01/server.920/a96540/statements_913a.htm#2133161
    My personal opinion is that you probably won't see any benefit because under the hood I think Oracle will still be doing single row inserts. I could be wrong though.
    The only way to confirm was if you did a test of multiple inserts vs an INSERT ALL, that is if the INSERT ALL met your requirements.
    HTH.

  • HP Officejet 6500A How do I scan a document with multiple pages into one file?

    HP Officejet 6500A Plus e-All-in-One Printer - E710n
    Windows 7 (64 bit)
    How do I scan a document with multiple pages into one file?  My old printer (psc 2110) asked after each scan if I wanted to scan another page.  At the end I had one pdf file with multiple pages.
    This new one creates one file for each page and I cannot find a way to create one pdf file with multiple pages.
    This question was solved.
    View Solution.

    Hi mpw101,
    If you load the papers into the ADF - Automatic Document Feeder, and then select Document to PDF then they will all be scanning into one file. Let me know if this works for you?
    I am an HP employee.
    Say Thanks by clicking the Kudos Star in the post that helped you.
    Please mark the post that solves your problem as "Accepted Solution"

  • Creation of multiple Records in the file as per multiple segments in IDOC

    Hi SapAll.
    i have got a requirement to create a multiple records in a file based on multiple segments at sending Idoc in a File To Idoc Interface.
    the Scenario  is the reciever message type is mapped with fields of 3 segments in sending IDOC.
    SEG01   1.....1(PARENT SEGMENT)
      SEG02  0...999999(CHILD SEGMENT)
      SEG03 0...9999999(CHILD SEGMENT)
    in an instance where if the SEG01 exists for one time and SEG02 exists for 2 times and Seg03 Exists for 2 times PI is creating the file with 2 records in it but
    when if the SEG01 exists for one time and SEG02 exists for 2 times and Seg03 Exists for 1 time it is raising the error in message mapping where it is supposed to create 2 records in a file with empty values in the fields (mapping with seg03) segment.
    can anybody help me in this.
    regards.
    Varma

    you can create a UDF after you validate if the count match. if match you create the message if not, call de UDF.
    this UDF should receive two parameters -->Queue SEG2 and queue of SEG3.
    then you should loop by the count of SEG2. if you find a Supress Value in the queue of SEG3 add a "" to result. for example.
    for(i=0;i<=SEG2.count;i++){
    If SEG3<i>.equals(ResultList.SUPPRESS) {
           result.addValue(" ");
    }else{result.addValue(SEG3<i>);
    the result of UDF is a queue which should map to target field directly coz it has context changes
    I think that is what you are needing. if no let me know.
    RP
    Edited by: Rodrigo Alejandro Pertierra on Jun 17, 2010 11:56 AM

Maybe you are looking for