Concat result into one string

I have following table
col1 col2
A mouse
B mouse
C mouse
D keyboard
E keyboard
I need to write a query which will give me an output
mouse - A, B, C

this?
SQL> WITH T AS
  2     (SELECT 'A' col1, 'mouse' col2  FROM DUAL
  3      UNION ALL
  4      SELECT 'B', 'mouse' VALUE FROM DUAL
  5      UNION ALL
  6      SELECT 'C' ,'mouse' VALUE FROM DUAL
  7      UNION ALL
  8      SELECT 'D' ,'keyboard' VALUE FROM DUAL
  9      UNION ALL
10     SELECT 'E', 'keyboard' VALUE FROM DUAL
11     )--------- end of data
12  SELECT col2
13        , SUBSTR(MAX(SYS_CONNECT_BY_PATH(col1, ',' )),2) con
14     FROM ( SELECT col2
15                 , col1
16                 , row_number() OVER (PARTITION BY col2 ORDER BY col2) rn
17              FROM T
18          )
19    START WITH rn = 1
20  CONNECT BY PRIOR rn = rn-1
21      AND PRIOR col2 = col2
22    GROUP BY col2;
COL2     CON
keyboard D,E
mouse    A,B,C

Similar Messages

  • Concat rows into one string for display on report

    I have a result set having 1 column and multiple rows.
    On the report I just want to display all the rows comma separated.
    For example:
    Name
    RAM
    GURU
    Sundar
    Shyam
    Inba
    KalaiOutput:
    "RAM, GURU, Sundar, Shyam, Inba, Kalai"Any help appreciated
    Thanks.

    Hi,
    it's ok like this.
    The result will be your return value.
    The reason is that if you choose context instead of value that you could have more than one return value.
    In your case you could use the code of Rohit and then just map it like
    input (with context E1EDPT1) -> UDF -> target
    Regards
    Patrick

  • Need to concatonate multiple values for same key columns into one string

    Hi...I'm attempting to use PL/SQL to read through a table containing more than one column value for a set of keys, and concatonate those values together into one string. For example, in the STUDENT table, for a STUDENT_ID there are multiple MAJORS_ACCOMPLISHED such as History, Biology and Mathematics. Each of the majors is stored in a different row with the same STUDENT_ID due to different faculty DEPARTMENT values.
    I want to read through the table and write out a single row for the STUDENT_ID and
    concatonate the values for MAJORS_ACCOMPLISHED. The next row should be another STUDENT_ID and the MAJORS ACCOMPLISHED for that student..etc.
    I've hit a wall trying to use cursors and WHILE loops to get the results I want. I'm hoping someone may have run across this before and have a suggestion. Tks!!

    I think you are looking for string aggregation.
    The following are the replies posted by me in the forum recently on the same case.
    they might help you.
    Re: Concatenating multiple rows in a table - Very urgent - pls help
    Re: Doubt in a query ( Urgent )
    Re: How to remove words which consist of max 2 letters?
    Re: output like Name1,Name2,Name3...

  • Output strings from loop into one string

    im trying my best to explain my problem so ber in mind:)
    hey having a bit of trouble with outputing strings from loop
    example
    i typed ab into the textbox
    the output should be 12
    but since it is in a loop it would only output the last string and in this case is 2
    im trying to get both strings from the loop and output strings from loop into one string.
    here is some of my code to understand my problem
    // characters a to f
         char[] charword = {'a','b','c','d','e','f'};
         String charchange ;
      // get text from password textbox
                          stringpassword = passwordTextbox.getText();
                          try {
                          // loop to show password length
                          for ( int i = 0; i < stringpassword.length(); i++ ){
                          // loop to go through alfabet     
                          for (int it = 0; it < charword.length; it++){
                             // if char equals stringwords
                               if (stringpassword.charAt(i) == charword[it]){
                                    System.out.print("it worked");
                                    // change characters start with a
                                    if (charword[it] == 'a'){
                                         charchange = "1";
                                    // change to 2
                                    if (charword[it] == 'b'){
                                         charchange = "2";
                                        }

    Not sure how you are displaying the result but you could display each value as soon as you find it.
    if (charword[it] == 'a'){
        System.out.print("1");
    }If it is in a text field then use append. Or if you really need a String with the entire result then use concatenation.
    if (charword[it] == 'a'){
        charchange += "1";
    }

  • Concatenate multiple columns into one string

    Hello,
    I am using Oracle 11.2, how can I concatenate the value of multiple columns into one string with one SQL:
    create table testTb(classId number(5), classRoom varchar2(32));
    insert into testTb value(101, 'room101');
    insert into testTb value(101, 'room201');
    insert into testTb value(101, 'room301');
    insert into testTb value(202, 'room444');
    insert into testTb value(202, 'room555');
    I would like to generate the result as followings:
    Class 101 is in room101, room201, room301
    Class 202 is in room444, room555
    Thanks,

    Hi,
    Since you're using Oracle 11.2, you can use the aggregate LISTAGG function:
    SELECT       'Class ' || classid
                   || ' is in '
                 || LISTAGG ( classroom
                         ) WITHIN GROUP (ORDER BY classroom)
                   AS txt
    FROM       testtb
    GROUP BY  classid
    ;The generic name for concatenating all the strings in a group is String Aggregation . This page shows several ways to do it, suitable for different versions of Oracle.

  • SQL Query -How2bring multiple results into one field using Formatted Search

    Hi Everyone
    i am trying to bring in the results of the field dbo.Lot_ITEM.LOT using a formatted search into a row level using the following query:
    SELECT     dbo.LOT_ITEM.LOT
    FROM       dbo.DLN1 INNER JOIN dbo.LOT_ITEM ON dbo.DLN1.ItemCode = dbo.LOT_ITEM.ITEM
    WHERE     dbo.LOT_ITEM.ITEM=$[DLN1.ItemCode]
    however the result of the dbo.Lot_ITEM.LOT field could be more then one value depending on how many lots are assigned for that item
    (for example this query would be similar to assigning batch/serial numbers to an item being despatched - as you can choose multiple batches/serials depending on the quantities available and required and then move from the left to the right side of the selection window) if that makes sense!
    is it possible to bring in the multiple results into one field? and how can i amend the above query to include this?
    Thankyou in advance :o)
    Edited by: Asma Bi on Apr 23, 2008 7:22 PM
    Edited by: Asma Bi on Apr 23, 2008 7:24 PM

    Hi Suda
    Thanks for replying :o) but im not sure about the query?
    just to simplify it (as the query im working with is to do with 3rd party addons) i have used the serial/batchs field instead and used standard demo database fields from SBO 2005 sp01:
    SELECT     dbo.ixvSerialNoFact.SRI1_IntrSerial
    FROM       dbo.DLN1 INNER JOIN
                    dbo.ixvSerialNoFact ON dbo.DLN1.DocEntry = dbo.ixvSerialNoFact.SRI1_BaseEntry
    WHERE     dbo.ixvSerialNoFact.ItemCode='g1000' and dbo.ixvSerialNoFact.SRI1_BaseEntry = '193'
    The above brings me the relevant results but when i change it to be used in a formatted search:
    SELECT     dbo.ixvSerialNoFact.SRI1_IntrSerial
    FROM       dbo.DLN1 INNER JOIN
                    dbo.ixvSerialNoFact ON dbo.DLN1.DocEntry = dbo.ixvSerialNoFact.SRI1_BaseEntry
    WHERE     dbo.ixvSerialNoFact.ItemCode=$[dln1.itemcode] and dbo.ixvSerialNoFact.SRI1_BaseEntry = $[dln1.DocEntry]
    i cant seem to get it to work - now this may be because the serial number is not allocated until teh record is added to the system, however when this happens i am unable to go back in and manually trigger the query as the delivery note rows cannot be selected!
    i  think as what im originally wanting an answer for is same as this example, im wanting to know if this is even possible?
    Thanks
    Edited by: Asma Bi on Apr 24, 2008 3:53 PM
    Edited by: Asma Bi on Apr 24, 2008 3:55 PM

  • XML into one string element

    Hello,
            In Graphical mapping, Could anyone pls tell me in detail about how to achieve One whole xml into one string element. This XML file i want to send to DATABASE.

    Thi blog might be of some help
    /people/michal.krawczyk2/blog/2005/11/01/xi-xml-node-into-a-string-with-graphical-mapping

  • Combining string array elements into one string

    Right, I have an string array called str which stores 1 character in each of its 16 elements. It gets this character from another array, strArray. Now, what I want to be able to do is to take all 16 elements and combine them into one string called keyString. Using the code below keyString only prints out the last character. The code is shown below:
    for (x=0; x<16; x++) {
         str = new String[16];
         str[x] = "";
         str[x] += (strArray[(index+x)%16].charAt(strChar[x]));
         keyString = str[x];
           System.out.print(keyString);
    }Any help would be very much appreciated.
    Edited by: Paragon96 on May 20, 2008 7:32 AM

    your logic is wrong ; if you want to concatenate the content of the array, you have to loop (what you did), and concatenate keyString for each index, meaning:
    keyString += str[x];you can also use a StringBuilder for such kind of operations

  • Multiple BI Query Results into one Table

    Hi All
    Can I embed Multiple queries into one table using VC?
    I have data in different BI sources(Info Areas) like sales and distribution,Shipments etc. Can I write any universal query to retrive data from multiple sources?(If any???)

    Hi Jan Pasha,
    My model contains two BW queries which uses UNION and sent result to one table.
    I tried using UNION also but when I use it I am able to see no records to select in result table.
    I donot have any coloums in common. Is it pre-requisite for using UNION?

  • Combining like results into one row

    The statement below works. However when the results are returned there are multiple values returned for the same "Period" that I would like to see returned into one row.
    SELECT "Request ID", "External Customer", "Staff Prof Id", "Period", "Planned External", "Actual External", "Planned Internal", "Actual Internal", "Total Planned", "Actual Total"
    FROM (
    SELECT ppl.request_id "Request ID", ppl.mdpr_bds_ext_customer "External Customer", cells.staff_prof_id "Staff Prof Id", period.period_short_name "Period", CELLS.PLANNED_FTE/100 "Planned External", CELLS.actual_fte/100 "Actual External", 0 "Planned Internal", 0 "Actual Internal", /*skills.skill_name,*/ total.plan_total_fte/100 "Total Planned", total.actual_total_fte/100 "Actual Total"
    FROM RML.MREQ_MDPR_PROJ PPL, knta.krsc_staff_prof_line_cells_v CELLS, knta.krsc_staff_prof_lines_v LINES, knta.knta_periods PERIOD, knta.krsc_skills_v SKILLS, knta.krsc_staff_prof_period_sum TOTAL
    where PPL.MDPR_BDS_SUB_PROJ IS NOT NULL AND PPL.KNTA_STAFFING_PROFILE = CELLS.STAFF_PROF_ID(+) AND cells.staff_prof_line_id = lines.staff_prof_line_id AND ppl.knta_staffing_profile = total.staff_prof_id
    AND cells.period_id = period.period_id AND lines.skill_id = skills.skill_id AND skills.skill_name like '%External%' AND total.period_id = period.period_id
    UNION
    SELECT ppl.request_id "Request ID", ppl.mdpr_bds_ext_customer "External Customer", cells2.staff_prof_id "Staff Prof Id", period.period_short_name "Period", 0 "Planned External", 0 "Actual External", CELLS2.planned_fte/100 "Planned Internal", CELLS2.actual_fte/100 "Actual Internal", /*skills.skill_name,*/ total.plan_total_fte/100 "Total Planned", total.actual_total_fte/100 "Actual Total"
    FROM RML.MREQ_MDPR_PROJ PPL, knta.krsc_staff_prof_line_cells_v CELLS2, knta.krsc_staff_prof_lines_v LINES, knta.knta_periods PERIOD, knta.krsc_skills_v SKILLS, knta.krsc_staff_prof_period_sum TOTAL
    where PPL.MDPR_BDS_SUB_PROJ IS NOT NULL AND PPL.KNTA_STAFFING_PROFILE = CELLS2.STAFF_PROF_ID(+) AND cells2.staff_prof_line_id = lines.staff_prof_line_id AND ppl.knta_staffing_profile = total.staff_prof_id
    AND cells2.period_id = period.period_id AND lines.skill_id = skills.skill_id AND skills.skill_name not like '%External%' AND total.period_id = period.period_id)
    ORDER BY "Request ID"

    Probably you are looking at something like GROUP BY "Request ID", "External Customer", "Staff Prof Id", "Period" and SUM () the other columns. As Enrico says, examples of actual and desired output would be helpful.
    At a glance a UNION of...
    AND    skills.skill_name LIKE '%External%'...and...
    AND    skills.skill_name NOT LIKE '%External%'...seems a slightly strange approach.

  • Merging two Queires result into one.

    I have to get two different result on the same table.First Result will be get first then added by Second result
    SELECT distinct cust.custid,cust.firstnm,cust.nextactiondt,cust.priorityscr,cust.lastacssts FROM Customer cust, Custqueue custqueue
    WHERE cust.custid=custqueue.custid AND custqueue.qcd = 'A'
    AND trunc(cust.nextactiondt)>=trunc(current_date) AND trunc(cust.lastacssts)<trunc(current_date)
    ORDER BY cust.nextactiondt,cust.priorityscr desc
    Custid            Name     Nextactiondt   priorityscr      lastacssts
    *65 A     16-JUN-11     11.52     14-MAR-11*
    *84 B     16-JUN-11     1.38     14-MAR-11*
    *93 C     17-JUN-11     0     18-APR-11*
    SELECT distinct cust.custid,cust.firstnm,cust.nextactiondt,cust.priorityscr,cust.lastacssts FROM Customer cust, Custqueue custqueue
    WHERE cust.custid=custqueue.custid AND custqueue.qcd = 'A'
    AND trunc(cust.nextactiondt)>=trunc(current_date) AND trunc(cust.lastacssts)=trunc(current_date)
    ORDER BY cust.lastacssts,cust.nextactiondt,cust.priorityscr desc
    Custid            Name     Nextactiondt   priorityscr      lastacssts
    *59 S      16-JUN-11     1212     16-JUN-11*
    I want to club the result of the two query into 1 as follows.
    Custid            Name     Nextactiondt   priorityscr      lastacssts
    *65 A     16-JUN-11     11.52     14-MAR-11*
    *84 B     16-JUN-11     1.38     14-MAR-11*
    *93 C     17-JUN-11     0     18-APR-11*
    *59 S      16-JUN-11     1212     16-JUN-11*
    but when i am using UNION
    SELECT distinct cust.custid,cust.firstnm,cust.nextactiondt,cust.priorityscr,cust.lastacssts FROM Customer cust, Custqueue custqueue
    WHERE cust.custid=custqueue.custid AND custqueue.qcd = 'A'
    AND trunc(cust.nextactiondt)>=trunc(current_date) AND trunc(cust.lastacssts)<trunc(current_date)
    UNION
    SELECT distinct cust.custid,cust.firstnm,cust.nextactiondt,cust.priorityscr,cust.lastacssts FROM Customer cust, Custqueue custqueue
    WHERE cust.custid=custqueue.custid AND custqueue.qcd = 'A'
    AND trunc(cust.nextactiondt)>=trunc(current_date) AND trunc(cust.lastacssts)=trunc(current_date)
    ORDER by 3,4 desc,5
    I am getting
    Custid            Name     Nextactiondt   priorityscr      lastacssts
    *59 S      16-JUN-11     1212     16-JUN-11*
    *65 A     16-JUN-11     11.52     14-MAR-11*
    *84 B     16-JUN-11     1.38     14-MAR-11*
    *93 C     17-JUN-11     0     18-APR-11*
    but that is different from what i expect
    Custid            Name     Nextactiondt   priorityscr      lastacssts
    *65 A     16-JUN-11     11.52     14-MAR-11*
    *84 B     16-JUN-11     1.38     14-MAR-11*
    *93 C     17-JUN-11     0     18-APR-11*
    *59 S      16-JUN-11     1212     16-JUN-11*
    so any one know how can i append the results of two queries into one since i have order by clause in both queries and i can club them together.
    Any help regarding this would be appreciated

    Look at the following example:
    SQL> select * from emp
      2  where deptno=10
      3  order by job;
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7934 MILLER     CLERK           7782 23-JAN-82       1300                    10
          7782 CLARK      MANAGER         7839 09-JUN-81       2450                    10
          7839 KING       PRESIDENT            17-NOV-81       5000                    10
    SQL> select * from emp
      2  where deptno=20
      3  order by ename;
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7876 ADAMS      CLERK           7788 23-MAY-87       1100                    20
          7902 FORD       ANALYST         7566 03-DEC-81       3000                    20
          7566 JONES      MANAGER         7839 02-APR-81       2975                    20
          7788 SCOTT      ANALYST         7566 19-APR-87       3000                    20
          7369 SMITH      CLERK           7902 17-DEC-80        800                    20
    SQL> with q1 as (
      2  select * from emp
      3  where deptno=10
      4  order by job),
      5  q2 as (
      6  select * from emp
      7  where deptno=20
      8  order by ename
      9  )
    10  select * from q1
    11  union all
    12  select * from q2;
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7934 MILLER     CLERK           7782 23-JAN-82       1300                    10
          7782 CLARK      MANAGER         7839 09-JUN-81       2450                    10
          7839 KING       PRESIDENT            17-NOV-81       5000                    10
          7876 ADAMS      CLERK           7788 23-MAY-87       1100                    20
          7902 FORD       ANALYST         7566 03-DEC-81       3000                    20
          7566 JONES      MANAGER         7839 02-APR-81       2975                    20
          7788 SCOTT      ANALYST         7566 19-APR-87       3000                    20
          7369 SMITH      CLERK           7902 17-DEC-80        800                    20
    8 rows selected.Max

  • Mapping question: n recordsets with m fields into one string

    Hi,
    My input message will look like
    <customer>
      <name>name</name>
    </customer>
    <row1>
      <customer>name</customer>
      <field11>111</field11>
      <field12>122</field12>
    </row1>
    <row2>
      <customer>name</customer>
      <field21>211</field21>
      <field22>222</field22>
    </row2>
    <rown>
      <customer>name</customer>
      <fieldn1>n11</fieldn1>
      <fieldn2>n22</fieldn2>
    </row1>
    and i need an output like
    <customer>
      <name>name</name>
    </customer>
    <rowx>
      <fieldx>111222211222.........n11n22</fieldx>
    </rowx>
    in short all fields from row1 to rowx need to be concatened in one big string.
    What is the best way to do this?
    Kr
    Robert

    Surely Using UDF/ Java Mapping it is easy .
    What version are u working on .
    IF 7.1 , try Using Global Variable (  Graphical variable ) on receiver side.
    Lets see if it worked.
    try Like this
    field11  ->                Concat ->      Graphical Variable
    Graphical Variable ->
    I am expecting every time value of field11 will be conactinated with previously store Graphical Variable .
    Similarly for all other fields .
    and in last Concate them all fields to One Output Final String.
    Check this link . If you want to know the working of Graphical variable .
    SAP PI 7.1 Mapping Enhancements Series: Graphical Variables.
    /people/william.li/blog/2008/02/13/sap-pi-71-mapping-enhancements-series-using-graphical-variable
    Regards
    PS

  • Linking three databases and combing results into one resultset

    Hi Folks,
    I would like to receive input of respectable members of this forum for this problem. Please see details below and let me know what would be the best approach to implement it.
    Problem statement:I need to present data from three Oracle databases in the form of a report based upon parameter values entered by users.
    Problem Details:I have three tables which have same structure but different data. Each table is in a different database, i-e:
    DB1.TableX (say: DB1 holds data for Europe)
    DB2.TableX (DB2 holds data for Asia)
    DB3.TableX (DB3 holds data for North America)
    User Parameters:If p_country = 'ENGLAND' then go and fetch data from DB1.TableX only
    If p_country in ('ENGLAND', 'U.S.A') then go and fetch data from DB1.TableX and DB3.TableX etc.
    Users:Users of DB1, DB2 ,and DB3 will be running this report from their respective dbs so users of DB1 will be able to see data of DB2 and DB3 as well and the vice versa.

    dreporter wrote:
    User Parameters:If p_country = 'ENGLAND' then go and fetch data from DB1.TableX only
    If p_country in ('ENGLAND', 'U.S.A') then go and fetch data from DB1.TableX and DB3.TableX etc.You do not want to hit and process remote tables when they do not have the required rows.
    There's an old feature, dating back to Oracle v7 and still around, called partitioned views. Simply put, you create a view on the tables by using union all.
    A constraint per table specify the expected rows in that table. Oracle's CBO uses this constraint to determine which tables in the partition view to query (assuming of course the constraint column is used).
    For example, you have 5 organisations (same table structure) and a table per organisation. You add a organisation column to each of the tables, with a constraint on the column specifying which organisation's data is in that table. So table1 will have a check constraint on ORG_CODE that says 'BBC', and table2 will have the same constraint with value 'CNN', and table3 will have constraint with value 'SKY', etc.
    The partition view is a plain vanilla view. E.g.
    <i>create or replace view organisations as
    select * from table1 union all
    select * from table2 union all
    select * from table3 union all
    select * from table4 union all
    select * from table5</i>
    If you now query the partition view and use ORG_CODE = 'SKY', then only table3 will be queried and the other tables will not (the CBO prunes the other tables from the view using a special predicate).
    This works pretty well - especially when you only have Oracle Standard Edition. The question though is whether this will work across db links. But it is worth finding out and having a look at this option.

  • Read multiple files and save all into one output file(AGAIN)

    Hi, guys
    I need your help for reading data from multiple files and save the results into one output file. When files are selected from file chooser, my program read the data line by line , do some calculations and save the result into the output. I made an array to store input files and it seems to be working fine, but when it comes to SaveFile() function, issues NullPointException message.
    public class FileReduction1 extends JFrame implements ActionListener
       // GUI definition and layout
        /* ACTION PERFORMED */
        public void actionPerformed(ActionEvent event) {
            if (event.getActionCommand().equals("Open File")) getFileName();
        /* OPEN THE FILE */
        private void getFileName() {
            // Display file dialog so user can select file to open
         JFileChooser fileChooser = new JFileChooser();
         fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fileChooser.setMultiSelectionEnabled(true);
         int result = fileChooser.showOpenDialog(this);
         // If cancel button selected return
         if (result == JFileChooser.CANCEL_OPTION) return;
            if (result == JFileChooser.APPROVE_OPTION)
             files = fileChooser.getSelectedFiles();
                textArea.setText("");
                if(files.length>0)
                    filelist="";
                    System.out.println("files length"+files.length);
                    for(int i=0;i<files.length;i++)
                         System.out.println(files.getName());
    filelist+=files[i].getName()+" ,";
    if (checkFileName(files[i]) )
    openButton.setEnabled(true);
    readButton.setEnabled(true);
    textArea.append("file "+files[i].getName()+"is a proper file"+"\n");
    readFile(files[i]);
    textfield.setText(filelist);
    else{JOptionPane.showMessageDialog(this,"Please select file(s)",
                    "Error 5: ",JOptionPane.ERROR_MESSAGE); }
         // Obtain selected file
    /* READ FILE */
    private void readFile(File fileName_in) {
    // Disable read button
    readButton.setEnabled(false);
    // Dimension data structure
         getNumberOfLines(fileName_in);
         data = new String[numLines][4];
         // Read file
         readTheFile(fileName_in);
         // Rnable open button
         openButton.setEnabled(true);
    /* GET NUMBER OF LINES */
    /* Get number of lines in file and prepare data structure. */
    private void getNumberOfLines(File fileName_in) {
    int counter = 0;
         // Open the file
         openFile(fileName_in);
         // Loop through file incrementing counter
         try {
         String line = fileInput.readLine();
         while (line != null) {
         counter++;
              System.out.println("(" + counter + ") " + line);
    line = fileInput.readLine();
         numLines = counter;
    closeFile(fileName_in);
         catch(IOException ioException) {
         JOptionPane.showMessageDialog(this,"Error reading File",
                   "Error 5: ",JOptionPane.ERROR_MESSAGE);
         closeFile(fileName_in);
         System.exit(1);
    /* READ FILE */
    private void readTheFile(File fileName_in)
    // Open the file
    //int row=0;
    int col=0;
    openFile(fileName_in);
    System.out.println("Read the file");
    // Loop through file incrementing counter
    try
    String line = fileInput.readLine();
    while (line != null)
    boolean containsDoubles = false;
    double temp;
    String[] lineParts = line.split("\t");
    try
    for (col=0;col<lineParts.length;col++)
    temp=Double.parseDouble(lineParts[col]);
    data[row][col] = lineParts[col];
    containsDoubles = true;
    System.out.print("data["+row+"]["+col+"]="+lineParts[col]+" ");
    } catch (Exception e) {row=0; col=0; temp=0.0;}
    if (containsDoubles){ row++;}
    System.out.println();
    line = fileInput.readLine();
    catch(IOException ioException)
    JOptionPane.showMessageDialog(this,"Error reading File", "Error 5: ",JOptionPane.ERROR_MESSAGE);
    closeFile(fileName_in);
    System.exit(1);
    //System.out.println("length"+data.length);
    closeFile(fileName_in);
    process(fileName_in);
    /* CHECK FILE NAME */
    /* Return flase if selected file is a directory, access is denied or is
    not a file name. */
    private boolean checkFileName(File fileName_in) {
         if (fileName_in.exists()) {
         if (fileName_in.canRead()) {
              if (fileName_in.isFile()) return(true);
              else JOptionPane.showMessageDialog(null,
                        "ERROR 3: File is a directory");
         else JOptionPane.showMessageDialog(null,
                        "ERROR 2: Access denied");
         else JOptionPane.showMessageDialog(null,
                        "ERROR 1: No such file!");
         // Return
         return(false);
    /* OPEN FILE */
    private void openFile(File fileName_in) {
         try {
         // Open file
         FileReader file = new FileReader(fileName_in);
         fileInput = new BufferedReader(file);
         catch(IOException ioException) {
         JOptionPane.showMessageDialog(this,"Error Opening File",
                   "Error 4: ",JOptionPane.ERROR_MESSAGE);
         textArea.append("OPEN FILE\n---------\n");
         textArea.append(fileName_in.getPath());
         textArea.append("\n");
         //System.out.println("File opened successfully");
    /* CLOSE FILE */
    private void closeFile(File fileName_in) {
    if (fileInput != null) {
         try {
              fileInput.close();
         catch (IOException ioException) {
         JOptionPane.showMessageDialog(this,"Error Opening File",
                   "Error 4: ",JOptionPane.ERROR_MESSAGE);
    System.out.println("File closed");
    private void process(File fileName_in) {
    //getNumberOfLines();
         //data = new String[numLines][3];
         // Read file
    double temp,temp1;
         //readTheFile();
    //System.out.println("row:"+row);
    //int number=data.length;
    //System.out.println(number);
    for (int i=0; i<row; i++)
    temp=Double.parseDouble(data[i][1]);
    sumx+=temp;
    temp1=Double.parseDouble(data[i][3]);
    sumy+=temp1;
    multixy+=(temp*temp1);
    square_x_sum+=(temp*temp);
    square_y_sum+=(temp1*temp1);
    //System.out.println("Sum(x)="+sumx);
    double tempup=(row*multixy)-(sumx*sumy);
    double tempdown=(row*square_x_sum)-(sumx*sumx);
    slope=tempup/tempdown;
    double tempbup=sumy-(slope*sumx);
    intb=tempbup/row;
    double tempside=(row*square_y_sum)-(sumy*sumy);
    double cordown=Math.sqrt(tempdown*tempside);
    corr=tempup/cordown;
    r_sqrt=corr*corr;
         textArea.append("Data for file"+ fileName_in.getName()+" have been processed successfully.");
         textArea.append("\n");
         textArea.append("Please enter output file name including extension.");
    System.out.println("number"+row);
    System.out.println("slope(m)="+slope);
    System.out.println("intecept b="+intb);
    System.out.println("correlation="+corr);
    System.out.println("correlation="+r_sqrt);
    saveFile();
    private void saveFile()
    textArea.append("SAVE FILE\n---------\n");
    if (openFile1())
         try {
              outputToFile();
    catch (IOException ioException) {
              JOptionPane.showMessageDialog(this,"Error Writing to File",
                   "Error",JOptionPane.ERROR_MESSAGE);
    private boolean openFile1 ()
         // search for the file path
    StringBuffer stringpath;
    title=textfield1.getText().trim();
    int temp=fileName_in.getName().length();
    int temp_path=fileName_in.getPath().length();
    int startd=(temp_path-temp);
    stringpath=new StringBuffer(fileName_in.getPath());
    stringpath.delete(startd, temp_path+1);
    //System.out.println("file-path="+temp_path);
    //System.out.println("length-file="+temp);
    path=stringpath.toString();
    fileName_out = new File(path, title);
    //System.out.println(file_out.getName());
    if (fileName_out==null || fileName_out.getName().equals(""))
         JOptionPane.showMessageDialog(this,"Invalid File name",
                   "Invalid File name",JOptionPane.ERROR_MESSAGE);
         return(false);
         else
    try
    boolean created = fileName_out.createNewFile();
    if(created)
    fileOutput = new PrintWriter(new FileWriter(fileName_out));
    fileOutput.println("File Name"+"\t"+"Slope(m)"+"\t"+"y-intercept(b)"+"\t"+"Coefficient(r)"+"\t"+"Correlation(R-Squared)");
    return(true);
    else
    fileOutput = new PrintWriter(new FileWriter(fileName_out,true));
    return(true);
    catch (IOException exc)
    JOptionPane.showMessageDialog(this,"Please enter the file name","Error",JOptionPane.ERROR_MESSAGE);
    return(false);
    private void outputToFile() throws IOException
    // Initial output
         textArea.append("File name = " + fileName_out + "\n");
         // Test if data exists
         if (data != null)
         fileOutput.println(fileName_in.getName() +"\t"+ slope+"\t"+intb+"\t"+corr+"\t"+r_sqrt);
    textArea.append("File output complete\n\n");
         else
    textArea.append("No data\n\n");
         // End by closing file
    initialcomp();
         fileOutput.close();
    private void initialcomp()
    slope=0.0;
    intb=0.0;
    corr=0.0;
    r_sqrt=0.0;
    sumx=0.0; sumy=0.0; multixy=0.0; square_x_sum=0.0; square_y_sum=0.0;
    for(int i=0;i<data.length;i++)
    for(int j=0;j<data[i].length;j++)
    data[i][j]=null;
    /* MAIN METHOD */
    public static void main(String[] args) throws IOException
         // Create instance of class FileChooser
         FileReduction1 newFile = new FileReduction1("File Reduction Program");
         // Make window vissible
         newFile.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         newFile.setSize(500,400);
    newFile.setVisible(true);
    Sorry about the long lines.
    As you can see, all input files saved in array called files, however when OpenFile1() function is called, it take input (fileName_in) as a single file not an array. I'm assuming this causes the exception.
    When there's muptiple inputs, program should take each file from getFileName() to outputToFile() sequentially.
    Does anybody have an idea to solve this?
    Thanks a lot!!

    you naming convention is confussing. you should follows Java naming convention..you have a getXXX but decalred the return type as "void"...get usully means to return something...
    your code is doing too much..and hard to follows..
    1. get the selected files
    for each selected file
    process the file and return the result
    write out the result.
    /** close the precious resource */
    public void closeResource(Reader in){
        if (in != null){
            try{ in.close(); }
            catch (Exception e){}
    /** get the total number of line in a file */
    public int getLineCount(File file) throws IOException{
        BufferedReader in = null;
        int lineCount = 0;
        try{
            in = new BufferedReader(new FileReader(file));
            while ((in.readLine() != null)
                lineCount++;
            return lineCount;
        finally{ closeResource (in);  }
    /** read the file */
    public void processFile(File inFile, File outFile) throws IOException{
        BufferedReader in = null;
        StringBuffer result = new StringBuffer();
        try{
            in = new BufferedReader(new FileReader(inFile));
            String line = null;
            while ((in.readLine() != null){
                .. do something with the line
                result.append(....);
            writeToFile(outFile, result.toString());
        finally{ closeResource (in);  }
    public void writeToFile(File outFile, String result) throws IOException{
        PrintWriter out = null;
        try{
            out = new PrintWriter(new FileWriter(outFile, true));  // true for appending to the end of the file
            out.println(result);
        finally{  if (out != null){ try{ out.close(); } catch (Exception e){} }  }
    }

  • Merge an internal table into a string stream

    Hello,
    i need to merge an internal table (2 column) layout:
    ELEMENT
    VALUE
    into one string stream.
    E.g.:
    ELEMENT | VALUE
    test1   | 1111111111111111111
    test1   | 2222222222222222222
    result should be:
    test1   | 11111111111111111112222222222222222222 (= type string!)
    too bad you cant use offset while working with a field of type string and im sure there is a ABAP class which does do this.
    regards,
    Markus

    Try this Markus:
    REPORT ztest NO STANDARD PAGE HEADING LINE-SIZE 255.
    DATA: BEGIN OF itab OCCURS 0,
            element TYPE string,
            value   TYPE string,
          END   OF itab.
    DATA: BEGIN OF itab2 OCCURS 0,
            element TYPE string,
            value   TYPE string,
          END   OF itab2.
    DATA: next LIKE sy-tabix VALUE 1,
          old_element LIKE itab-element.
    PERFORM load_itab.
    sy-subrc = 0.
    DO.
      READ TABLE itab INDEX next.
      IF sy-subrc <> 0.
        EXIT.
      ELSE.
        IF itab-element <> old_element.
          IF next <> 1.
            APPEND itab2.
            CLEAR itab2.
          ENDIF.
          itab2-element = itab-element.
          old_element = itab-element.
        ENDIF.
        CONCATENATE itab2-value itab-value INTO itab2-value.
        next = next + 1.
      ENDIF.
    ENDDO.
    IF itab2-element <> space.
      APPEND itab2.
    ENDIF.
    break rburbank.
    *&      Form  load_itab
    *       text
    FORM load_itab.
      REFRESH: itab,
               itab2.
      CLEAR  : itab,
               itab2.
      itab-element = 'test1'.
      itab-value   = '1111111111111111111'.
      APPEND itab.
      itab-element = 'test1'.
      itab-value   = '2222222222222222222'.
      APPEND itab.
      itab-element = 'test2'.
      itab-value   = '3333333333333333333'.
      APPEND itab.
      itab-element = 'test2'.
      itab-value   = '4444444444444444444'.
      APPEND itab.
    ENDFORM.                    " load_itab
    Rob

Maybe you are looking for

  • How do I delete contents from my iCloud account  to free- up space

    Recently i replaced my damaged iPhone with a new one. I could restore the contents to new phone. But now I am not able to update the iCloud from my new phone as it says that "Not enough space". This leads to the question - how do i remove all the con

  • For a PO with item catagory S user exit was not triggering

    HI SDN, I wrote a code for invoicing plan in EXIT_SAPLMRMP_001 for block the payment with INVOICE VERIFICATION block . it is working fine for a PO with item catagory Blank and not working for item catagory S. please suggest me is there any solution f

  • Strange behavior with NI 9401

    Hi everyone! I think I have a strange problem with the NI 9401 modules. My hardware is a CompactRIO and I'm using Labview 8.0. I'm reading a 13 bit encoder with two NI 9401 modules: the first for 8 input channels and the second for the other remainin

  • Displaying a Metadata in URM List!!

    Hi, I would like to populate a field in the 'Disposition Content and Record List' page in URM10g. My Retention Assignments--> List Disposition Content and Record. Currently i could see the following field in the page. Select, Name, Identifier, Author

  • Not being able to browse network (automount not running) ?

    Hi, I'm experiencing a weird problem when connecting to networks using ethernet (i do not notice the problem with wireless). When i connect to an ethernet network. Then sometimes i'm unable to browse the network (mainly for SMB shares but also AFP).