Truncate byte array of UTF-8 characters without corrupting the data?

Hi all,
I need to be able to determine if the byte array, which is truncated from the original byte array representing UTF-8 string, contains corrupted character. Knowing if the byte array contains corrupted character allows me to remove it from the truncated array.
As in the sample code below, when truncate the string with 16 bytes it displays ok. However, truncate with 17 bytes, the last character is corrupted. Is there a way to check to see if the character is corrupted so that it can be removed from the truncated byte array?
Thanks in advance,
Phuong
PS: The Japanese characters I chose it randomly from Unicode charts. I don't know their meaning so if it is offensive, please forgive me.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.UnsupportedEncodingException;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class TestTruncateUTF8 extends JFrame
    private static final long serialVersionUID = 1L;
    private JTextArea textArea = new JTextArea(5,20);
    private JLabel japanese = new JLabel("Japanese: " + "\u65e5\u672c\u3041\u3086\u308c\u306e");
     * @param args
    public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run()
                JFrame frame = new TestTruncateUTF8();
                frame.setVisible(true);
    public TestTruncateUTF8()
        super("Test Truncated");
        JButton truncate17Button = new JButton("Truncate 17 bytes");
        truncate17Button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e)
                truncates(17);
        JButton truncate16Button = new JButton("Truncate 16 bytes");
        truncate16Button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e)
                truncates(16);
        JPanel panel1 = new JPanel();
        panel1.setLayout(new BoxLayout(panel1, BoxLayout.Y_AXIS));
        panel1.add(japanese);
        panel1.add(truncate16Button);
        panel1.add(truncate17Button);
        panel1.add(new JScrollPane(textArea));
        this.setLayout(new BorderLayout());
        this.add(panel1, BorderLayout.CENTER);
        this.pack();
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    private void truncates(int numOfBytesToTruncate)
        try
            byte[] bytes = japanese.getText().getBytes("UTF-8");
            byte[] newBytes = new byte[numOfBytesToTruncate];
            System.arraycopy(bytes, 0, newBytes, 0, numOfBytesToTruncate);
            TestTruncateUTF8.this.putTextInsideJTextArea(bytes, newBytes);
        catch (UnsupportedEncodingException e1)
            e1.printStackTrace();
    private void putTextInsideJTextArea(byte[] original, byte[] truncated)
        try
            textArea.append("\nOriginal String:  " + new String(original, "UTF-8"));
            textArea.append("\nTruncated String: " + new String(truncated, "UTF-8"));
            textArea.append("\n*****************************\n");
        catch (UnsupportedEncodingException e)
            e.printStackTrace();
}

Since the byte array is in UTF-8, you can easily examine whether it is corrupt or not by taking a look at the last 4 bytes (at most). That is because the bit distribution of each byte (1st, 2nd, 3rd, and 4th) in UTF-8 encoding is well defined in its spec.
BTW, a Japanese Hiragana/Kanji character typically has 3 bytes in UTF-8, so truncating with neither 16 nor 17 bytes would produce correct truncation.
HTH,
Naoto

Similar Messages

  • Convertion of byte array in UTF-8 to GSM character set.

    I want to convert byte array in UTF-8 to GSM character set. Please advice How can I do that?

    String s = new String(byteArrayInUTF8,"utf-8");This will convert your byte array to a Java UNICODE UTF-16 encoded String on the assumption that the byte array represents characters encoded as utf-8.
    I don't understand what GSM characters are so someone else will have to help you with the second part.

  • Using the Insert statement in a Java program without hardcoding the data

    hello.
    this is james mcfadden. i have developed a program called Demo.java, which is used with another program called QueryTableModel.java (a program that allows data to be viewed in a JTable). The Demo.java program displays a menu, connects to a database, allows the user to add data into the database and allows the user to view data that is already in the database. I have a problem with the Demo.java program. I have hardcoded the Insert statement in it. How do you use the Insert statement to put data into a database without hardcoding the data?
    import java.awt.*;//Contains all of the classes for creating user interfaces and for painting graphics and images
    import java.awt.event.*;//Provides interfaces and classes for dealing with different types of events fired by AWT components
    import javax.swing.*;//Provides a set of lightweight components that, to the maximum degree possible, work the same on all platforms
    import javax.swing.table.*;//Provides classes and interfaces for dealing with javax.swing.JTable
    import javax.swing.JOptionPane;//provides a class that makes it easy to pop up a standard dialog box that prompts users for a value or informs them of something
    import java.sql.*;//Provides the API for accessing and processing data stored in a data source using the Java programming language
    public class Demo extends JFrame{
       static String url = "jdbc:odbc:VideoLibrary";//a static variable that allows a connection to be made to a database called VideoLibrary
       static Statement stmt;//a static variable that allows a statement to be made once a connection is set up
       static Connection con;//a static interface that allows a connection to be made to a database
         //global variables
         JTextField hostField;//a class that allows a line of text to be changed
       JTextField queryField;//a class that allows a line of text to be changed
       QueryTableModel qtm;//a class that shows and changes regular two-dimensional tables of cells
       JComboBox comboBox;//a class that puts a button or editable field and a drop-down list together 
       public static void main(String args[]){     
          int choice=-1;//a variable of type int that is set to -1
              do{
             choice=getChoice();//invokes the method getChoice()
             if(choice!=0){
                getSelected(choice);//invokes the method getSelected(choice)
             }//end if
                   //if the user chooses 5, it will cause him or her to exit the system
          }while(choice!=5);//end do-while
          System.exit(0);//closes down the menu screen
       }//end main
       public static int getChoice(){
          String choice;//a variable of type string
          int ch;//a variable of type int
          choice = JOptionPane.showInputDialog(null,"1. Maintain product details\n"+"2. Maintain member details\n"+"3. Maintain rental details\n"+"4. View product, member and rental details\n"+"5. Log Off\n\n"+"Enter your choice");//asks the user for some input   
              ch = Integer.parseInt(choice);//a class that wraps a value of the primitive type int in an object     
              return ch;//a method that returns an integer value
       }//end getChoice
       public static void getSelected(int choice){   
              if(choice==1){
             maintainProductDetails();//invokes the method maintainProductDetails()
          }//end if
          if(choice==2){
             maintainMemberDetails();//invokes the method maintainMemberDetails()
          }//end if
              if(choice==3){
             maintainRentalDetails();//invokes the method maintainRentalDetails()
          }//end if
              if(choice==4){
                 Demo test = new Demo();//invokes the constructor Demo()
             test.setVisible(true);//shows the JTable component by marking it as visible
              }//end if
       }//end getSelected
       public static Connection getConnection(){
          try {
             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//used to create a JDBC connection using a database
          }//end try
              catch(java.lang.ClassNotFoundException e){//causes an exception to be thrown when an application tries to load in a class through its string name
             System.err.print("ClassNotFoundException: ");//displays an error message
             System.err.println(e.getMessage());//returns the exception that was raised if an error occurred while attempting to load the ClassNotFoundException class
          }//end catch
          try {
             con=DriverManager.getConnection(url,"","");//tries to create a connection with the database using the DriverManager class
          }//end try
              catch(SQLException ex) {
             System.err.println("SQLException: " + ex.getMessage());//returns an SQL error message
          }//end catch
          return con;
       }//end getConnection
       public static void maintainProductDetails(){
          Connection con = getConnection();//creates a connection with the database
          String  addProduct1, addProduct2, addProduct3, addProduct4, addProduct5, addProduct6, addProduct7, addProduct8, addProduct9, addProduct10;//string variables that represent information about the different types of product data that will be stored in the database
          addProduct1 = "insert into Product values (110001, 'The Killers - Sams Town', 5.00, 'G', 'CD', 2006)";
          addProduct2 = "insert into Product values (110002, 'Robbie Williams - Rudebox', 5.00, 'G', 'CD', 2006)";
          addProduct3 = "insert into Product values (110003, 'Razorlight - Razorlight', 5.00, 'G', 'CD', 2006)";
          addProduct4 = "insert into Product values (110004, 'My Chemical Romance - The Black Parade', 5.00, 'G', 'CD', 2006)";
          addProduct5 = "insert into Product values (110005, 'Snow Patrol - Eyes Open', 5.00, 'G', 'CD', 2006)";
          addProduct6 = "insert into Product values (110006, 'Scissor Sisters - Ta-Dah!', 5.00, 'G', 'CD', 2006)";
              addProduct7 = "insert into Product values (110007, 'Lovesounds - Justin Timberlake', 5.00, 'G', 'CD', 2006)";
          addProduct8 = "insert into Product values (110008, 'Director - We thrive on big cities', 5.00, 'G', 'CD', 2006)";
          addProduct9 = "insert into Product values (110009, 'Roxette - Roxette hits', 5.00, 'G', 'CD', 2006)";
          addProduct10 = "insert into Product values (110010, 'Pussy Cat Dolls - PCD', 5.00, 'G', 'CD', 2006)";
              try {
             stmt = con.createStatement();//Creates a Statement object for sending SQL statements to the database
                 //statements are allowed to be made once a connection is set up
                 stmt.executeUpdate(addProduct1);
             stmt.executeUpdate(addProduct2);
             stmt.executeUpdate(addProduct3);
             stmt.executeUpdate(addProduct4);
                   stmt.executeUpdate(addProduct5);
             stmt.executeUpdate(addProduct6);
                 stmt.executeUpdate(addProduct7);
             stmt.executeUpdate(addProduct8);
             stmt.executeUpdate(addProduct9);
             stmt.executeUpdate(addProduct10);
             stmt.close();//closes the Statement object
             con.close();//terminates the connection with the database
          }//end try
              catch(SQLException ex) {
             System.err.println("SQLException: " + ex.getMessage());//returns an SQL error message
          }//end catch
       }//end maintainProductDetails
       public static void maintainMemberDetails(){
          Connection con = getConnection();//creates a connection with the database
          String addMember1, addMember2, addMember3, addMember4, addMember5, addMember6, addMember7, addMember8, addMember9, addMember10;//string variables that represent information about the member data that will be stored in the database
          addMember1 = "insert into Member values (1234, 'Ann', 'Smyth', 'Upper Killult, Falcarragh, Co. Donegal', '(074)-9135210', '(087)-2030172', #5/11/85#, #5/12/06#)";
          addMember2 = "insert into Member values (2345, 'John', 'Murphy', 'Lower Killult, Falcarragh, Co. Donegal', '(074)-9135211', '(087)-2030173', #4/12/85#, #6/13/06#)";
          addMember3 = "insert into Member values (1324, 'James', 'McFadden', 'Lower Ardsbeg, Gortahork, Co. Donegal', '(074)-9165314', '(087)-2030171', #4/11/85#, #6/14/06#)";
          addMember4 = "insert into Member values (1235, 'Frankie', 'Ferry', 'Ardsmore, Gortahork, Co. Donegal', '(074)-9165325', '(087)-2031234', #6/13/60#, #6/15/06#)";
          addMember5 = "insert into Member values (1236, 'Daniel', 'McKimm', 'Ballyness, Falcarragh, Co. Donegal', '(074)-9135212', '(087)-2030184', #5/14/73#, #6/16/06#)";
          addMember6 = "insert into Member values (2346, 'Stephen', 'Doohan', 'Ballyness, Falcarragh, Co. Donegal', '(074)-9135213', '(087)-2030185', #6/13/85#, #5/13/06#)";
          addMember7 = "insert into Member values (2347, 'James', 'Ferry', 'Meenlaragh, Gortahork, Co.Donegal', '(074)-9165360', '(087)-2031345', #9/12/85#, #5/14/06#)";
          addMember8 = "insert into Member values (2348, 'Liam', 'Cannon', 'Derryconner, Gortahork, Co.Donegal', '(074)-9165324', '(087)-2031456', #4/11/86#, #5/15/06#)";
          addMember9 = "insert into Member values (2401, 'Ciaran', 'Ferry', 'Brinalack, Gweedore, Co.Donegal', '(074)-9176425', '(087)-2030282', #9/12/85#, #5/16/06#)";
          addMember10 = "insert into Member values (2402, 'Ciaran', 'McGee', 'Derrybeg, Gweedore, Co.Donegal', '(074)-9176536', '(087)-2030393', #9/14/85#, #5/18/06#)";
          try{
             stmt = con.createStatement();//Creates a Statement object for sending SQL statements to the database
                   //statements are allowed to be made once a connection is set up
                   stmt.executeUpdate(addMember1);
             stmt.executeUpdate(addMember2);
             stmt.executeUpdate(addMember3);
                   stmt.executeUpdate(addMember4);
                   stmt.executeUpdate(addMember5);
                   stmt.executeUpdate(addMember6);
                   stmt.executeUpdate(addMember7);
                   stmt.executeUpdate(addMember8);
                   stmt.executeUpdate(addMember9);
                   stmt.executeUpdate(addMember10);
             stmt.close();//closes the Statement object
             con.close();//terminates the connection with the database
          }//end try
              catch(SQLException ex) {
             System.err.println("SQLException: " + ex.getMessage());//returns an SQL error message
          }//end catch
       }//end maintainMemberDetails
         public static void maintainRentalDetails(){
          Connection con = getConnection();//creates a connection with the database
          String addRental1, addRental2, addRental3, addRental4, addRental5, addRental6, addRental7, addRental8, addRental9, addRental10;//string variables that represent information about the loan data that will be stored in the database
          addRental1 = "insert into Rental values (110001, 'The Killers - Sams Town', 1234, 'Ann', 'Smyth', #9/01/06#, #9/10/06#, 'Yes', 2.00)";
          addRental2 = "insert into Rental values (120001, 'Mission Impossible 3', 2345, 'John', 'Murphy', #9/02/06#, #9/09/06#, 'No', 0.00)";
          addRental3 = "insert into Rental values (130001, 'Need for Special Carbon', 1324, 'James', 'McFadden', #9/03/06#, #9/12/06#, 'Yes', 2.00)";
          addRental4 = "insert into Rental values (110002, 'Robbie Williams - Rudebox', 1235, 'Frankie', 'Ferry', #9/04/06#, #9/11/06#, 'No', 0.00)";
          addRental5 = "insert into Rental values (120015, 'Prime', 1236, 'Daniel', 'McKimm', #9/05/06#, #9/14/06#, 'Yes', 2.00)";
          addRental6 = "insert into Rental values (130015, 'FIFA 07', 2346, 'Stephen', 'Doohan', #9/06/06#, #9/13/06#, 'No', 0.00)";
          addRental7 = "insert into Rental values (110009, 'Roxette - Roxette hits', 2347, 'James', 'Ferry', #9/07/06#, #9/16/06#, 'Yes', 2.00)";
          addRental8 = "insert into Rental values (120003, 'The Break Up', 2348, 'Liam', 'Cannon', #9/08/06#, #9/15/06#, 'No', 0.00)";
          addRental9 = "insert into Rental values (130027, 'Gears of War', 2401, 'Ciaran', 'Ferry', #9/09/06#, #9/18/06#, 'Yes', 2.00)";
          addRental10 = "insert into Rental values (110021, 'Scooter - Mind the Gap', 2402, 'Ciaran', 'McGee', #9/10/06#, #9/17/06#, 'No', 0.00)";
          try{
             stmt = con.createStatement();//Creates a Statement object for sending SQL statements to the database
                   //statements are allowed to be made once a connection is set up
                   stmt.executeUpdate(addRental1);
             stmt.executeUpdate(addRental2);
             stmt.executeUpdate(addRental3);
                   stmt.executeUpdate(addRental4);
                   stmt.executeUpdate(addRental5);
                   stmt.executeUpdate(addRental6);
                   stmt.executeUpdate(addRental7);
                   stmt.executeUpdate(addRental8);
                   stmt.executeUpdate(addRental9);
                   stmt.executeUpdate(addRental10);
             stmt.close();//closes the Statement object
             con.close();//terminates the connection with the database
          }//end try
              catch(SQLException ex) {
             System.err.println("SQLException: " + ex.getMessage());//returns an SQL error message
          }//end catch
       }//end maintainRentalDetails
       public Demo(){//a constructor
          super("Demo Test Frame");//overrides the constructor
          setSize(350, 200);//Resizes this component so that it has width of 350 and height of 200 
          comboBox = new JComboBox();//invokes the class JComboBox
          comboBox.addItem("jdbc:odbc:VideoLibrary");//adds the specified item to the end of the scrolling list
          qtm = new QueryTableModel();//invokes the class QueryTableModel
          JTable table = new JTable(qtm);//a class that shows and changes regular two-dimensional tables of cells
          JScrollPane scrollpane = new JScrollPane(table);//a class that provides a scrollable view of a lightweight component
          JPanel p1 = new JPanel();//a class that puts the combo box and query field in a panel
          p1.setLayout(new GridLayout(3, 2));//Sets the layout manager for this container
          p1.add(comboBox);//Appends the specified component to the end of this container
          p1.add(new JLabel("Enter your query: "));//Appends the specified component to the end of this container
          p1.add(queryField = new JTextField());//Appends the specified component to the end of this container
          p1.add(new JLabel("Click here to send: "));//Appends the specified component to the end of this container
          JButton jb = new JButton("Search");//a class that is an implementation of a "push" button
          jb.addActionListener(new ActionListener(){//Adds an ActionListener to the button
             public void actionPerformed(ActionEvent e){
                qtm.setHostURL();//invokes the method setHostURL
                qtm.setQuery(queryField.getText().trim());//invokes the method setQuery; and returns the text that is presented by this text component and returns a copy of the string, with leading and trailing whitespaces omitted
          } );//end addActionListener
          p1.add(jb);//Appends the specified component to the end of this container
          getContentPane().add(p1, BorderLayout.NORTH);//Returns the content pane
          getContentPane().add(scrollpane, BorderLayout.CENTER);//Returns the content pane
       }//end Demo
    }//end class Demo
    import java.sql.*;//Provides the API for accessing and processing data stored in a data source using the Java programming language
    import java.io.*;//Provides for system input and output through data streams, serialization and the file system
    import java.util.Vector;//provides a class that implements a growable array of objects
    import javax.swing.*;//Provides a set of lightweight components that, to the maximum degree possible, work the same on all platforms
    import javax.swing.table.*;//Provides classes and interfaces for dealing with javax.swing.JTable
    public class QueryTableModel extends AbstractTableModel{
         Vector cache;//a class that constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero 
         int colCount;//a variable that counts the number of columns in the three tables
         String[] headers;//a class that represents character strings and all string literals in this program are implemented as instances of the String class
         Connection db;//an interface that allows a connection to be made to a database
         Statement statement;//an interface that allows executes the given SQL statement, which returns a single ResultSet object
         String currentURL;//a variable that allows the URL to be displayed in a combo box
         public QueryTableModel(){//a constructor
              cache=new Vector();//constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero
              try{
             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//used by opening a JDBC connection using an URL
              }//end try
              catch(Exception e){
                   System.out.println("problem loading the driver ");//an error message
              }//end catch
         }//end QueryTableModel
         public String getColumnName(int i){//Returns the designated column's name
            return headers;//returns the name of each column in the three table
         }//end getColumnName
         public int getColumnCount(){//Returns the number of columns in the column model
         return colCount;//returns the number of columns in the three tables
         }//end getColumnCount
         public int getRowCount(){//Returns the number of rows in this table's model
         return cache.size();//returns the number of components in the vector
         }//end getRowCount
         public Object getValueAt(int row, int col){//Returns the cell value at row and column
              return ((String[])cache.elementAt(row))[col];//Returns the component at the specified index
         }//end getValueAt
         public void setHostURL(){//sets the URL for the database
         String url = "jdbc:odbc:VideoLibrary";//a variable that allows a connection to be made to a database called VideoLibrary
         closeDB();//invokes the method closeDB()
              try{
    db=DriverManager.getConnection(url,"","");//tries to create a connection with the database using the DriverManager class
    statement=db.createStatement();//Creates a Statement object for sending SQL statements to the database
    }//end try
    catch(Exception e){
    System.out.println("Could not initialize the database.");//an error message
    e.printStackTrace();//a Throwable method that prints this throwable and it's backtrace to the standard error stream
    }//end catch
         }//end setHostURL
    public void setQuery(String q){//sets the kind of query that is to be sent to the database
              cache=new Vector();//constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero
    String s="select * from Product";//a variable that causes all the data that is in the product table to be displayed in a JTable, which also means that all the data that is in both the member and rental tables can also be displayed in a JTable
              try{
                   ResultSet rs=statement.executeQuery(q);//an interface that is used to generate a database result set by executing a statement that queries the database
                   ResultSetMetaData meta=rs.getMetaData();//an interface that is used to get information about the types and properties of the columns in a ResultSet object
                   colCount=meta.getColumnCount();//Returns the number of columns in this ResultSet object
                   headers=new String[colCount];//gets the name of each column in the three tables
                   for(int h=1;h<=colCount;h++){
                        headers[h-1]=meta.getColumnName(h);//Get the designated column's name
                   }//end for
                   while(rs.next()){
                        String[] record=new String[colCount];//stores the name of each column in the three tables in memory
                        for(int i=0;i<colCount;i++){
                             record[i]=rs.getString(i+1);//Retrieves the value of the designated column in the current row of this ResultSet object as a String
                        }//end for
                        cache.addElement(record);//Adds the specified component to the end of this vector, increasing its size by one
                   }//end while
                   fireTableChanged(null);//Forwards the given notification event to all TableModelListeners that registered themselves as listeners for this table model
              }//end try
              catch(Exception e){
                   cache=new Vector();//constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero
                   e.printStackTrace();//a Throwable method that prints this throwable and it's backtrace to the standard error stream
              }//end catch
         }//end setQuery
         public void initDB(String url){
              try{
                   db=DriverManager.getConnection(url);//tries to create a connection with the database using the DriverManager class
                   statement=db.createStatement();//Creates a Statement object for sending SQL statements to the database
              }//end try
              catch(Exception e){
                   System.out.println("Could not initialize the database.");//an error message
                   e.printStackTrace();//a Throwable method that prints this throwable and it's backtrace to the standard error stream
              }//end catch
         }//end initDB
         public void closeDB(){
              try{
                   if(statement!=null){
                   statement.close();//Releases this Statement object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed
                   }//end if
                   if(db!=null){
                   db.close();//Releases this Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released
                   }//end if
              }//end try
              catch(Exception e){
                   System.out.println("Could not close the current connection.");//an error message
                   e.printStackTrace();//a Throwable method that prints this throwable and it's backtrace to the standard error stream
              }//end catch
         }//end closeDB
    }//end class QueryTableModel

    here's an uncommented version of the code.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.JOptionPane;
    import java.sql.*;
    public class Demo extends JFrame{
       static String url = "jdbc:odbc:VideoLibrary";
       static Statement stmt;
       static Connection con;
       JTextField hostField;
       JTextField queryField;
       QueryTableModel qtm;
       JComboBox comboBox;
       public static void main(String args[]){
          int choice=-1;
          do{
             choice=getChoice();
             if(choice!=0){
                getSelected(choice);
          }while(choice!=5);
          System.exit(0);
       public static int getChoice(){
          String choice;
          int ch;
          choice = JOptionPane.showInputDialog(null,"1. Maintain product details\n"+"2. Maintain member details\n"+"3. Maintain rental details\n"+"4. View product, member and rental details\n"+"5. Log Off\n\n"+"Enter your choice"); 
          ch = Integer.parseInt(choice);    
          return ch;
       public static void getSelected(int choice){   
          if(choice==1){
             maintainProductDetails();
          if(choice==2){
             maintainMemberDetails();
          if(choice==3){
             maintainRentalDetails();
          if(choice==4){
             Demo test = new Demo();
             test.setVisible(true);
       public static Connection getConnection(){
          try {
             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
          catch(java.lang.ClassNotFoundException e){
             System.err.print("ClassNotFoundException: ");
             System.err.println(e.getMessage());
          try {
             con=DriverManager.getConnection(url,"","");
          catch(SQLException ex) {
             System.err.println("SQLException: " + ex.getMessage());
          return con;
       public static void maintainProductDetails(){
          Connection con = getConnection();
          String  addProduct1, addProduct2, addProduct3, addProduct4, addProduct5, addProduct6, addProduct7, addProduct8, addProduct9, addProduct10;
          addProduct1 = "insert into Product values (110001, 'The Killers - Sams Town', 5.00, 'G', 'CD', 2006)";
          addProduct2 = "insert into Product values (110002, 'Robbie Williams - Rudebox', 5.00, 'G', 'CD', 2006)";
          addProduct3 = "insert into Product values (110003, 'Razorlight - Razorlight', 5.00, 'G', 'CD', 2006)";
          addProduct4 = "insert into Product values (110004, 'My Chemical Romance - The Black Parade', 5.00, 'G', 'CD', 2006)";
          addProduct5 = "insert into Product values (110005, 'Snow Patrol - Eyes Open', 5.00, 'G', 'CD', 2006)";
          addProduct6 = "insert into Product values (110006, 'Scissor Sisters - Ta-Dah!', 5.00, 'G', 'CD', 2006)";
          addProduct7 = "insert into Product values (110007, 'Lovesounds - Justin Timberlake', 5.00, 'G', 'CD', 2006)";
          addProduct8 = "insert into Product values (110008, 'Director - We thrive on big cities', 5.00, 'G', 'CD', 2006)";
          addProduct9 = "insert into Product values (110009, 'Roxette - Roxette hits', 5.00, 'G', 'CD', 2006)";
          addProduct10 = "insert into Product values (110010, '***** Cat Dolls - PCD', 5.00, 'G', 'CD', 2006)";
          try {
             stmt = con.createStatement();
             stmt.executeUpdate(addProduct1);
             stmt.executeUpdate(addProduct2);
             stmt.executeUpdate(addProduct3);
             stmt.executeUpdate(addProduct4);
             stmt.executeUpdate(addProduct5);
             stmt.executeUpdate(addProduct6);
             stmt.executeUpdate(addProduct7);
             stmt.executeUpdate(addProduct8);
             stmt.executeUpdate(addProduct9);
             stmt.executeUpdate(addProduct10);
             stmt.close();
             con.close();
          catch(SQLException ex) {
             System.err.println("SQLException: " + ex.getMessage());
       public static void maintainMemberDetails(){
          Connection con = getConnection();
          String addMember1, addMember2, addMember3, addMember4, addMember5, addMember6, addMember7, addMember8, addMember9, addMember10;
          addMember1 = "insert into Member values (1234, 'Ann', 'Smyth', 'Upper Killult, Falcarragh, Co. Donegal', '(074)-9135210', '(087)-2030172', #5/11/85#, #5/12/06#)";
          addMember2 = "insert into Member values (2345, 'John', 'Murphy', 'Lower Killult, Falcarragh, Co. Donegal', '(074)-9135211', '(087)-2030173', #4/12/85#, #6/13/06#)";
          addMember3 = "insert into Member values (1324, 'James', 'McFadden', 'Lower Ardsbeg, Gortahork, Co. Donegal', '(074)-9165314', '(087)-2030171', #4/11/85#, #6/14/06#)";
          addMember4 = "insert into Member values (1235, 'Frankie', 'Ferry', 'Ardsmore, Gortahork, Co. Donegal', '(074)-9165325', '(087)-2031234', #6/13/60#, #6/15/06#)";
          addMember5 = "insert into Member values (1236, 'Daniel', 'McKimm', 'Ballyness, Falcarragh, Co. Donegal', '(074)-9135212', '(087)-2030184', #5/14/73#, #6/16/06#)";
          addMember6 = "insert into Member values (2346, 'Stephen', 'Doohan', 'Ballyness, Falcarragh, Co. Donegal', '(074)-9135213', '(087)-2030185', #6/13/85#, #5/13/06#)";
          addMember7 = "insert into Member values (2347, 'James', 'Ferry', 'Meenlaragh, Gortahork, Co.Donegal', '(074)-9165360', '(087)-2031345', #9/12/85#, #5/14/06#)";
          addMember8 = "insert into Member values (2348, 'Liam', 'Cannon', 'Derryconner, Gortahork, Co.Donegal', '(074)-9165324', '(087)-2031456', #4/11/86#, #5/15/06#)";
          addMember9 = "insert into Member values (2401, 'Ciaran', 'Ferry', 'Brinalack, Gweedore, Co.Donegal', '(074)-9176425', '(087)-2030282', #9/12/85#, #5/16/06#)";
          addMember10 = "insert into Member values (2402, 'Ciaran', 'McGee', 'Derrybeg, Gweedore, Co.Donegal', '(074)-9176536', '(087)-2030393', #9/14/85#, #5/18/06#)";
          try{
             stmt = con.createStatement();
             stmt.executeUpdate(addMember1);
             stmt.executeUpdate(addMember2);
             stmt.executeUpdate(addMember3);
             stmt.executeUpdate(addMember4);
             stmt.executeUpdate(addMember5);
             stmt.executeUpdate(addMember6);
             stmt.executeUpdate(addMember7);
             stmt.executeUpdate(addMember8);
             stmt.executeUpdate(addMember9);
             stmt.executeUpdate(addMember10);
             stmt.close();
             con.close();
          catch(SQLException ex) {
             System.err.println("SQLException: " + ex.getMessage());
       public static void maintainRentalDetails(){
          Connection con = getConnection();
          String addRental1, addRental2, addRental3, addRental4, addRental5, addRental6, addRental7, addRental8, addRental9, addRental10;
          addRental1 = "insert into Rental values (110001, 'The Killers - Sams Town', 1234, 'Ann', 'Smyth', #9/01/06#, #9/10/06#, 'Yes', 2.00)";
          addRental2 = "insert into Rental values (120001, 'Mission Impossible 3', 2345, 'John', 'Murphy', #9/02/06#, #9/09/06#, 'No', 0.00)";
          addRental3 = "insert into Rental values (130001, 'Need for Special Carbon', 1324, 'James', 'McFadden', #9/03/06#, #9/12/06#, 'Yes', 2.00)";
          addRental4 = "insert into Rental values (110002, 'Robbie Williams - Rudebox', 1235, 'Frankie', 'Ferry', #9/04/06#, #9/11/06#, 'No', 0.00)";
          addRental5 = "insert into Rental values (120015, 'Prime', 1236, 'Daniel', 'McKimm', #9/05/06#, #9/14/06#, 'Yes', 2.00)";
          addRental6 = "insert into Rental values (130015, 'FIFA 07', 2346, 'Stephen', 'Doohan', #9/06/06#, #9/13/06#, 'No', 0.00)";
          addRental7 = "insert into Rental values (110009, 'Roxette - Roxette hits', 2347, 'James', 'Ferry', #9/07/06#, #9/16/06#, 'Yes', 2.00)";
          addRental8 = "insert into Rental values (120003, 'The Break Up', 2348, 'Liam', 'Cannon', #9/08/06#, #9/15/06#, 'No', 0.00)";
          addRental9 = "insert into Rental values (130027, 'Gears of War', 2401, 'Ciaran', 'Ferry', #9/09/06#, #9/18/06#, 'Yes', 2.00)";
          addRental10 = "insert into Rental values (110021, 'Scooter - Mind the Gap', 2402, 'Ciaran', 'McGee', #9/10/06#, #9/17/06#, 'No', 0.00)";
          try{
             stmt = con.createStatement();
             stmt.executeUpdate(addRental1);
             stmt.executeUpdate(addRental2);
             stmt.executeUpdate(addRental3);
             stmt.executeUpdate(addRental4);
             stmt.executeUpdate(addRental5);
             stmt.executeUpdate(addRental6);
             stmt.executeUpdate(addRental7);
             stmt.executeUpdate(addRental8);
             stmt.executeUpdate(addRental9);
             stmt.executeUpdate(addRental10);
             stmt.close();
             con.close();
          catch(SQLException ex) {
             System.err.println("SQLException: " + ex.getMessage());
       public Demo(){
          super("Demo Test Frame");
          setSize(350, 200);
          comboBox = new JComboBox();
          comboBox.addItem("jdbc:odbc:VideoLibrary");
          qtm = new QueryTableModel();
          JTable table = new JTable(qtm);
          JScrollPane scrollpane = new JScrollPane(table);
          JPanel p1 = new JPanel();
          p1.setLayout(new GridLayout(3, 2));
          p1.add(comboBox);
          p1.add(new JLabel("Enter your query: "));
          p1.add(queryField = new JTextField());
          p1.add(new JLabel("Click here to send: "));
          JButton jb = new JButton("Search");
          jb.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e){
                qtm.setHostURL();
                qtm.setQuery(queryField.getText().trim());
          p1.add(jb);
          getContentPane().add(p1, BorderLayout.NORTH);
          getContentPane().add(scrollpane, BorderLayout.CENTER);
    import java.sql.*;
    import java.io.*;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.table.*;
    public class QueryTableModel extends AbstractTableModel{
         Vector cache; 
         int colCount;
         String[] headers;
         Connection db;
         Statement statement;
         String currentURL;
         public QueryTableModel(){
              cache=new Vector();
              try{
             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
              catch(Exception e){
                   System.out.println("problem loading the driver ");
         public String getColumnName(int i){
            return headers;
         public int getColumnCount(){
         return colCount;
         public int getRowCount(){
         return cache.size();
         public Object getValueAt(int row, int col){
              return ((String[])cache.elementAt(row))[col];
         public void setHostURL(){
         String url = "jdbc:odbc:VideoLibrary";
         closeDB();
              try{
    db=DriverManager.getConnection(url,"","");
    statement=db.createStatement();
    catch(Exception e){
    System.out.println("Could not initialize the database.");
    e.printStackTrace();
    public void setQuery(String q){
              cache=new Vector();
    String s="select * from Product";
              try{
                   ResultSet rs=statement.executeQuery(q);
                   ResultSetMetaData meta=rs.getMetaData();
                   colCount=meta.getColumnCount();
                   headers=new String[colCount];
                   for(int h=1;h<=colCount;h++){
                        headers[h-1]=meta.getColumnName(h);
                   while(rs.next()){
                        String[] record=new String[colCount];
                        for(int i=0;i<colCount;i++){
                             record[i]=rs.getString(i+1);
                        cache.addElement(record);
                   fireTableChanged(null);
              catch(Exception e){
                   cache=new Vector();
                   e.printStackTrace();
         public void initDB(String url){
              try{
                   db=DriverManager.getConnection(url);
                   statement=db.createStatement();
              catch(Exception e){
                   System.out.println("Could not initialize the database.");
                   e.printStackTrace();
         public void closeDB(){
              try{
                   if(statement!=null){
                   statement.close();
                   if(db!=null){
                   db.close();
              catch(Exception e){
                   System.out.println("Could not close the current connection.");
                   e.printStackTrace();

  • HT201363 My iPhone, iPad and iPod are all associated with the same Apple ID.  How can I remove the iPod and associate it with a new Apple ID without affecting the data on the other devices (note: there is no data on the iPod I want to keep)?

    My iPhone, iPad and iPod are all associated with the same Apple ID.  How can I remove the iPod and associate it with a new Apple ID without affecting the data on the other devices (note: there is no data on the iPod I want to keep)?

    Very simple.  Turn off Find my iDevice, then  Tap Settings, General, Erase, Erase all content and settings.

  • How can I view an AI file created on a MAC on a PC without corrupting the fonts?

    How can I view an AI file created on a MAC on a PC without corrupting the original fonts?  An AI file was created with an image and text on a MAC.  When the AI file was opened on a PC, the text fonts were not the same as originally created.  Also, the same AI file was saved to PDF on the MAC.  When the AI file was opened on a PC, there wasn't anything visible.  Anyone have any ideas?

    Are you using the save version of Illustrator on both Mac and PC? If so, and you have the same fonts installed on both machines you should be able to open it without any problems. You may need to tell it which fonts to assign, they are not always named the same. If you don't need to edit the text, you could convert the text to outline and eliminate the need for fonts.

  • I reinstalled my OS and now it wants to empty my phone.  How can I get it to back up my phone without removing the data?

    I reinstalled my OS and now it wants to empty my phone.  How can I get it to back up my phone without removing the data?

    You can't. But if you backed up your computer prior to wiping it out, you should be able to restore your iTunes library, contacts, photos, etc. from that backup. Once you do, you can set the phone up again and just sync everything from your library back to it.
    If you didn't back the computer up either, you can transfer items purchased on the phone into iTunes, and if you set up at least one contact in whatever application you sync your contacts to on the computer, it will offer to merge the address books on the first sync, saving those.  Any media you'd acquired from sources other than the iTunes store will have to be re-downloaded from the source or re-ripped.
    The iPhone is NOT a backup device.

  • How to export the text edit data to excel file without splitting the data in excel file?

    how to export the text edit data to excel file without splitting the data in excel file?
    I have a requirement in SAP HR where in the appraiser can add comments in the area given and can export that to excel file. Currently the file is getting exported but the comments getting split into deifferent rows.
    I want the entire comment to be fit in one row.
    Please help.
    Thank you

    Hi,
    if your text edit value is stored in 'lv_string' variable.
    then before exporting the value to excel you have to remove CL_ABAP_CHAR_UTILITIES=>NEWLINE
    that is '#' from the variable lv_string.
    for that use code some thing like this.
    REPLACE ALL OCCURRENCES OF CL_ABAP_CHAR_UTILITIES=>NEWLINE in lv_string WITH space.
    I think this will do the trick.

  • HT1212 device disabled after entering wrong passcode. Please help me in getting this unlocked  without lossing the data as the data is really important for me

    device disabled after entering wrong passcode.
    Please help me in getting this unlocked  without lossing the data as the data is really important for me

    I think you should call via phone or perhaps take it to a phone store. I suggest taking your id, box packaging and other necessities such as the reciept of the phone being purchased.
    Hope this helped

  • Time capsule partition without deleting the data?

    I have a Time Capsule already with data and would like to set a limited space for backups. Is it possible to partition a Time Capsule (or create an image) without deleting the data it already has? Can anyone provide a step-by-step or tutorial?
    Thanks a lot in advance.

    The following instructions will work for Lion and Mountain Lion Macs, but I have not tested on Mavericks....which seems to be just that....a Maverick.
    Changing the maximum size or case-sensitivity of a sparse bundle

  • How do I retrieve the my iCloud data off of my old, unusable iPhone without sacrificing the data off of my current iPhone?

    Firstly, I have 2 iCloud accounts, which creates constant confusion (considering I have a third "apple" acct. as well).  I have not found any solutions (even the genius bar has been unhelpful) for this, but my current major issue is with storage space:
    I have 2 iPads (first gen and a mini), and HAD 2 iPhones (4s and currently an iPhone5), plus one laptop:
    ACCESS the old iPhone data (the phone drowned last month) on iCloud, such as the photos, notes, etc.  This way I get my data (isn't that the point - backup??), and I also free up space to back up my current phone and ipad.
    I'm currently way over my max data limit (which is the maximum purchase, btw).
    Any suggestions would be greatly appreciated at this point . . !
    Cheers,
    DAH

    If I understand your question correctly, you want to recover data from an iCloud backup of another device without losing the data that is on your current device.  You could do this by backing up your current device as it is now, either to iCloud or to your computer using iTunes if you don't have space in your iCloud account to back up.  Then restore your device to the backup of your other device to recover the data.  Then save the recovered data to your computer (by, for example, importing the photos as explained here: http://support.apple.com/kb/HT4083, and emailing any recovered notes to yourself, etc.).  Then, when you're done saving the recovered data, restore your device back to the backup you made at the beginning, returning it to the state it was in when you started.
    Another option would be to sign into the iCloud account your other device was using on icloud.com and back up some of the data to your computer as explained here: http://support.apple.com/kb/HT4910.  This would not, however, allow you to access your camera roll photos and other data that is not synced with iCloud.

  • Partition Ext HDD without losing the data already on the disc

    I have an early G5 iMac 80gb HDD, Macbook and a Macmini
    I have finally managed to get them all running the same version of ilife(08) and thought it was time to get them all running from the same hymn sheet...
    I have been using a 500gb Ext HDD (iphoto,itunes etc) so i have filled around 300GB so far, the problem is I want to move my iMovie events/projects to the ext HDD to. I have followed the steps to move the files but I get a dialogue box telling me my drive isn't compatible with imovie. (iMovie 08)
    When I check the Ext HDD format (using <apple>+i it tells me the format is appleshare...
    So after that intro..... can I partition this drive and set aside say 100GB (178GB free) without losing the data on the drive??
    Thank you for reading
    Chris

    Appleshare? That is not a format.
    It must be formatted as Mac OS Extended (Journaled) if not already. Reformatting will delete everything on the disk.
    How to partition a Hard Drive:
    http://www.kenstone.net/fcphomepage/partitioningtiger.html

  • Shared variable data type: Can I choose an array of a custom typedef, without making the array itself a typedef?

    Hi all,
    I'd like to pass an array of a cluster across my network. My cluster is typedef'ed, but I'd like to avoid polluting my project with another redundant typedef.
    Is it possible to use the shared variable's "From Custom Control..." option with an array, without saving the array as a new .ctl file?
    Solved!
    Go to Solution.

    Ah, I didn't realize you were using shared variables. I thought you were just considering it as another option along with TCP/IP or UDP or something like that. In this case, you would have to create a second custom control. This control would be an array with teh typedef cluster in it. No need to make this new control itself a typedef though. Sorry, I know you were hoping for a different answer. I doubt one file will really "clutter" your project though
    CLA, LabVIEW Versions 2010-2013

  • How can i access a mysql table without putting the data in a datagrid

    I developed my air app with a datagrid which uses a php service to display all data from a table of strings in MySql.
    I now do not need the datagrid, how can i get the data from my database without putting it into a dataGrid? Do i need an array? how do i do this? anyone got any example code?

    Balakrishnan V wrote:
    var resultArrayCollection:ArrayCollection=new ArrayCollection()
    protected function resultHandler(event:ResultEvent)
         result=event.result as ArrayCollection
    You can use the result array collection now inside your program for any further changes / manipulations.
    Hope this helps; If you have further doubts, do ask...
    Balakrishnan V
    Hi, yeah this helps,
    however, how would i generate a result handler for a service that has not been called yet? Sorry my knowledge of services is very limited.
    This is a php service, get_all service that returns all the rows from a mysql table.
    I can see the service box with the service i want to use:
    but how do i pass that to a result handler?

  • Can I create a mirrored RAID1 from an existing striped RAID0 without erasing the data?

    I have a 1.5 TB striped RAID0 with 3 500 GB drives. I have a clone of the data from the 1.5TB RAID on a non-RAID 1TB drive and a 500GB drive. I'd like to create a RAID1 mirrored set out of all of these disks. I can partition the 1TB into 2 500GB drives and combine that with the other 500 GB. I'd rather not erase the data to create the mirror. Is there a way to rebuild a mirrored set from the existing 1.5 TB striped set, or do I need to start all over? I have a third copy of the data that I could put on the new mirrored RAID if necessary.
    The data is aperture, itunes and imovie libraries. To back up a minute, is having a RAID1 a good option or is there a better solution that I am not considering?
    PS I'm using a 2.53 GHz macbook pro unibody with 8GB of RAM.

    First off a mirrored RAID requires two drives of equal size (could be two striped RAIDs of equal size.) So, as I understand what you have to work with you can create a single 500 GB mirrored RAID using two of the 500 GB drives.
    You could create a striped RAID array using two of the 500 GB drives, then combine it with the 1 TB drive you have to create a 1 TB mirrored RAID. But this would not be the best alternative because if one of the smaller drives in the striped array fails then you lose everything on those drives. Not so bad as long as the single 1 TB drive is OK.
    Also, you might find this information helpful:
    RAID Basics
    For basic definitions and discussion of what a RAID is and the different types of RAIDs see RAIDs.  Additional discussions plus advantages and disadvantages of RAIDs and different RAID arrays see:
    RAID Tutorial;
    RAID Array and Server:
    Hardware and Service Comparison.
    Hardware or Software RAID?
    RAID Hardware Vs RAID Software - What is your best option?
    RAID is a method of combining multiple disk drives into a single entity in order to improve the overall performance and reliability of your system. The different options for combining the disks are referred to as RAID levels. There are several different levels of RAID available depending on the needs of your system. One of the options available to you is whether you should use a Hardware RAID solution or a Software RAID solution.
    RAID Hardware is always a disk controller to which you can cable up the disk drives. RAID Software is a set of kernel modules coupled together with management utilities that implement RAID in Software and require no additional hardware.
    Pros and cons
    Software RAID is more flexible than Hardware RAID. Software RAID is also considerably less expensive. On the other hand, a Software RAID system requires more CPU cycles and power to run well than a comparable Hardware RAID System. Also, because Software RAID operates on a partition by partition basis where a number of individual disk partitions are grouped together as opposed to Hardware RAID systems which generally group together entire disk drives, Software RAID tends be slightly more complicated to run. This is because it has more available configurations and options. An added benefit to the slightly more expensive Hardware RAID solution is that many Hardware RAID systems incorporate features that are specialized for optimizing the performance of your system.
    For more detailed information on the differences between Software RAID and Hardware RAID you may want to read: Hardware RAID vs. Software RAID: Which Implementation is Best for my Application?
    Do You Really Need a RAID?
    There is only one thing a RAID  provides - more space.  Beyond that a RAID can’t help you with:
    Accidental deletion or user error
    Viruses or malware
    Theft or catastrophic damage
    Data corruption due to other failed hardware or power loss
    Striped RAIDs have a higher failure risk than a single drive
    The purpose of a RAID is to provide high speed mass storage for specialized needs like video editing, working with extremely large files, and storing huge amounts of data.
    If your array fails it means complete loss of data and hours of time to rebuild.  RAIDs degrade over time necessitating many hours of restoration.  And, if you don't know much about RAIDs then you really don't need one.
    You can use a RAID for backup.  But unless your backup needs involve TBs of data requiring rapid and frequent access, why bother?  TM works in the background.  It's not like you have to sit there waiting for your backup to be completed.  Furthermore, you're buying two drives possibly to solve a problem where a single drive will do.  And, one drive is less expensive than two.
    Ignoring overhead, two drives in a RAID 0 (striped) array should perform about twice as fast. However, as the array fills up with files that performance will degrade.
    RAID was a technology that in it's time was meant to solve a problem.  Large capacity, fast drives were extremely expensive.  Small drives were cheaper but slower.  However, combining these cheaper drives into arrays gave faster performance and the larger capacity needed for data storage needs.  Thus, the reason why it's called Redundant Array of Inexpensive Drives.  But today you can buy a 3 TB drive with performance that's better than the 1 TB drives of two or three years ago.

  • HT201269 I have bought a new IPad Air to replace the first version of IPad. I want to transfer my information from the old to the new one without losing the data and history from APPs like Candy Crush. What do I do?

    Just purchased an IPad Air to replace a first geneation IPad purchased several years ago. How do I transfer data from the old to the new without losing the history and data from Apps like Candy Crush? Thanks

    How to Transfer Everything from an Old iPad to New iPad
    http://osxdaily.com/2012/03/16/transfer-old-ipad-to-new-ipad/
    iOS: Transferring information from your current iPhone, iPad, or iPod touch to a new device
    http://support.apple.com/kb/HT2109
    Moving Content to a New iPad
    http://tinyurl.com/qzk2a26
    Transferring your prepaid cellular data account depends on your carrier. AT&T lets you move it yourself when you go to Cellular Data in Settings and log into your account with your previous AT&T user name and password. For iPads with Sprint service, you can set up an account on the new iPad and contact Sprint Customer Care (888-211-4727 and go through the menus) to deactivate the old plan and get credit for unused service. For Verizon, call the company’s customer service number for mobile broadband support (800-786-8419) and ask to have your account transferred.
     Cheers, Tom

Maybe you are looking for