SimpleDateFormat Parse date

import java.text.SimpleDateFormat;
class Datum 
     public Datum()
          java.util.Date datum = null;
          SimpleDateFormat formatter = new SimpleDateFormat("dd-mm-yyyy");
          try
                 datum =  formatter.parse("15-08-2006");
                 System.out.println(datum.toString());
          catch(Exception e)
                e.printStackTrace();
     public static void main( String args[] )
          Datum d =  new Datum();
}Parse Dosesn't working Correct.As a result I get DAte with JAnuary MOnth always, no metter what iactal date is.
I use jdk 1.5.0_06
Please help!!

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); // <-- note the uppercase portion...~

Similar Messages

  • SimpleDateFormat.parse() causes Unparsable date exception

    I am using SimpleDateFormat to both format and parse date strings. The format is working properly, but parse results in the following exception:
    java.text.ParseException: Unparseable date: "2007-08-31T12:05:05.651-0700"
    at java.text.DateFormat.parse(Unknown Source)
    Here is my code:
    SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss.SZ");
    String dateTime = dateFormatter.format(new Date());
    Date test = dateFormatter.parse(dateTime);
    For testing purposes, I am formatting a date string, and then passing it right back into parse() and I get the exception.
    I am using jre1.5.0_10.
    Thank you for your help.
    -Karen

    You have specified the milliseconds (S) to have a minimum of 1 letter.
    From the API:
    Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields.
    If you specify it like this:SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss.SSSZ");
    // or like this
    SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss.S Z");it will work.
    Message was edited by:
    dwg

  • Parsing Date with SimpleDateFormat

    Hi,
    In my application, i want to parse date which is in String format.
    The format of Date in String is "yyyyMMdd'T'HHmmss.SSS'Z'" (ex:- 20031201T100116.000Z).
    //Happy Case - Input Param "20031201T100116.000Z"
    //Output : 2003-12-01 10:01:16.0 is the expected output ------- works well.
    //Exception case Input param Value "00000000T000000.000Z"
    But the above case breaks as the expected output is "0000-00-00 00:00:00 ". But the output what i get is
    "0002-11-30 00:00:00.0"
    Greatly appreciate your inputs...,
    Here is my code for the above stated case....
    private static void printDateFormat(String str) throws Exception
    String format = "yyyyMMdd'T'HHmmss.SSS'Z'"; //Desired Format
    ParsePosition pos = new ParsePosition(0);
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    Date date = sdf.parse(str, pos);
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    System.out.println("[After Formatting]" + date.toString());
    java.sql.Timestamp ts = new java.sql.Timestamp(cal.getTime().getTime());
    System.out.println(ts.toString());
    Thanks !
    Priya.Jlus
    IIMS-NZ.

    SimpleDateFormat is set to lenient date parsing by default, so it's trying it's best to come up with an actual date for 0000-00-00 (what would you say a 'zero' month should be?). You can prevent this "approximation" by using "setLenient(false)", but then you will get a null Date reference for non-parseable dates like the one you're using.
    The bottom line is that you're going to have to do some validation for the user input and handle exceptional conditions.
    Hope this helps! :o)

  • SimpleDateFormat: Parse String To Date

    Hi
    I'm trying to parse Date-String to Date. But the Date-String I want to parse is embedded in a Text like:
    Bla bla bla bla bla bla 2004-05-05 bla bla bla bla bla.
    So I tried the attached Class to solve the problem, but it didn't work.
    Any ideas?
    Thanks Bona
    public class Test {
    private static SimpleDateFormat dateFormat = new SimpleDateFormat();
    private String text;
    private Date date;
    public Test() {
    /ry {
    text = "Bla bla bla bla bla bla 2004-05-05 bla bla bla bla bla.";
    date = toDate(text, "yyyy-MM-dd");
    System.out.println("Datum: "+date);
    } catch (ParseException pe) {
    System.out.println(pe.getMessage());
    public static void main(String[] args) {
    Test test1 = new Test();
    public static Date toDate(String dateString, String dateFormatPattern)
    throws ParseException {
    Date date = null;
    dateFormat.applyPattern(dateFormatPattern);
    dateFormat.setLenient(true);
    date = dateFormat.parse(dateString);
    return date;
    }

    Well, you need to extract the date pattern from that String.
    You can use regular expressions to do that. See theRegex package for info on how to do that.
    BTW - AFAIK, lenient date parsing means, that the parser accepts stuff that matches the pattern, but contains illegal values like "2004-02-30" ...

  • Strange problem with SimpleDateFormat.parse method

    I got something strange with this method.
    String pattern = "yyyy/MM/dd";
    String mydate = "2007/00/10";
    SimpleDateFormat formatter = new SimpleDateFormat(pattern);
    Date newdate = formatter.parse(mydate);
    I get "2006/12/10"
    is this correct.

    dongyisu wrote:
    and there no exception get thrown outYes it does. I ran this:
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    public class DateFormatTest
       public static final String DEFAULT_DATE_FORMAT = "yyyy/MM/dd";
       public static void main(String[] args)
          DateFormat formatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
          formatter.setLenient(false);
          for (int i = 0; i < args.length; ++i)
             try
                Date date = formatter.parse(args);
    System.out.println("input: " + args[i] + " date: " + date);
    catch (ParseException e)
    System.err.println(args[i] + " is not a valid date");
    and got this when I input "2007/00/10":
    com.intellij.rt.execution.application.AppMain DateFormatTest 2007/00/10
    2007/00/10 is not a valid date
    Process finished with exit code 0%

  • Help parse date : MMM dd, yyyy hh:mm:ss a zzz

    I don't know how to get this to work. It parses but give me a wrong date all the time:
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    public class DateParserTest {
        public DateParserTest() {
        public static void main(String [] argv) {
            //Nov 17, 2006 1:00:00 PM MST<
            String sdate = "Nov 17, 2006 1:00:00 PM MST";
            Date date = extractDate(sdate);
            System.out.println("Orig date: " + sdate);
            System.out.println("Current date: " + date.toString());
        public static Date extractDate(String data) {
            SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy hh:MM:ss a zzz"); //zzz
            try {
                Date date = sdf.parse(data);
                return date;
            } catch (ParseException ex) {
                ex.printStackTrace();
                return null;
    }

    Instead of:
    "MMM dd, yyyy hh:MM:ss a zzz"you should have:
    "MMM dd, yyyy hh:mm:ss a zzz"Minutes are lowercase m's

  • Strange result of SimpleDateFormat.parse()

    Hi,
    I'm having trouble with the parse data function as it does not return the correct hour.
    Here is what I'm doing:
    Date nullDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse("1900-01-01T00:00:00-0000");I would now expect nullDate to be Mon Jan 01 00:00:00 CET 1900
    But instead, it is Mon Jan 01 00:09:21 CET 1900
    Personally I cannot think of a reason why the time is not 0.
    Any ideas?

    I don't see the problem you see. What version of Java on what OS and in what time zone?
    P.S. I would certainly set the time zone for the parser i.e.
           SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
            parser.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date nullDate = parser.parse("1900-01-01T00:00:00-0000");
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
            System.out.println(formatter.format(nullDate));On my Ubuntu 10.04 using JDK 1.6.0_20 in London (currently GMT) time zone I get
    1900-01-01 00:00:00 GMT

  • Parsing date from JSON response

    Is there any helper method to parse date time value being returned in JSONResponse to get java.util.Date. For example, 2012-06-26T15:51:59.078-05:00. I have done simple java method using SimpleDateFormat, but that does not handle all possible formats. Anyone has ideas on libraries that can be used for this purpose?
    Chandresh

    Oh I see you receive different formats from different services, who's backend you can not modify.
    I found this, it should help you get the job done:
    http://stackoverflow.com/questions/4024544/how-to-parse-dates-in-multiple-formats-using-simpledateformat
    Note however, that his problem is only relatively simplistic, yours on the other hand seems to be one of a kind where you have to be set up a pretty nifty algorithm taking care of all the different possible formats. That being said, there is no method which can parse ANY format you throw at it. you must write one yourself which knows which possible formats to expect.
    If its only those two formats you can expect:
    2012-06-26T15:51:59.078-05:00
    2012-06-26T15:51:59-05:00
    it should be an easy try-catch construct within a helper method. just be sure to use the right letters when setting up your SimpleDateFormat parse object, it's case sensitive and one quickly gets lost in all those letters.
    Edit:
    Again this should do the trick:
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSz");
    Just make sure you remove the last ":" from the JSONString (simple string manipulation) and then have two cases
    //removing last ":" from JSONString
    //====
    //Parsing string to date or gregCalendar
    GregorianCalendar time= new GregorianCalendar();
    try{
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSz");
    time.setTime(sdf.parse(JSONString));
    catch{
    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");
    time.setTime(sdf2.parse(JSONString));
    Edited by: Pascal B on 05.07.2012 04:50
    Edited by: Pascal B on 05.07.2012 04:55

  • Parsing Date Problem

    I have date problem that I am finding hard to resolve. Please
    suggest me what I could do.
    I want to parse String Date values of formats like "19 Jun 2003" and
    "19/06/2003" to a Date object.
    Can I Do it.
    Thanking in Advance.

    Sure. See SimpleDateFormat#parse.
    Kind regards,
      Levi

  • SimpleDateFormat parsing problem

    Hi All,
    I am creating a date "12142007 14:30" by parsing this string with the SimpleDateFormat object. However, when I convert it back to string and ask it to spit it out it gives me a completely different date of "Sun Jun 14 14:00:00 CDT 2009".
    Am I missing something here ? Not sure if i have to put something in the parse position. Any help would be appreciated.
    Thanks and Regards,
    *public void test2() throws Exception{*
    *          SimpleDateFormat sdf3 = new SimpleDateFormat("MMddyyyy HH:MM");*
    *          Date theDate = sdf3.parse("12142007 14:30");*
    *          System.out.println(theDate.toString());          *
    Edited by: mikematic_wha on Dec 14, 2007 9:42 AM

    PeterBro wrote:
    Try that again with the spelling corrected
    public void Calest()
              String tempDate = textField2.getText(); // ie 20080128
              SimpleDateFormat ofd = new SimpleDateFormat("yyyyMMdd");
         Date tod = odf.parse(tempDate); // this line errors
         }Peter,
    Why don't you return to the thread you started where you got a couple of answers and if you have a follow up question post it there.
    [http://forum.java.sun.com/thread.jspa?threadID=5290540]

  • UrGEnt HELP ... PARSING DATE

    hello,,
    I have this string:
    String dateTime = "7/10/1996 4:50:00 PM";
    I need to convert it to Date ( Parsing) to Date Object...
    I am using this Formatting :
    SimpleDateFormat parse = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
    because I need the am/pm info also...
    but I get different format
    Wed Jul 10 16:50:00 GMT 1996
    which is wrong .. I dont know why I get it .. it should be a date object with value: "7/10/1996 4:50:00 PM";
    any help ??

    gold wrote:
    Hi !!
    Please make use of the below code,
    String dateTime = "7/10/1996 4:50:00 PM";
              SimpleDateFormat parse = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
              Date date = new Date(dateTime);
              String formatedDate = parse.format(date);
              System.out.println(formatedDate);I can't help myself I'm going to have to comment.
    To basharf,
    Please do NOT use that example at least not this part of it.
    String dateTime = "7/10/1996 4:50:00 PM";
    Date date = new Date(dateTime);The Date constructor that takes a String is deprecated. It was deprecated sometime in the previous century. Why anybody ever thought that was a good idea is beyond me. But that's a rant for another day. As I think you realize, SimpleDateFormat.parse is a better way to create a Date from a formatted String.

  • SimpleDateFormat parsing difficulty

    Hello all,
    Recently, I had to parse Strings into Dates using SimpleDateFormat. The difficulty I had was because the Strings had timezone offsets. The code below shows the 3 tests it took to create a Date object of specified TimeZone.
    Test 1
    Fails because I don't set the TimeZone for SimpleDateFormat.
    Test 2
    Works for the first String because the TimeZone matches the timezone in the String.
    Test 3
    Works for all Strings, but is cumbersome because I have to parse the end of the String myself.
    My question is this: Shouldn't SimpleDateFormat parse a String directly into a Date without having you to specify the TimeZone of that Date? This problem was very annoying to solve and goes against logic (at least mine!).
    I'm interested in any thoughts on this matter. Am I being unreasonable, or is this poorly explained in the API?
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.SimpleTimeZone;
    public class DateTests {
         private static String DATE_FORMAT = "yyyyMMddHHmmss.SSSZ";
         private static String[] TEST_DATA = {
              "20020125120434.175+0800",
              "20031101195801.942+0000",
              "20041231000159.999-0536",
              "20050220165427.531-1100"
         private static int MINUTE = 60 * 1000; //in milliseconds
         private static int HOUR = 60 * MINUTE;
         public static void main(String[] args) {
              test1();
              test2();
              test3();
         private static void test1() {
              System.out.println("**** TEST 1 ****\n");
              DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
              formatter.setLenient(false); //want to check that dates are valid
              for (String dateString : TEST_DATA) {
                   try {
                        Date date = formatter.parse(dateString);
                        System.out.println("Success! The date is: "+date.toString());
                   } catch (ParseException e) {
                        System.out.println(dateString + " has error index of: " + e.getErrorOffset());
              //out of curiousity, lets see the String representation of the current date & time
              Date now = new Date();
              String currentDate = formatter.format(now);
              System.out.println("\nThe current date as a String: "+currentDate);
              System.out.println("\n");
         private static void test2() {
              System.out.println("**** TEST 2 ****\n");
              DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
              formatter.setLenient(false); //want to check that dates are valid
              //lets make the timezone +0800
              formatter.setTimeZone(new SimpleTimeZone(8 * HOUR, "GMT")); //8 hour offset
              for (String dateString : TEST_DATA) {
                   try {
                        Date date = formatter.parse(dateString);
                        System.out.println("Success! The date is: "+date.toString());
                   } catch (ParseException e) {
                        System.out.println(dateString + " has error index of: " + e.getErrorOffset());
              System.out.println("\nSuccess for the first date. Why? The timezone of the formatter matches the date.");
              System.out.println("\n");
         private static void test3() {
              System.out.println("**** TEST 3 ****\n");
              DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
              formatter.setLenient(false); //want to check that dates are valid
              for (String dateString : TEST_DATA) {
                   try {
                        //lets set a timezone for each individual date
                        int length = dateString.length();
                        int gmtMinutes = Integer.parseInt(dateString.substring(length-2, length));
                        int gmtHours = Integer.parseInt(dateString.substring(length-4, length-2));
                        int timeZone = gmtMinutes * MINUTE + gmtHours * HOUR;
                        timeZone = dateString.charAt(length-5) == '+' ? timeZone : -timeZone;
                        formatter.setTimeZone(new SimpleTimeZone(timeZone, "GMT"));
                        Date date = formatter.parse(dateString);
                        System.out.println("Success! The date is: "+date.toString());
                   } catch (ParseException e) {
                        System.out.println(dateString + " has error index of: " + e.getErrorOffset());
    }-Muel

    Date objects don't have time zones.
    This is true, my problem was that I needed to parse both the Date and the TimeZone from a String. I got misled by the SimpleDateFormat documentation (the symbol Z), and somehow got the impression that a Date should have an associated TimeZone!
    In hindsight, it is clear that Z should be used for Date strings containing a timezone and that SimpleDateFormat uses the timezone to modify the Date so that it's correct for the timezone of the current machine. If that makes sense!
    -Muel

  • How do i parse data from the second jframe back to the first?

    Hello.
    I have a jFrame were I promt users to keep a list of Names in a jTable. (I keep data for something else, but lets say names.. ) Anyway, afterwords I want to add some extra parameters for each name. So I created a new frame, which is opened when user press an Edit button. The new frame opens and users can add for the specific name some extra data, like age, height, color, sex.. etc. that characterizes this person.
    On this second form i have a save button, which when its pressed i would like to keep this information for this name, so as when user press edit again from the first frame on the same Name the data that previously entered will be loaded (lets say that the user can not enter the say name again)
    I haven' t figured the code for the save Button, but with the rest I am fine.
    Can you give any ideas with structures that I have to use and how the action listener will have to be??
    When I set visible the new form i have made a constructor that loads the new form which have a label with the name of the person that is edited., but how do i parse data from the second form back to the first that is already opened??
    Thanks very much..

    I found it.. it was not so hard afterall..
    anyway, i quote the new code..
    package namelist;
    // Java core packages
    import java.awt.event.*;
    import java.util.*;
    // Java extension packages
    import javax.swing.*;
    import javax.swing.table.*;
    public class NamesGUI extends javax.swing.JFrame {
        //Variables for managing the jTables
        DefaultTableModel tableModel;
        Vector rows,cols;
        String[] colName1 = {"List of Names"};
        ManageJTables mJT = new ManageJTables();
        Hashtable h;
        /** Creates new form ProsAgentGUI */
        public NamesGUI() {
            h = new Hashtable();
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        private void initComponents() {
            Panel = new javax.swing.JPanel();
            ToolBar = new javax.swing.JToolBar();
            ADD = new javax.swing.JButton();
            EDIT = new javax.swing.JButton();
            REMOVE = new javax.swing.JButton();
            jButton1 = new javax.swing.JButton();
            TScrollPane = new javax.swing.JScrollPane();
            Table = new javax.swing.JTable();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Names");
            setBackground(new java.awt.Color(0, 51, 51));
            Panel.setBorder(javax.swing.BorderFactory.createTitledBorder("List of Names"));
            ToolBar.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
            ADD.setText("ADD");
            ADD.setToolTipText("");
            ADD.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
            ADD.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    ADDActionPerformed(evt);
            ToolBar.add(ADD);
            EDIT.setText("EDIT");
            EDIT.setToolTipText("");
            EDIT.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
            EDIT.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    EDITActionPerformed(evt);
            ToolBar.add(EDIT);
            REMOVE.setText("REMOVE");
            REMOVE.setToolTipText("");
            REMOVE.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
            REMOVE.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    REMOVEActionPerformed(evt);
            ToolBar.add(REMOVE);
            jButton1.setText("jButton1");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            ToolBar.add(jButton1);
            rows=new Vector();
            cols= new Vector();
            cols=mJT.addColumns(colName1, cols);
            tableModel =new DefaultTableModel();
            tableModel.setDataVector(rows,cols);
            Table.setModel(tableModel);
            TScrollPane.setViewportView(Table);
            org.jdesktop.layout.GroupLayout PanelLayout = new org.jdesktop.layout.GroupLayout(Panel);
            Panel.setLayout(PanelLayout);
            PanelLayout.setHorizontalGroup(
                PanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(ToolBar, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE)
                .add(TScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE)
            PanelLayout.setVerticalGroup(
                PanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(PanelLayout.createSequentialGroup()
                    .add(ToolBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 34, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(TScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 159, Short.MAX_VALUE))
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(Panel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap())
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(29, Short.MAX_VALUE)
                    .add(Panel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap())
            pack();
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
            System.out.println(h.toString());
    public void updateNamesTable (int id, String na){
         Integer i2 = new Integer(id);
         Object o2 = (Object)i2;
         if (h.containsKey(o2)){
            Name a = (Name)h.get(o2);
            a.name = na;
            h.put(o2,a);
         else {
             Name aa = new Name();
             aa.name=na;
             h.put(o2,(Object)aa);
        private void EDITActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
            String name = Table.getValueAt(Table.getSelectedRow(),0).toString();
            int rowNum= Table.getSelectedRow();
            Integer i = new Integer(rowNum);
            Object o = (Object)i;
            updateNamesTable (rowNum, name);
            //public NameEditor(Name n,  Hashtable h, int id)
            NameEditor re = new NameEditor((Name)h.get(o), h, rowNum );
            re.setVisible(true);
        private void REMOVEActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
            mJT.deleteRow(Table.getSelectedRow(), rows, Table);
        private void ADDActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
            mJT.addRow(rows, Table);
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NamesGUI().setVisible(true);
        // Variables declaration - do not modify
        javax.swing.JButton ADD;
        javax.swing.JButton EDIT;
        javax.swing.JPanel Panel;
        javax.swing.JButton REMOVE;
        javax.swing.JScrollPane TScrollPane;
        javax.swing.JTable Table;
        javax.swing.JToolBar ToolBar;
        javax.swing.JButton jButton1;
        // End of variables declaration
    public class NameEditor extends javax.swing.JFrame {
        Hashtable h;
        Name n;
        int id;
        /** Creates new form NameEditor */
        public NameEditor() {
            initComponents();
        public NameEditor(Name n,  Hashtable h, int id) {
            this.h=h;
            this.n=n;
            this.id=id;
            initComponents();
            NameField.setText(n.name);
            jTextField2.setText(n.weight);
            jTextField1.setText(n.height);
            setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        private void initComponents() {
            NameLabel = new javax.swing.JLabel();
            NameField = new javax.swing.JTextField();
            SaveBut = new javax.swing.JButton();
            jLabel3 = new javax.swing.JLabel();
            jLabel4 = new javax.swing.JLabel();
            jTextField1 = new javax.swing.JTextField();
            jTextField2 = new javax.swing.JTextField();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Name Editor");
            getAccessibleContext().setAccessibleName("Name Editor");
            NameLabel.setText("Name: ");
            NameField.setEditable(false);
            NameField.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    NameFieldActionPerformed(evt);
            SaveBut.setText("SAVE");
            SaveBut.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    SaveButActionPerformed(evt);
            jLabel3.setText("Height");
            jLabel4.setText("Weight");
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                        .add(layout.createSequentialGroup()
                            .addContainerGap()
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                .add(layout.createSequentialGroup()
                                    .add(jLabel4)
                                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED))
                                .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                        .add(jLabel3)
                                        .add(NameLabel))
                                    .add(16, 16, 16)))
                            .add(17, 17, 17)
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                .add(NameField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 138, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                                    .add(org.jdesktop.layout.GroupLayout.LEADING, jTextField2)
                                    .add(org.jdesktop.layout.GroupLayout.LEADING, jTextField1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 46, Short.MAX_VALUE))))
                        .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                            .add(127, 127, 127)
                            .add(SaveBut)))
                    .addContainerGap())
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(NameLabel)
                        .add(NameField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(30, 30, 30)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jLabel3)
                        .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(12, 12, 12)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jLabel4)
                        .add(jTextField2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 27, Short.MAX_VALUE)
                    .add(SaveBut)
                    .addContainerGap())
            pack();
        public void updateNameTable (){
         Integer i2 = new Integer(id);
         Object o2 = (Object)i2;
         h.put(o2,n);       
        private void SaveButActionPerformed(java.awt.event.ActionEvent evt) {                                       
    // TODO add your handling code here:
            n.height= jTextField1.getText();
            n.weight = jTextField2.getText();
        private void NameFieldActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NameEditor().setVisible(true);
        // Variables declaration - do not modify
        javax.swing.JTextField NameField;
        javax.swing.JLabel NameLabel;
        javax.swing.JButton SaveBut;
        javax.swing.JLabel jLabel3;
        javax.swing.JLabel jLabel4;
        javax.swing.JTextField jTextField1;
        javax.swing.JTextField jTextField2;
        // End of variables declaration
    }

  • How do I create individual xml files from the parsed data output of a xml file?

    I have written a program (DOM Parser) that parses data from a XMl File. I would like to create an individual file with the corresponding name for each set of data parsed from the xml document. If the parsed output is Single, Double, Triple, I would like to create an individual xml file (Single.xml, Double.xml, Triple.xml)with those corresponding names. How do I create the xml files and give each file the name of my parsed data output? Thanks in advance for your help.
    import java.io.IOException;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    public class MyDomParser {
      public static void main(String[] args) {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      try {
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document doc = builder.parse("ENtemplate.xml");
      doc.normalize();
      NodeList rootNodes = doc.getElementsByTagName("templates");
      Node rootNode = rootNodes.item(0);
      Element rootElement = (Element) rootNode;
      NodeList templateList = rootElement.getElementsByTagName("template");
      for(int i=0; i < templateList.getLength(); i++) {
      Node theTemplate = templateList.item(i);
      Element templateElement = (Element) theTemplate;
      System.out.println("Template" + ": " +templateElement.getAttribute("name")+ ".xml");
      } catch (ParserConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      } catch (SAXException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();

    Ive posted the new code but now I'm getting a FileAlreadyExistException error. How do I handle this exception error correctly in my code?
    import java.io.IOException;
    import java.nio.file.FileAlreadyExistsException;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    public class MyDomParser {
      public static void main(String[] args) {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      try {
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document doc = builder.parse("ENtemplate.xml");
      doc.normalize();
      NodeList rootNodes = doc.getElementsByTagName("templates");
      Node rootNode = rootNodes.item(0);
      Element rootElement = (Element) rootNode;
      NodeList templateList = rootElement.getElementsByTagName("template");
      for(int i=0; i < templateList.getLength(); i++) {
      Node theTemplate = templateList.item(i);
      Element templateElement = (Element) theTemplate;
      System.out.println(templateElement.getAttribute("name")+ ".xml");
      for(int i=0; i < templateList.getLength(); i++) {
      Node theTemplate = templateList.item(i);
      Element templateElement = (Element) theTemplate;
      String fileName = templateElement.getAttribute("name") + ".xml";
      Files.createFile(Paths.get(fileName));
      System.out.println("File" + ":" + fileName + ".xml created");
      } catch (ParserConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      } catch (SAXException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();

  • Implementing Database codes FAIL /error in parsing data into jsp page

    Hi there,
    I have this problem trying to build a portal application. I am using the JSPDynPage, jsp page and a bean to build a page.
    I have this problem parsing data from JSPDynPage to the beans and to the jsp page.
    I tested out the connection between the beans and the jsp page. There is no error parsing information from the beans to the jsp page.
    So i tried to test out the codes for the database from the beans.
    Will this work? Because it does not display the results i want.
    I need an Solution asap to find out wad is wrong also also the correct codes to the database.
    public String db(){
    try {
                 InitialContext iC = new InitialContext();
                 DataSource dataSource = (DataSource)iC.lookup("java:env/jdbc/mySQL");
                 java.sql.Connection connection = dataSource.getConnection();
                 PreparedStatement st = connection.prepareStatement("SELECT name FROM test WHERE id='123'");
                 ResultSet resultSet = st.executeQuery();
                 while (resultSet.next()){
                      name = resultSet.getString("name");
                      name = name.toString();
                 connection.close();
                 return name;
                 } catch(Exception n){
                      e = "Exception";
                      return e;
    This is the method i put in the beans to test out the database connection.
    Thanks Loads
    Quatre

    Hi there,
    Thanks for the reply, i thought that no one is going to reply me anymore. Thanks loads.
    Bean Class name: Bean1
    Bean Packeage name: Beans1
    Bean id : myBean1
    Jsp Codes
    <%@ taglib uri="tagLib" prefix="hbj" %>
    <jsp:useBean id="myBean1" scope="application" class="Beans1.Bean1" />
    <hbj:content id="myContext" >
      <hbj:page title="PageTitle">
       <hbj:form id="myFormId" >
       <hbj:textView id = "ll" text="lalalalalalalalalasasa" />
      <%--
    <hbj:textView id = "l">
                   <% l.setName(myBean1.getName());%>
    </hbj:textView>
    --%>
    <hbj:textView
                    id="appraisal_yr_label"
                    text="Apprasial Year:">
                    </hbj:textView>
                    <hbj:textView id = "la" >
                    <% la.setText(myBean1.getName());%>
                    </hbj:textView>
       </hbj:form>
      </hbj:page>
    </hbj:content>
    Beans1.java
    package Beans1;
    import java.io.Serializable;
    public class Bean1 implements Serializable{
    private String name = new String();
    private String e = new String();
    private String year = new String();
         public void setName(String name){
              this.name = name;
         public String getName(){
              return name;
    JSPDynPage
    import Beans1.Bean1;
    import com.sapportals.htmlb.*;
    import com.sapportals.htmlb.enum.*;
    import com.sapportals.htmlb.event.*;
    import com.sapportals.htmlb.page.*;
    import com.sapportals.portal.htmlb.page.*;
    import com.sapportals.portal.prt.component.*;
    public class testDBv5 extends PageProcessorComponent {
    import Beans1.Bean1;
    import com.sapportals.htmlb.*;
    import com.sapportals.htmlb.enum.*;
    import com.sapportals.htmlb.event.*;
    import com.sapportals.htmlb.page.*;
    import com.sapportals.portal.htmlb.page.*;
    import com.sapportals.portal.prt.component.*;
    public class testDBv5 extends PageProcessorComponent {
      public DynPage getPage(){
        return new testDBv5DynPage();
      public static class testDBv5DynPage extends JSPDynPage{
        private Bean1 myBean1= null;
        private String name = new String();
        public void doInitialization(){
              try{
                                  IntitialContext context = new javax.naming.InitialContext();
                                  DataSource dataSource = (DataSource)context.lookup("java:env/jdbc/appDB");
                                  Connection connection = dataSource.getConnection();
                                  Statement stmt = connection.createStatement();
                                  ResultSet rs = stmt.executeQuery("Select AppraisalYear From tblAppraisal Where AppraisalYear='2007'");
                                          while(rs.next()){
                                            year = rs.getString("AppraisalYear");
                                            rs.close();
                                            stmt.close();
                                            connection.close();
                                            return year;
                                       }catch (Exception n){
                                            n.printStackTrace();
              IPortalComponentProfile profile = ((IPortalComponentRequest)getRequest()).getComponentContext().getProfile();
                     Object o = profile.getValue("myBean1");
                     if(o==null || !(o instanceof Bean1)){
                        myBean1 = new Bean1();
                        profile.putValue("myBean1",myBean1);
                     } else {
                          myBean1 = (Bean1) o;
                        Object value = request.getSession().getValue("myBeans1");
                        if (value==null || (value instanceof Bean1)){
                             myBean1 = new Bean1();
                        request.getSession().putValue("myBean1", Object value);
              DataBase cn = new DataBase();
              name = cn.dataBaseConnection();
              myBean1.setName(name);
    //name = "gir";
    //myBean1.setName(name);
    // IPortalComponentRequest request = (IPortalComponentRequest) this.getRequest();
    //IPortalComponentContext myContext = request.getComponentContext();
    //Bean1 myNameContainer = (Bean1) myContext.getValue("myBean1");
    //myNameContainer.setName(name);
          // fill your bean with data here...
        public void doProcessAfterInput() throws PageException {
        public void doProcessBeforeOutput() throws PageException {
          this.setJspName("testDBv5.jsp");
    //testing purpose
      public static void main (String[] arg){
         testDBv5DynPage ef = new testDBv5DynPage();
               ef.doInitialization();
    Thanks Loads
    Quatre

Maybe you are looking for