Real's HowTo PDF version.

This is the PDF version of the Real's HowTo Web site ( http://www.rgagnon.com/howto.html ). For up−to−date content, please refer to the Web site. There are 4 files : Real's Java , Real's Javascript, Real's Powerbuilder and Real's VBS and Misc Prog HowTo. Please don't make PDF versions available on the internet (it's ok in intranet) From the PDF, you can't run the examples and the links to other How−to's are not working. If you feel that effort has been useful to you, perhaps you will consider giving something back? You can make a donation through PayPal at https://www.paypal.com , make you donation to real@rgagnon.com Contributions via PayPal are accepted in any amount using a credit card or checking account. (Donations of any size gladly accepted) Real's Howto copyright notice ( real@rgagnon.com ) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions is met: * the source code is used in a development project Redistributions of source code or site content (even partially) in any publications (electronic or paper) is forbidden without permission. DISCLAIMER THIS SOFTWARE IS PROVIDED BY Real Gagnon "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Real Gagnon BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Real's HowTo@www.rgagnon.com
1 Applet..............................................................................................................................................1 . 1.1 java−applet........................................................................................................................1 1.2 Goto to a new URL from an Applet....................................................................................1 1.3 Determine the host from where the Applet is loaded.........................................................3 1.4 Have a scrolling status line................................................................................................3 1.5 Use a search engine..........................................................................................................5 1.6 Have an on−screen clock..................................................................................................6 1.7 Have Applets on the same page communicate with each other........................................8 1.8 Have Applets on different frames communicates with each other.....................................9 1.9 Send a message from an Applet to another Applet on a different page..........................10 1.10 Have an applet launch an other applet..........................................................................12 1.11 Get the user name.........................................................................................................14 1.12 Access parameters passed in the URL ..........................................................................14 1.13 Convert an Applet to Application ....................................................................................16 1.14 Change the mouse cursor in Applet..............................................................................17 . 1.15 Use an Image as the Applet background.......................................................................17 1.16 Handle the new Control Activation mechanism in IE.....................................................18 1.16.1 Solution #1............................................................................................................19 1.16.2 Solution #2............................................................................................................19 1.16.3 Solution #3............................................................................................................20 1.17 Pass parameters to the Applet JVM (WIN)....................................................................21 1.18 See the Java Console Window Log (Java plugin).........................................................22 1.19 Display debugging infos for an Applet...........................................................................23 1.20 Have an invisible Applet................................................................................................23 . 2 Date and Time...............................................................................................................................24 2.1 java−date.........................................................................................................................24 2.2 Have year on 4 digits from a Date object.........................................................................24 2.3 Get the current Date and Time........................................................................................24 2.4 Compute days between 2 dates......................................................................................25 2.5 Get the number of days in a month ..................................................................................26 2.6 Validate a date.................................................................................................................27 2.6.1 Using DateFormat...................................................................................................27 2.6.2 Using GregorianCalendar.......................................................................................28 2.7 Determine to day of the week..........................................................................................29 2.8 Add/Substract Day/Month/Year to a Date........................................................................29 2.9 Get the correct TimeZone on DateFormat.......................................................................30 2.10 Simply format a date as "YYYYMMDD".........................................................................30 2.11 Compare 2 dates...........................................................................................................31 2.12 Parse a String to obtain a Date/GregorianCalendar object ...........................................31 . 2.13 Use System time to generate unique ID........................................................................32 2.14 Get the day name..........................................................................................................33 2.15 Find the current date format..........................................................................................33 . 2.16 Get a julian date.............................................................................................................34 2.17 Calculate the age...........................................................................................................36 2.18 Format a duration in ms into a string as "Days,Hours,minutes and seconds"...............37 2.19 Get the atomic time........................................................................................................38 2.20 Get a date interval.........................................................................................................40 . 2.21 Determine if an hour is between an interval..................................................................42 . 2.22 Set the computer clock..................................................................................................43

2.23 Use System time to generate unique ID

Real's HowTo@www.rgagnon.com
2 Date and Time 2.23 Use System time to generate unique ID........................................................................43 3 AWT ................................................................................................................................................45 3.1 java−awt ..........................................................................................................................45 . 3.2 Use The CardLayout manager........................................................................................45 . 3.3 Detect which card is visible with a CardLayout................................................................47 3.4 Use Popups.....................................................................................................................47 3.5 Use a File Dialog ..............................................................................................................49 3.6 Use TrueType font...........................................................................................................50 3.7 Display available fonts.....................................................................................................51 3.8 Font with 3D effect...........................................................................................................52 3.9 Use the System Clipboard...............................................................................................52 3.10 Maximize a Frame.........................................................................................................53 3.11 Center a Frame/Dialog ...................................................................................................54 3.12 Close a Frame...............................................................................................................55 3.13 Call events on a Frame from a Panel............................................................................56 3.14 Set the small top−left icon on a Frame..........................................................................58 3.15 Prevent a Frame to be resized .......................................................................................59 3.16 Embed an image into a Frame .......................................................................................60 3.17 Display a message box..................................................................................................62 3.18 Display a Splash screen................................................................................................63 3.19 Vibrate a Window...........................................................................................................65 3.20 Limit TextField input to numeric value...........................................................................67 3.21 Limit TextField input to a maximum length....................................................................69 3.22 React to the ENTER key in a Textfield..........................................................................70 3.23 Make the ENTER key act like the TAB key ....................................................................70 3.24 Reset all textfields in one shot.......................................................................................71 3.25 Limit a TextField to Uppercase......................................................................................72 3.26 Have an ImageButton....................................................................................................73 3.27 Reset a checkbox group................................................................................................76 3.28 Set the listbox width.......................................................................................................76 3.29 Align the column in a List...............................................................................................77 3.30 Have a srolling text display............................................................................................77 3.31 Label dynamic resizing..................................................................................................78 3.32 Make a TextArea "word−wrap"......................................................................................80 3.33 Synchronize a TextArea vs a Choice.............................................................................80 3.34 Display underlined text..................................................................................................80 . 3.35 Display vertical text........................................................................................................81 3.36 Have Label with many lines...........................................................................................82 3.37 Have a Label with underlined text..................................................................................86 3.38 Have a Label acting as HTML HREF (URLLabel).........................................................87 3.39 Display a GIF in a Canvas.............................................................................................88 3.40 Embed an image into a Frame .......................................................................................89 3.41 Load several images from a single GIF.........................................................................91 3.42 Load an Image from a JAR file......................................................................................92 3.43 Load an Icon from a jar (again)......................................................................................93 3.44 Scale an Image..............................................................................................................94 3.45 Fade an image...............................................................................................................95 3.46 Rotate an image .............................................................................................................97

Real's HowTo@www.rgagnon.com
3 AWT 3.47 Create a scrollable canvas .............................................................................................99 3.48 Use an Image as the Applet background.....................................................................103 3.49 Have a simple Image browser.....................................................................................104 3.50 Simulate a "mouse over" event to toggle an image.....................................................107 3.51 Hide the mouse cursor.................................................................................................108 3.52 Make a color transparent.............................................................................................109 3.53 Save an Image as a GIF or JPEG file..........................................................................110 3.54 Use the same background color as the browser .........................................................111 . 3.55 Do simple animation using Images..............................................................................112 3.56 Do simple animation to show "work in progress".........................................................113 3.57 Get the color of a specific pixel....................................................................................114 3.58 Do "rubber−band" drawing ...........................................................................................115 3.59 Convert RGB value to Hexadecimal (to be used in HTML for example) .....................117 . 3.60 Draw a line or set a pixel in my own image ..................................................................117 3.61 Draw a dashed line......................................................................................................118 3.62 Draw a line with a thickness .........................................................................................119 3.63 Draw a pie chart...........................................................................................................121 3.64 Draw faster rectangles.................................................................................................123 3.65 Get a screen capture and save it as a JPEG...............................................................124 3.66 Display a TIF................................................................................................................124 3.67 Convert a multi−page TIF into single−page TIF ...........................................................126 3.68 Convert an Image to a BufferedImage.........................................................................127 3.69 Detect a double click vs simple click............................................................................128 3.70 Detect the mouse button used when clicking ...............................................................129 3.71 Exit an application from a menu ...................................................................................130 3.72 Trigger a click on a Button...........................................................................................131 4 Environment ................................................................................................................................133 4.1 java−env........................................................................................................................133 4.2 Read environment variables from an application...........................................................133 4.3 Retrieve environment variables (JDK1.5)......................................................................137 4.4 Retrieve environment variable (JNI)..............................................................................137 4.5 Use a MAKE file.............................................................................................................138 4.6 Detect the browser/JVM type.........................................................................................139 4.7 Fix the "Wrong magic number" error message..............................................................141 4.8 Use a precompiler "à la C" with Java.............................................................................141 4.9 Open source packages..................................................................................................141 4.10 Ant...............................................................................................................................141 . 4.11 Simple boolean flag.....................................................................................................142 4.12 Determine what are the classes actually used in a Java Applet or application ............143 4.13 Set the memory available to the JVM..........................................................................143 4.14 Generate the Javadoc "en français"............................................................................143 4.15 Use JDK1.5 new features............................................................................................145 4.16 Check the class version...............................................................................................145 4.17 Get the system properties or the JVM uptime ..............................................................147 4.18 Detect if running in a 64bit JVM...................................................................................147 4.19 Set the default JVM type..............................................................................................148 4.20 Capture the output of JAVAC .......................................................................................149 4.21 Freeze the JVIEW window in MS VJ++.......................................................................150

4.22 Wrap a Java beans in a COM object

Real's HowTo@www.rgagnon.com
4 Environment 4.22 Wrap a Java beans in a COM object...........................................................................150 4.23 Know details about the JAVA at run−time...................................................................151 4.24 Detect the Microsoft JVM version installed..................................................................153 4.25 Run JAVA as a Windows service .................................................................................153 4.26 Execute a class from Windows Explorer .....................................................................153 . 4.27 Create an icon to launch java apps for Windows?.......................................................155 4.28 Fix the "out of environment" error when setting a new CLASSPATH..........................155 4.29 Query Windows registry...............................................................................................156 4.30 Quickly retrieve available Java JVM on a workstation (Windows)...............................158 4.31 Get the Windows "My Documents" path......................................................................159 4.32 Get a return code from a VBS ......................................................................................160 4.33 List currently running processes (Windows)................................................................161 4.33.1 Using TASKLIST.EXE .........................................................................................161 4.33.2 Using a VBS ........................................................................................................162 4.34 Check if a program or process is running (Windows)..................................................163 4.35 Windows registry vs. Java JDK/JRE installation..........................................................164 4.36 Create a Taglet to document database access (Javadoc) ..........................................165 . 4.36.1 newMethod .........................................................................................................165 4.37 Generate the Javadoc "en français"............................................................................169 4.38 Document a package using Javadoc...........................................................................170 4.39 Display a comment in a Javadoc.................................................................................171 4.40 Display XML in a javadoc .............................................................................................172 4.41 Add a copyright notice to a Javadoc............................................................................172 4.42 Use a Log file...............................................................................................................173 4.43 Trace the execution.....................................................................................................175 4.44 Time the execution .......................................................................................................177 4.45 Log information efficiently (with Log4J).......................................................................178 . 4.46 Change the logging level on−the−fly (Log4J)..............................................................179 4.47 Use a JAR/ZIP/CAB file with an Applet.......................................................................180 . 4.48 Make ZIP/JAR file always accessible from applet.......................................................182 4.49 Make a JAR executable...............................................................................................182 4.50 Accessing jars from within a jar...................................................................................184 4.51 Access a JAR outside the CLASSPATH ......................................................................184 4.52 Extract a file from a Jar................................................................................................185 4.53 Determine if running from JAR .....................................................................................186 4.54 Get list of classes in package (in a Jar).......................................................................187 4.55 Add version to Jar packaging .......................................................................................188 4.56 Use ANT to Build a JAR with version/build number.....................................................190 4.57 Include all jars in the classpath definition .....................................................................193 4.58 Windows batch file.......................................................................................................194 4.59 JDK6............................................................................................................................194 4.60 JAR (and ANT)............................................................................................................195 . 4.61 Detect the browser/JVM type.......................................................................................196 4.62 Detect if Java is enabled from HTML...........................................................................198 4.63 See the Java Console Window Log (Java plugin).......................................................198 5 Internationalization .....................................................................................................................200 5.1 java−inter.......................................................................................................................200 5.2 Load resources based upon client environment at startup............................................200

Real's HowTo@www.rgagnon.com
5 Internationalization 5.3 Load resources dynamically..........................................................................................203 5.4 Load resources via a resources file...............................................................................206 5.5 Display "special character" using Unicode .....................................................................210 5.6 Display chinese/japanese characters............................................................................211 5.7 Localize a JOptionPane dialog......................................................................................211 5.8 Validate/Convert a number using the current Locale()..................................................213 5.9 Localize a JFileChooser................................................................................................214 . 5.10 Disable localization......................................................................................................216 5.11 Generate the Javadoc "en français"............................................................................217 5.12 Sort a String array........................................................................................................218 5.13 Accentuated characters in Properties/ResourceBundle file.........................................220 5.14 Compare accentuated letters.......................................................................................220 5.15 Unaccent letters...........................................................................................................221 5.16 Output french characters to the console......................................................................224 5.17 Get the default character set of the JVM.....................................................................225 5.18 Convert OEM (DOS) file to Ansi (Windows)................................................................225 5.19 Detect non−ASCII character in a String.......................................................................226 6 IO..................................................................................................................................................228 6.1 java−io...........................................................................................................................228 6.2 Redirect output(stdout/stderr) to a frame.......................................................................228 6.3 Redirect printStackTrace() to a String ............................................................................229 6.4 Output french characters to the console........................................................................230 6.5 Clear the console and control attributes........................................................................231 6.6 Print text to a printer easily............................................................................................232 6.7 Print without a Dialog.....................................................................................................232 6.8 Simple input from the keyboard.....................................................................................233 6.9 Initialize and write to a serial port..................................................................................234 . 6.10 Redirect to a NULL device...........................................................................................235 6.11 Get the volume label....................................................................................................235 6.12 Easy keyboard input (JDK1.5).....................................................................................236 6.13 Open or close a CD/DVD drive....................................................................................236 6.14 Get faster console output (System.out.println() replacement).....................................238 6.15 Execute an external program.......................................................................................239 6.16 Using Runtime.exec()..................................................................................................239 6.17 Launch a Windows CMD (or BAT) file and retrieve the errorlevel or exitcode .............240 6.18 Launch a Unix script....................................................................................................241 6.19 Using the ProcessBuilder............................................................................................241 . 6.20 Windows rundll32 utility...............................................................................................242 6.21 PDF (Windows only)....................................................................................................242 6.22 PDF (Mac only)............................................................................................................242 6.23 Path to executable with spaces in them .......................................................................243 6.24 VBSCRIPT...................................................................................................................243 6.25 HTML Help (Windows only).........................................................................................243 6.26 Start Excel...................................................................................................................243 . 6.27 Start a Windows application under another account...................................................244 . 6.28 Windows : execute something in Program Files..........................................................245 6.29 Launch the application associated with a file extension..............................................245 6.30 Launch an application from another application..........................................................246

6.31 Start the default browser from an application

Real's HowTo@www.rgagnon.com
6 IO 6.31 Start the default browser from an application..............................................................248 6.32 Execute a Windows Shortcut (.lnk)..............................................................................250 6.33 Create a file association with a Java program.............................................................250 6.34 Capture the output from a VBS....................................................................................252 6.35 Get a return code from a VBS ......................................................................................253 6.36 Execute a CMD file stored in a JAR .............................................................................254 6.37 Read the content of a file.............................................................................................255 6.38 Read a text file from a jar.............................................................................................257 6.39 Extract a file from a Jar................................................................................................260 6.40 Read a data file with floats...........................................................................................261 6.41 Write to the end of a file...............................................................................................262 6.42 Write "real" ascii file.....................................................................................................263 6.43 Copy a file....................................................................................................................264 6.44 Use a "log file" ..............................................................................................................266 6.45 Delete files with a certain extension .............................................................................267 6.46 Insert a line in a file......................................................................................................268 6.47 Read a file into a variable in one shot..........................................................................269 6.48 Serialize an object to a file...........................................................................................269 6.49 Redirect stdout to a file................................................................................................271 6.50 Get the "last modified" date from a file .........................................................................271 6.51 Check if a file exists.....................................................................................................271 6.52 Detect file modification.................................................................................................272 6.53 File/directory polling to detect change.........................................................................274 6.54 jpoller (directory poller)................................................................................................274 6.55 JNotify..........................................................................................................................274 6.56 Java Native Access (JNA)...........................................................................................275 6.57 Call native methods in a DLL from Java (NativeCall)..................................................275 6.58 Java 7..........................................................................................................................275 6.59 The simple (and naive!) approach...............................................................................275 6.60 Get the current directory..............................................................................................275 6.61 Get the "root" of an application....................................................................................276 6.62 Get the content of a directory with a Filter...................................................................276 6.63 Get the content of a directory with subdirectories........................................................278 6.64 Make a directory..........................................................................................................279 6.65 Create a fixed−length file.............................................................................................280 6.66 Delete a non−empty directory......................................................................................280 6.67 Create a temporary file................................................................................................281 6.68 Get the default character set of the JVM.....................................................................282 6.69 Parse a pathname ........................................................................................................282 6.70 Handle Excel files........................................................................................................283 6.71 JDBC−ODBC Excel driver...........................................................................................283 6.72 JExcel..........................................................................................................................283 6.73 POI...............................................................................................................................284 6.74 JXLS............................................................................................................................285 6.75 xlSQL...........................................................................................................................285 6.76 JCOM...........................................................................................................................286 6.77 OpenXLS Java Spreadsheet SDK...............................................................................287 6.78 Handle CSV file ............................................................................................................289 6.79 com.Ostermiller.util CSV Utils......................................................................................289

Real's HowTo@www.rgagnon.com
6 IO 6.80 opencsv ........................................................................................................................289 6.81 ServingXML.................................................................................................................289 6.82 Super CSV...................................................................................................................289 6.83 csvreader.....................................................................................................................289 6.84 CSVFile........................................................................................................................289 6.85 FlatPack.......................................................................................................................289 6.86 Create an Excel file......................................................................................................290 6.87 Create or process a PDF file ........................................................................................290 6.88 Create a PDF...............................................................................................................292 6.89 iText.............................................................................................................................292 6.90 Convert OEM (DOS) file to Ansi (Windows)................................................................293 6.91 Close a stream in a try/catch block..............................................................................294 6.92 Rename a file extension..............................................................................................295 6.93 Remove HTML tags from a file to extract only the TEXT .............................................295 6.94 Using regular expression.............................................................................................296 6.95 Using javax.swing.text.html.HTMLEditorKit.................................................................296 6.96 Get the Mime Type from a File....................................................................................297 6.96.1 Using javax.activation.MimetypesFileTypeMap..................................................297 6.96.2 Using java.net.URL.............................................................................................298 6.96.3 Using JMimeMagic ..............................................................................................298 6.96.4 Using mime−util..................................................................................................298 6.96.5 Using Droid.........................................................................................................299 6.96.6 Aperture framework .............................................................................................299 6.97 Sort a directory listing..................................................................................................299 6.98 Filter a directory listing by date....................................................................................300 6.99 Display a comment in a Javadoc.................................................................................301 6.100 Create a compressed (ZIP) file..................................................................................302 6.101 Display compressed (ZIP) file content.......................................................................303 6.102 Expand the compressed (ZIP) file ..............................................................................304 6.103 Emit a beep................................................................................................................305 6.104 Emit a Tone ................................................................................................................305 6.105 Play an audio file from an application........................................................................306 7 JDBC............................................................................................................................................308 7.1 java−jdbc ........................................................................................................................308 7.2 Connect to a database via JDBC−ODBC......................................................................308 7.3 SELECT data from a table.............................................................................................309 7.4 INSERT data into a table...............................................................................................310 7.5 MODIFY data in a table.................................................................................................311 7.6 DELETE data in a table.................................................................................................312 7.7 Test for an empty ResultSet..........................................................................................312 7.8 Store and retrieve an object from a table.......................................................................313 7.9 Retrieve an Image ..........................................................................................................315 7.10 Insert an Image............................................................................................................315 7.11 Connect to an Oracle database with JDBC.................................................................315 7.12 Connect to Oracle using a connection pool.................................................................316 7.13 Get JDBC driver for major database vendors..............................................................319 7.14 Handle dates................................................................................................................319 7.15 Call a stored procedure ................................................................................................320

7.16 Stored procedure with Input/Output parms and a ResultSet

Real's HowTo@www.rgagnon.com
7 JDBC 7.16 Stored procedure with Input/Output parms and a ResultSet.......................................321 7.17 Fix incomplete field returned by the ResultSet............................................................322 7.18 Get a record count with a SQL Statement...................................................................322 7.19 Transfer a ResultSet to a JTable.................................................................................323 7.20 List tables in a database..............................................................................................323 7.21 Display ResultSet data in an HTML Table in Servlet...................................................324 7.22 Detect SQL errors or warnings....................................................................................325 7.23 Using DSN−less connection........................................................................................326 7.24 Read data from Excel worksheet.................................................................................327 7.25 Handle Excel files........................................................................................................329 7.26 JDBC−ODBC Excel driver...........................................................................................329 7.27 JExcel..........................................................................................................................329 7.28 POI...............................................................................................................................330 7.29 JXLS............................................................................................................................330 7.30 xlSQL...........................................................................................................................331 7.31 JCOM...........................................................................................................................331 7.32 OpenXLS Java Spreadsheet SDK...............................................................................333 7.33 Specify a CharSet when connecting to a DBMS ..........................................................334 7.34 Get current date using JDBC.......................................................................................335 7.35 Enable JDBC logging...................................................................................................335 7.36 Detect if a table exists..................................................................................................337 7.37 Convert a ResultSet to XML........................................................................................337 7.38 Escape special character in a LIKE clause..................................................................339 7.39 Insert the current date..................................................................................................340 7.40 Log the SQL Statements ..............................................................................................340 7.41 Plain JDBC Logging.....................................................................................................340 7.42 P6Spy..........................................................................................................................340 7.43 Proxool.........................................................................................................................341 8 JNI................................................................................................................................................342 8.1 java−jni ..........................................................................................................................342 . 8.2 Use native code through JNI.........................................................................................342 . 8.3 Pass a string to/from Java to/from C ..............................................................................342 8.4 Set the computer clock..................................................................................................344 8.5 Determine the signature of a method .............................................................................344 8.6 Use arrays ......................................................................................................................346 8.7 Load a DLL....................................................................................................................347 8.8 Use the MouseWheel....................................................................................................347 . 8.9 Throw an Exception (from JNI code).............................................................................347 8.10 Throw my own Exception (from JNI code)...................................................................348 8.11 JNI from a package......................................................................................................349 8.12 Make a Window "stay on top"......................................................................................349 8.13 Start a JVM from C......................................................................................................350 8.14 Retrieve environment variable (JNI)............................................................................351 8.15 Get the PID..................................................................................................................351 8.16 Clear the console, set color and cursor position (JNI).................................................352 8.17 Call Windows API (Open source solution)...................................................................355

Real's HowTo@www.rgagnon.com
9 Javascript interaction .................................................................................................................356 9.1 java−js ............................................................................................................................356 9.2 * Read me * ....................................................................................................................356 9.3 Wake−up a Java applet.................................................................................................356 9.4 Call a Java method from Javascript...............................................................................358 9.5 Calling Java applets methods using DOM and JavaScript............................................360 9.6 Access Java variables from Javascript..........................................................................360 9.7 Call Javascript from a Java applet.................................................................................361 9.8 Create dynamic HTML from a Java applet....................................................................364 9.9 Have Applets on different frames communicates with each other.................................365 9.10 Send a message from an Applet to another Applet on a different page......................366 9.11 Retrieve values from a Java applet for HTML form (CGI) ...........................................368 . 9.12 Detect if an Applet is ready..........................................................................................369 9.13 Read/Write HTML field values from JAVA...................................................................370 9.14 Detect if Java is enabled..............................................................................................372 9.15 Detect if Java 1.1 (with event delegation) is available.................................................372 9.16 Access Cookies from a Java Applet............................................................................372 9.17 Set Applet PARAM VALUE from javascript.................................................................375 9.18 Pass an Array between Java and Javascript...............................................................376 9.19 Interaction without LiveConnect...................................................................................378 9.20 Directory listing on the Web server in a Java Applet...................................................382 9.21 Have a Java button close the browser window............................................................384 9.22 Detect if cookies are enabled .......................................................................................385 9.23 Display a page after all applets are loaded..................................................................386 10 Servlet/JSP................................................................................................................................387 10.1 java−jsp ........................................................................................................................387 10.2 Read me......................................................................................................................387 10.3 Get parameters passed to a servlet.............................................................................387 10.4 Detect no argument condition in a Servlet...................................................................388 10.5 Set a Cookie from a servlet.........................................................................................389 . 10.6 Read a Cookie from a servlet......................................................................................389 10.7 Delete (or expire) a Cookie from a servlet...................................................................390 10.8 Ask for a password from a Servlet...............................................................................390 10.9 Talk to a CGI/Servlet...................................................................................................390 . 10.10 Test for Cookies.........................................................................................................391 10.11 Display ResultSet data in an HTML Table in Servlet.................................................392 10.12 Specify the filename to be used for a file sent by a Servlet.......................................393 10.13 Pass information to another servlet/jsp......................................................................393 10.14 Handle PDF output....................................................................................................394 10.15 Detect if the connection is via a secure channel........................................................394 10.16 In a Servlet, check if Form Field is present................................................................394 10.17 Get the root dir of a web app.....................................................................................395 10.18 Get client IP address from JSP..................................................................................395 10.19 Output a binary stream from a JSP ............................................................................395 10.20 Use a connection cache from JSP.............................................................................396 10.21 Read a Web Application property..............................................................................397 10.22 Use EJB from JSP.....................................................................................................398 10.23 Define a method in a JSP page.................................................................................398 10.24 Precompile JSP pages ...............................................................................................399

10.25 Get a list of directories for JSP

Real's HowTo@www.rgagnon.com
10 Servlet/JSP 10.25 Get a list of directories for JSP..................................................................................400 10.26 Use and share a class in JSP pages.........................................................................400 10.27 Get the root dir of a web app.....................................................................................402 10.28 Launch an applet from a JSP .....................................................................................402 10.29 Prevent caching of a JSP output...............................................................................403 . 10.30 Call another EJB........................................................................................................403 10.31 Keep java files generated from JSP (BEA WLS).......................................................404 10.32 Get the server version (BEA WLS)............................................................................404 10.33 Quickly create a Web application with BEA WLS......................................................405 10.34 Nicely display WEB.XML informations.......................................................................405 10.35 Reverse the CLASSLOADER order (BEA)................................................................406 10.36 Detect change in JSP and recompile (BEA)..............................................................407 11 Language ...................................................................................................................................408 11.1 java−language.............................................................................................................408 11.2 * Read me * ..................................................................................................................408 11.3 Obtain from where a Class is loaded...........................................................................409 11.4 Get the class name in a static method.........................................................................410 11.5 Get the current method name......................................................................................410 11.6 Call a method dynamically (Reflection) .......................................................................411 . 11.7 Detect if a package is available...................................................................................413 11.8 Create an object from a string ......................................................................................414 11.9 Get a variable value from the variable name...............................................................415 11.10 Make methods that have unspecified number of parameters....................................416 11.11 Create a java source dynamically, compile and call..................................................417 11.12 Launch an application from another application........................................................418 11.13 Access the enclosing class from an inner class .........................................................419 11.14 Access inner class from outside................................................................................420 11.15 Use globally defined constants..................................................................................421 11.16 Serialize an Object.....................................................................................................422 11.17 Serialize an Object over a socket..............................................................................424 11.18 Easily remove my debugging code............................................................................424 11.19 Have a singleton........................................................................................................425 11.20 Multiple expressions in for loops................................................................................426 11.21 Handle the List conflict...............................................................................................426 11.22 Use a generic toString().............................................................................................426 11.23 Use Object.clone().....................................................................................................428 11.24 Static field, constructor and exception.......................................................................429 11.25 Use a Label break......................................................................................................430 11.26 Put printStackTrace() into a String.............................................................................431 11.27 Use a Hashtable........................................................................................................431 11.28 Scan the content of a hashtable................................................................................432 11.29 Sort an array..............................................................................................................432 11.30 Initialize multidimensional array.................................................................................434 11.31 Get array upperbound................................................................................................434 11.32 Convert a String to an array.......................................................................................435 11.33 Sort in reverse order..................................................................................................436 11.34 Resize an array..........................................................................................................436 11.35 Dump array content...................................................................................................437

Real's HowTo@www.rgagnon.com
11 Language 11.36 Initialize a static array................................................................................................438 11.37 Sort an Hashtable......................................................................................................439 11.38 Eliminate "[unchecked] unchecked call ..." compiler warning....................................440 12 ANT............................................................................................................................................442 12.1 Sort on many fields......................................................................................................442 12.2 Optimize Collection usage...........................................................................................444 12.3 Sort an HashMap.........................................................................................................446 12.4 Get a key from value with an HashMap.......................................................................446 12.5 Iterate a Collection and remove an item......................................................................447 12.6 Count distinct elements in a Vector.............................................................................448 12.7 Dump the content of a Collection (JDK 1.5)................................................................450 . 12.8 Use an INI file (properties)...........................................................................................450 12.9 Load a properties file...................................................................................................452 12.10 Accentuated characters in Properties/ResourceBundle file.......................................452 12.11 Have a multi−line value in a properties file................................................................453 12.12 Use XML with Properties...........................................................................................453 12.13 Use the Registry to store informations (Preferences API).........................................454 12.14 Sort Properties when saving......................................................................................455 13 Networking................................................................................................................................457 13.1 java−net.......................................................................................................................457 13.2 Extract network card address......................................................................................457 13.3 Get the workstation name/ip........................................................................................459 13.4 Find port number not in use.........................................................................................461 13.5 Disable DNS caching...................................................................................................461 13.6 Encode/Decode to/from Base64..................................................................................462 13.7 Using javax.mail.internet.MimeUtility...........................................................................463 13.8 Using Apache Commons Codec..................................................................................463 13.9 MiGBase64..................................................................................................................464 13.10 Lookup using MX record to validate mail server........................................................464 13.11 Send an email using the SMTP protocol...................................................................472 . 13.12 Check if there is mail waiting.....................................................................................474 13.13 Receive email............................................................................................................475 13.14 Send email with an attachment..................................................................................477 13.15 Send email with JavaMail..........................................................................................483 13.16 Send email with authentication..................................................................................485 13.17 Send HTML mail with images (Javamail) ..................................................................486 . 13.18 Debug a Javamail Program.......................................................................................488 13.19 Send email with SMTPS (eg. Google GMail) (Javamail)...........................................489 13.19.1 Settings for well known mail providers..............................................................490 13.20 Mix plain text and HTML content in a mail.................................................................490 13.21 Read an Outlook MSG file.........................................................................................491 13.22 msgparser..................................................................................................................491 13.23 Apache POI HSMF....................................................................................................492 13.24 jmbox.........................................................................................................................492 13.25 Handle EML file with JavaMail...................................................................................492 13.26 Check if a file was modified on the server.................................................................493 13.27 Check if a page exists................................................................................................494

13.28 Connect through a Proxy

Real's HowTo@www.rgagnon.com
13 Networking 13.28 Connect through a Proxy...........................................................................................495 13.29 Identify yourself using HTTP Authentification............................................................498 13.30 Talk to a CGI/Servlet.................................................................................................500 . 13.31 Write/Read cookies using HTTP................................................................................501 13.32 Read a GIF or CLASS from an URL save it locally ....................................................503 13.33 Resolve a relative URL..............................................................................................504 13.34 File size from URL.....................................................................................................505 13.35 Use the HTTPS protocol............................................................................................505 13.36 Fetch a page from Google.........................................................................................506 13.37 Upload a file to a server.............................................................................................507 13.38 Connect through a Proxy...........................................................................................507 13.39 Have timeout on socket connection...........................................................................510 13.40 Ping a server..............................................................................................................510 13.41 Get the Date from server...........................................................................................511 13.42 Get the client IP address ............................................................................................512 13.43 Use the java.net.Socket.setSoLinger method............................................................512 13.44 Use the java.net.Socket.setTcpNoDelay method......................................................513 13.45 Find out who is accessing my ServerSocket.............................................................513 13.46 Transfer a file via Socket...........................................................................................513 14 Security ......................................................................................................................................516 14.1 java−security................................................................................................................516 14.2 Encrypt a password.....................................................................................................516 14.3 Create a checksum......................................................................................................518 14.4 Get the user name.......................................................................................................521 14.5 Get username using NT Challenge (NTLM)................................................................521 14.6 Check if the current user belongs a specific Windows group/role...............................523 14.7 Prompt for password from the console........................................................................523 14.8 Prevent XSS exploit.....................................................................................................524 14.9 Sanitize the input by removing suspicious tags...........................................................525 14.10 Sanitize the output by removing suspicious characters.............................................525 14.11 Display a simple username/password Dialog from an Applet....................................526 15 Swing.........................................................................................................................................529 15.1 java−swing...................................................................................................................529 15.2 * Read me * ..................................................................................................................529 15.3 Change component default font...................................................................................529 15.4 Repaint problem under the mouse cursor (JDK1.2)....................................................530 15.5 Set the LookAndFeel...................................................................................................530 15.6 Use any LookAndFeel on any plateform......................................................................530 15.7 Use a Timer.................................................................................................................531 15.8 Share ActionEvent handler..........................................................................................531 15.9 Get default values for Swing−based user interface.....................................................533 15.10 Have a systray icon (Windows) .................................................................................534 . 15.11 Close a JFrame under condition................................................................................536 15.12 Maximize a JFrame ....................................................................................................537 15.13 Capture System.out into a JFrame............................................................................538 15.14 Remove the titlebar of JInternalFrame .......................................................................540 15.15 Have borders on a JWindow/JFrame .........................................................................540

Real's HowTo@www.rgagnon.com
15 Swing 15.16 Display HTML in a JScrollPane.................................................................................541 15.17 Use a JOptionPane....................................................................................................542 15.18 Localize a JOptionPane dialog..................................................................................543 15.19 Customize JOptionPane buttons...............................................................................545 15.20 Localize a JFileChooser............................................................................................545 . 15.21 Select a directory with a JFileChooser ......................................................................548 . 15.22 Disable the JFileChooser's "New folder" button .........................................................549 15.23 Validate a filename from a JFileChooser...................................................................550 15.24 Make a JFrame looks like a JDialog..........................................................................552 15.25 Based on JTextField content, enable or disable a JButton........................................553 15.26 Apply special filter to a JtextField ...............................................................................553 15.27 Limit JTextField input to a maximum length ...............................................................556 15.28 Validate a value on the lostFocus event....................................................................557 15.29 Make sure that my jTextfield has the focus when a JFrame is created.....................559 15.30 Stop the beep on JFormattedTextField ......................................................................560 15.31 Right justified JTextfield content................................................................................560 15.32 Set the focus on a particuliar JTextField....................................................................561 15.33 Make JTextField unselectable...................................................................................561 15.34 Use a JTree to navigate in a site...............................................................................562 15.35 Expand or collapse a JTree.......................................................................................568 15.36 Have a popup attached to a JTree .............................................................................570 15.37 Traverse a JTree ........................................................................................................572 15.38 Show dotted lines in a JTree ......................................................................................574 15.39 Explore directories with a JTree .................................................................................574 15.40 Prevent JTree collapsing...........................................................................................575 15.41 Single selection in a JTree.........................................................................................576 15.42 Reduce JTree children indentation............................................................................576 15.43 Use + or − for JTree Icons.........................................................................................576 15.44 Change the JTable header color...............................................................................578 . 15.45 Double click on a JTable............................................................................................578 15.46 Read a data file into a JTable....................................................................................580 15.47 Disable row selection in a JTable..............................................................................583 15.48 Read a data file into a JTable and reload if data file have changed..........................583 15.49 Hide a column in JTable............................................................................................585 15.50 Scroll a JTable to the last row....................................................................................586 15.51 Transfer a ResultSet to a JTable...............................................................................587 15.52 Have on a JScrollPane/JTable an horizontal JScrollbar............................................587 15.53 Make a JList select an item on doubleclick or the ENTER key..................................588 15.54 Make a JList like a scrolling text display....................................................................589 15.55 Have images in a JList...............................................................................................590 15.56 Add a row and clear a JList.......................................................................................592 . 15.57 Sort a JList.................................................................................................................593 15.58 Double click on a JList...............................................................................................595 15.59 Have a PopUp on a JList...........................................................................................596 15.60 Make a JLabel selectable with the mouse.................................................................597 15.61 Change JLabel background color..............................................................................598 15.62 Bold / Unbold a JLabel...............................................................................................598 15.63 Multi−line JLabel........................................................................................................598 15.64 Underline a string.......................................................................................................598

15.65 Update a JLabel

Real's HowTo@www.rgagnon.com
15 Swing 15.65 Update a JLabel.........................................................................................................599 15.66 Display a blinking JLabel...........................................................................................599 15.67 Set the cursor position in a JTextArea.......................................................................601 15.68 Have Multi−line string in a JToolTip...........................................................................601 15.69 Change Tooltip color..................................................................................................602 15.70 Change a JTooltip font...............................................................................................602 15.71 Keep a JTooltip visible...............................................................................................603 15.72 Display icon associated with an executable ...............................................................603 15.73 Have items in JMenubar at rightmost position...........................................................605 15.74 Have an JButton with an Image.................................................................................606 15.75 Trigger a click on a Button.........................................................................................607 16 Thread ........................................................................................................................................609 16.1 java−thread..................................................................................................................609 16.2 Pipe the output of a thread to the input of another one ................................................609 16.3 Pipe the output of a thread to the input of other threads ..............................................611 16.4 Wait the for the completion of a thread........................................................................613 16.5 Control a thread from outside......................................................................................614 16.6 Create a Timer object..................................................................................................615 16.7 Pause the execution....................................................................................................616 16.8 Execute a method at a specified time interval.............................................................616 16.9 Execute a process at regular interval..........................................................................618 . 16.10 Handle concurrent read/write.....................................................................................619 16.11 Communicate between threads using a Queue.........................................................620 16.12 Get a unique identifier................................................................................................625 16.13 Using java.rmi.dgc.VMID...........................................................................................625 16.14 Using java.util.UUID...................................................................................................625 16.15 Using Apache commons............................................................................................626 16.16 Using java.util.concurrent.AtomicLong .......................................................................626 17 Varia...........................................................................................................................................627 17.1 java−varia....................................................................................................................627 17.2 Use System time to generate unique ID......................................................................627 17.3 Get a unique identifier..................................................................................................627 17.4 Using java.rmi.dgc.VMID.............................................................................................627 17.5 Using java.util.UUID.....................................................................................................628 17.6 Using Apache commons..............................................................................................628 17.7 Using java.util.concurrent.AtomicLong .........................................................................628 17.8 Get the hard disk serial number or Motherboard serial number..................................629 17.9 Motherboard serial number..........................................................................................629 17.10 Hard disk serial number.............................................................................................630 17.11 Sort an array..............................................................................................................631 17.12 Sort a String array......................................................................................................632 17.13 Do a selection sort.....................................................................................................634 17.14 Validate a Social Security Number (canadian)..........................................................635 17.15 Validate a Credit Card Number..................................................................................636 17.16 Obtain from where a Class is loaded.........................................................................639 17.17 Get the class name with or without the package.......................................................640 17.18 See the generated bytecode......................................................................................641

Real's HowTo@www.rgagnon.com
17 Varia 17.19 Self replicating programs...........................................................................................644 17.20 A curiosity (strange Java code).................................................................................645 . 17.21 Classic bugs ...............................................................................................................646 17.22 Number of the beast!.................................................................................................647 17.23 Preventing multiple instances of an application.........................................................648 17.24 Trap JVM shutdown...................................................................................................651 17.25 Use Java scripting engine (JDK 1.6).........................................................................651 . 18 XML............................................................................................................................................653 18.1 java−xml ......................................................................................................................653 . 18.2 Read me......................................................................................................................653 18.3 Display XML using plain HTML....................................................................................654 18.4 Transform XML into HTML using XSLT.......................................................................655 18.5 Parse using SAX or DOM............................................................................................656 18.6 Parse an XML string....................................................................................................658 18.7 Create an XML document with DOM...........................................................................659 18.8 Attach a stylesheet to an XML file ................................................................................661 18.9 Create an XML file and attach an XSL .........................................................................662 18.10 Nicely display WEB.XML informations.......................................................................665 18.11 Serialize an object using XML ....................................................................................666 18.12 Convert a flat file to XML (SAX).................................................................................667 18.13 Convert a flat file to XML (DOM)................................................................................669 18.14 Convert a ResultSet to XML......................................................................................672 18.15 Parse with XPath.......................................................................................................674 18.16 Strip extra spaces in a XML string.............................................................................675 18.17 Create an XML file and attach an XSL .......................................................................676 18.18 Use XML with Properties...........................................................................................679 18.19 Change a particular node in XML..............................................................................680 18.20 Create a RSS feed (part 1)........................................................................................681 18.20.1 RSS 2.0 .............................................................................................................681 18.20.2 Atom ..................................................................................................................682 18.20.3 Creating a feed ..................................................................................................683 18.20.4 Creating a feed with Apache Commons Digester.............................................683 18.20.5 Creating a feed with Rome ................................................................................685 18.21 Creating an RSS Feed (part 2)..................................................................................686 18.22 Parse a RSS XML file................................................................................................692 18.22.1 Parsing a feed with Apache Commons Digester..............................................692 . 18.22.2 Parsing a feed with ROME ................................................................................693 18.22.3 RSS−UTIL.TLD.................................................................................................694 18.23 Add a Live bookmark.................................................................................................694 18.24 Validate a RSS feed ...................................................................................................694 18.25 Attach a CSS to RSS feed.........................................................................................694 19 DEPRECATED...........................................................................................................................697 19.1 java−deprecated..........................................................................................................697 19.2 * Read me * (this howto is deprecated)......................................................................697 19.3 Keep the console open after execution (this howto is deprecated).............................697 19.4 Read the Registry (this howto is deprecated)..............................................................698 19.5 Call a Win API (this howto is deprecated) ...................................................................698 .

.....................................................709 19.......10 Uninstalling the MS JVM (this howto is deprecated) .............................................725 20............................9 Get the latest MS JVM (this howto is deprecated).......... 19................731 20....................................................................................19 Substitute tokens in a String................................................................... 19......................................................19..............................................................rgagnon.........................................................................713 19.......14 Start an executable on the client (this howto is deprecated)..................15 Unaccent letters..............20 Use Netscape Java Console hidden commands (this howto is deprecated).....................10 Remove spaces from a string.......21 Avoid the Netscape "Couldn't connect to '' with origin from 'local−classpath−classes'" message....................................................................738 20.......6 Replace every occurences of a string within a string.....719 20..........................17 Format a String (JDK1....................................................................................7 "Tokenize" a string..................701 .......12 Sign an applet (this howto is deprecated)........................................................................................24 Get a list of headers from a newsgroup (this howto is deprecated).......700 19................11 Wrap a Java class in a COM object (this howto is deprecated) ....5)....................8 Split a string using String......2 * Read me * .........................................................................................................3 Convert from type X to type Y..............6 Display a BMP image (this howto is deprecated) Real's HowTo@www....................................................................715 20.701 19......................................................................19 Start automatically JAVA when opening Netscape (this howto is deprecated) .................................................................................. 20 String/Number .........15 Get rid of the message "Warning − unsigned applet window" (this howto is deprecated)..............................710 19...............................................................................................732 20....................717 20..................27 Make Swing always available from Netscape (this howto is deprecated) ...........714 20.....................13 Bypass the need for a certificate (this howto is deprecated).............. (this howto is deprecated) .........................................................................................5 Replace/remove character in a String ..........702 ..............709 19.........................1 java−stringnumber............................733 20..........................................................................704 19.732 20........................718 20...................................25 Get a list of all available newsgroup from a newsserver (this howto is deprecated)..............................................................................................706 19...704 19...............8 Detect if the MS JVM is used (this howto is deprecated) .................................13 Easy String padding..7 Play a WAV audio file (this howto is deprecated)................26 Detect if Swing is installed (this howto is deprecated)..... 19........................................................17 Write "other−browser−friendly" code when using the Netscape Capabilities package (this howto is deprecated)..........711 19.................12 Get InputStream from a String...................................737 20..........................................714 20.............................713 ...........14 Replace \r\n with the <br> tag.....................4 Strip certain characters from a String.........18 Disable the JIT compiler in Netscape or IE (this howto is deprecated) .....................................................................................................................720 20..........................731 20..................................................................................738 .....9 Optimize String operations ......20 Compare accentuated letters.701 ................................................................... 19.............................22 Post a message on a newsserver using NNTP protocol (this howto is deprecated).................... 19......................................................................................................com 19 DEPRECATED 19........6 Display a BMP image (this howto is deprecated)............................................................11 Test if a String starts with a digit or uppercase letter....706 19..............23 Read messages from a newsserver (this howto is deprecated).....730 20.......714 20..735 20...729 20...............................712 19.....................................18 Replace a "\" by "\\"...split()......700 19...........708 ......736 20...................................................................709 ....................710 19.............705 19..16 Read/write a local file from an Applet (this howto is deprecated).....................................................................16 Apply a mask to String................707 19................

.........742 20............44 Get a random number...........................util..................................................................25 Using HashMap.7 Run JAVA as a Windows service .776 21..........................................................................................................48 Pass floats as string literals to a method.............................................773 20...........755 20.............................................49 Get random numbers..........................................................................40 Round a double ...750 20..................................util................................................31 Convert a byte array to a Hex string.......53 Convert bytes to megabytes.54 Validate a number..............37 Justify a string with wordwrap..... 20.........29 Using regular expression.................749 20....57 Using java........28 Remove HTML tags from a file to extract only the TEXT ........35 Using Apache Commons Codec..............................745 20......................................771 20............................22 Unquote a String........................772 20.....................................776 21................39 Type conversion (JDK1...........769 20........................................................775 21...........................................50 Convert number into words..........................................................................................................754 20.............................................26 Using Array..........................................................................................................................60 Validate/Convert a number using the current Locale().....760 20..............................................770 20...............................................................27 Detect non−ASCII character in a String..............AtomicLong ........................................4 com4j................758 20.....................770 ............................................................................MimeUtility.........................................................................................................text..........................rgagnon...........................................59 Using java...................................................swing..................................................6 j−xchange...776 ........................VMID.............................................34 Using javax................................................................................................3 Call COM object.......................773 20.................................755 20......746 20.......................................................32 Apply proper uppercase and lowercase on a String...........................................................................46 Deal with big−endian and little−endian order...................................772 20.....................................................concurrent...........45 Convert an UNSIGNED byte to a JAVA type.............5)................23 Escape HTML special characters from a String ..........................759 20.............................1 java−os....................................743 20......................................41 Display numbers with commas..750 20............33 Encode/Decode to/from Base64.........................................................................................52 Detect even/odd number.................5 j−interop................................................................................................................38 Convert from type X to type Y........................................................21 Create a String with fixed length and filled with a specific character.................2 Call Windows API (Open source solution)..........................................................................................................................................773 21 Open Source..751 20.............775 21..775 21...............................Real's HowTo@www.......................................................................772 20..........36 MiGBase64...30 Using javax.......749 20..........758 20...........................47 Pass an integer by reference...................................................................................................................................................740 20...............................................................com 20 String/Number 20..........756 20...................................................................747 20.................................43 Display numbers with leading zeroes....................................................................56 Using java..............................................html.........58 Using Apache commons..................................UUID...................................mail..internet........775 21..........740 20............760 20.................................................................748 20.....................................................rmi....51 Arithmetic with double...................................................744 20.....24 Unescape HTML special characters from a String.....................................................................................................................dgc...................739 20..........775 21....................................................761 20....757 20..........................760 20............................................................................................................................HTMLEditorKit.......55 Get a unique identifier...............................................................750 20..............................746 20...........................746 20......42 Display numbers in scientific notation...................

.......................779 21............................................................................................................................................................21 CSVFile...............26 POI..............................................780 21.....................34 JadClipse..........................778 21.........................................................................................................................................43 File/directory polling to detect change....................27 JXLS.........................46 Java Native Access (JNA)...23 Handle Excel files..............................................................782 21.....42 jmbox...48 Java 7....................................................................................................................................................777 21....util CSV Utils............................................................................32 Convert a ............................................786 21....788 21..................................................................................21.........................................................................................................788 21................................778 21.........779 21.................................15 Handle CSV file ............................................................................................Ostermiller.......................................................................30 OpenXLS Java Spreadsheet SDK..........................................782 21..................................................................18 ServingXML..................................................13 JSmooth...................................................36 Deploy an application as only 1 jar..........................................................790 21....................779 21....................................................................................................................................rgagnon................20 csvreader...............................................25 JExcel..............................12 WinRun4J..................781 21.8 Create entity−relation diagram Real's HowTo@www...............................................................780 21...........................................................................................789 21...........................................................................................................................14 Launch4J..................................................789 21.............................40 msgparser................................................................................787 21.......22 FlatPack................................................................................................................790 21.....780 21.......................................................789 21...................8 Create entity−relation diagram ..........................787 21............................................................java file (decompiler).......................................................................................................786 21..............................784 21...............................................................................................................45 JNotify........................................class to ....................................787 21..........................................................39 Read an Outlook MSG file.............................................................787 21...779 21...............................................................................................11 Launch a java program as a Windows EXE file.........781 21...........................................................................................................................779 21............................................................35 JarPlug................................................................10 Create entity−relation diagram ......................................33 Jad..........47 Call native methods in a DLL from Java (NativeCall)..17 opencsv .................................................................31 Browse a Queue (JMS/MQ)...............................................................................................19 Super CSV........................................789 21................................................787 21.28 xlSQL..................................29 JCOM..........................................778 21.................789 21.........50 Create a PDF..........16 com.......51 iText.........................................................................................785 21...............44 jpoller (directory poller).............................................................................38 Fat Jar.....24 JDBC−ODBC Excel driver........778 21........................................................................................................41 Apache POI HSMF...................9 Java Remote desktop tool..............................................780 21.....................................786 21.................................................777 21..........790 ...........................................779 21...777 21..................................49 The simple (and naive!) approach.....................789 21...................................................................................37 One−Jar..............................................................................................................................................786 21..................com 21 Open Source 21..............................................779 21....................

getScreenSize().net."_top").html").html You have to use getAppletContext()."_top").whatever.rgagnon.applet.getDefaultToolkit().*. import java.1 java−applet 1. we want to display lowres. import java.*.2 Goto to a new URL from an Applet Current version of this HowTo : http://www.html page if resolution is 640x480 else the hires.com/javadetails/.showDocument (new URL("http://www.1 Applet 1./javadetails/java−0002. import java.showDocument (new URL(getCodeBase()+"hires. if (dim.*.showDocument (new URL(getCodeBase()+"lowres. or getAppletContext(). If "HTML frame ID" do not exists then a new browser window will be opened.html is used.height==480) { try { getAppletContext().whatever.awt."HTML FRAME ID").com"). } catch (Exception ex) {} } else { try { getAppletContext()..html"). } catch (Exception ex) {} } 1 Applet . public class whatres extends Applet { public void init() { Dimension dim = Toolkit. The following "HTML frame ID" have special meanings : "_self" "_parent" "_top" "_blank" current frame parent frame base frame new window For example.width==640 &dim.showDocument (new URL("http://www.com")).

printStackTrace(). TextField t. } catch (Exception e) { e.event.showDocument (new URL(getDocumentBase()+"/. b.toString()./lowres. } else { getAppletContext(). 1 Applet .} } NOTE: The previous example works only so long as the document was retrieved without specifying an actual document name. if (docString..awt.endsWith("/")) { getAppletContext().addActionListener(this).*.html"). since getDocumentBase() returns the full URL including the name of the document.google.applet. t. public class GotoURLButton extends Applet implements ActionListener { Button b. import import import import java. "_top"). If the document name was specified.net. type a new URL in a textfield. add(t).*. } } catch (Exception e) {} Another example.html"). java. "_top").setText("http://www.awt.showDocument (new URL(getDocumentBase()+"lowres.*.getText())).showDocument(new URL(t. java. java. b = new Button("Go to this URL").*. public void init() { t = new TextField(20).getSource() == b) { try { getAppletContext(). add(b).com"). you should try something like this or specify the complete URL (thanks to Rob Judd): : try { String docString = getDocumentBase(). } } } } Try it here. } public void actionPerformed(ActionEvent ae) { if (ae. and press a button to go to that page.

public void init(){ message = getParameter("message").. String message./javadetails/java−0003. StringBuffer buffer.applet.3 Determine the host from where the Applet is loaded . width Default values: message = "Isn't scrolling text in the status line annoying? " width = 36 Example usage: <applet code="ScrollStatus./javadetails/java−0010.html import java.com/javadetails/. public class ScrollStatus extends Applet implements Runnable { Thread thread.com/javadetails/.3 Determine the host from where the Applet is loaded Current version of this HowTo : http://www.util.class" width=0 height=0> <param name="message" value="Hello World!"> <param name="width" value="24"> </applet> */ import java. 1.4 Have a scrolling status line Current version of this HowTo : http://www.html /* ScrollStatus. // // you can check the value of getCodeBase() // to implements a simple copy protection // scheme. public class FromWhere extends Applet { public void init() { Label label = new Label(getCodeBase()..*.toString()). if(message == null) message = " Isn't scrolling text in the status line annoying? ". import java. import java.1.Applet.rgagnon.awt. If it's not equals to your // URL then quit.java Optional parameters: message.rgagnon. // NOTE : This is not a very strong protection! // } } Try it here 1. add(label). int at.applet. int width.*.*.

if(message. } } } } 1. } buffer = new StringBuffer(width).stop(). buf. } message. message = new String(buf).start(). if(ws == null) { width = 36.intValue(). if(at >= ml) { at = 0.length(). } getAppletContext(). ++i.length()) / 2).String ws = getParameter("width"). } else{ width = Integer.setCharAt(i.setLength(width). message.valueOf(ws).showStatus(buffer. } if(width < 5 || width > 180) { width = 36. } public void stop(){ thread. at++.length() < width) { char buf[] = new char[width]. } public void scroll(){ int ml = message. // wait 25 ms } catch(InterruptedException e){ break. (width − message. } buffer. at = 0. buffer. } } public void start(){ thread = new Thread(this). int k = at.3 Determine the host from where the Applet is loaded . } } public void run(){ while(true){ scroll(). thread.length(). ++i) { buf[i] = ' '.getChars (0.charAt(k)).toString()). ++k){ if(k >= ml) { k = 0. i < width. for(int i = 0. message. for(int i = 0.sleep(25). i < width. try{ Thread.

searchEngine. } } return true.addItem("AltaVista").5 Use a search engine Current version of this HowTo : http://www.*.net.com/javadetails/. searchEngine.addItem("Yahoo"). searchEngine = new Choice().addItem("WebCrawler").equals("")) { showStatus("Must enter a search string"). Choice searchEngine.toString()). } // JDK1.Applet.awt. if (searchString. searchEngine. break. public void init() { setBackground(Color. searchParameter = new TextField(20). import java. add(searchButton). public class SearchApplet extends Applet { TextField searchParameter. break.select(0).altavista. import java. 1. searchButton = new Button("Search").getSelectedIndex()) { case 0: url = "http://www. Button searchButton. add(searchParameter). } public void sendSearch() throws Exception { String url.white).equals(searchButton)) { try { sendSearch()..target.wbcrwl/search/web/". add(searchEngine). Object o) { if (e.getText().Try it here. } catch (Exception e1) { showStatus("Exception caught:" + e1.rgagnon.02 style event handling public boolean action(Event e. 1.*.webcrawler.applet.5 Use a search engine .com/web/results?q=". String searchString = searchParameter. searchEngine.html import java. case 1: url = "http://msxml.com/info./javadetails/java−0011. return. } switch (searchEngine.

It's not easy to call Google from an Applet but you can do it in application as seen in this HowTo. } // encode the search data url += URLEncoder.*. Color b. public class MyClock extends Applet { MyPanel mp. java.html import import import import java.start(). String dateText. java. f. java.applet.*.getForeground(). mct = new MyClockThread(this).getBackground(). default: showStatus("Invalid search engine selected. // launch the search engine showStatus("Connecting to search location " + url).yellow).util.yahoo. add(mp). f = this. String previousDateText = "".black). 1.. setBackground(new Color(0).awt.showDocument(new URL(url).*. SimpleDateFormat formatter.com/bin/search?p=".case 2: url = "http://search. break."). } public Dimension getPreferredSize() { return new Dimension 1. public void init() { mp = new MyPanel(getParameter("format")). setForeground(new Color(0). b = this.*. getAppletContext().rgagnon. return.text. validate().6 Have an on−screen clock Current version of this HowTo : http://www./javadetails/java−0012.com/javadetails/.encode(searchString). mct. } } Try it here. "_top"). formatter = new SimpleDateFormat(df). } } class MyPanel extends Panel { MyClockThread mct. MyPanel(String df) { super().6 Have an on−screen clock .

getFont()). } } public String getNow() { return formatter.format(new Date()). } catch(InterruptedException e) { } } } } <HTML><HEAD></HEAD><BODY> <APPLET CODE="MyClock.repaint().6 Have an on−screen clock .class" HEIGHT=25 WIDTH=200> <PARAM NAME="format" VALUE="H:mm:ss:SSS"> </APPLET><P> /BODY/HTML Try it here. } public void paint(Graphics g) { if (g != null) { g. } public void run() { while (true) { try { mp.class" HEIGHT=25 WIDTH=200> <PARAM NAME="format" VALUE="yyyy−MM−dd hh:mm:ss"> </APPLET><P> <APPLET CODE="MyClock.drawString(dateText. previousDateText = dateText. } } class MyClockThread extends Thread { MyPanel mp. g. this.MMMMM.10.15). g.drawString(previousDateText.stringWidth(getNow()) + 25. 30).10.(this.sleep(1000). public MyClockThread(MyPanel a) { mp = a. dateText = getNow().setColor(f).15).class" HEIGHT=25 WIDTH=200> <PARAM NAME="format" VALUE="yyyy.class" HEIGHT=25 WIDTH=200> <PARAM NAME="format" VALUE="h:mm a"> </APPLET><P> <APPLET CODE="MyClock.dd GGG hh:mm aaa"> </APPLET><P> <APPLET CODE="MyClock.getFontMetrics(this. g. 1.setColor(b).

com/javadetails/. } } [Applet2_0022. b = new Button("Send to Applet 2").java] import java.*.02 style evant handling public boolean action(Event ev.Applet { TextField inputText. public void init() { setLayout(new FlowLayout()).html [Applet1_0022. return true.append( textMsg ). add(b). if ( applet2 != null ) { applet2. Applet2_0022 applet2 = (Applet2_0022)getAppletContext().1.*. 40 ).java] import java.trim().println("Applet2 not found?").7 Have Applets on the same page communicate with each other .awt.getApplet("applet2").append( msg ). add(inputText).applet./javadetails/java−0022. textBox. public class Applet2_0022 extends java. Object arg) { if (ev. add( textBox ).awt.rgagnon. } } 1. } public void append( String msg ) { textBox.applet. inputText = new TextField( "". return false.getText(). Button b. } } return false. textBox = new TextArea( 5.target instanceof Button) { String textMsg = inputText. } else { System.out. public class Applet1_0022 extends java.Applet { TextArea textBox. } // JDK 1.append( "\n" ).. public void init() { setLayout(new FlowLayout()).7 Have Applets on the same page communicate with each other Current version of this HowTo : http://www. 15 ).

java)] import java.html It is possible to share data between different applets via static variables [HTML (java−0023.8 Have Applets on different frames communicates with each other Current version of this HowTo : http://www.html" NAME="f2"> </FRAMESET> </HEAD> [HTML (java−0023−f1.class" NAME="applet2" HEIGHT=200 WIDTH=400> </APPLET> </BODY></HEAD> Try it here.applet.html)] <HTML><HEAD></HEAD> <FRAMESET COLS="50%. 1.class" HEIGHT=200 WIDTH=200> </APPLET> </BODY></HTML> [JAVA source (Java0023. add(a). a = new Button("Send to Message"). import java.*.awt..b./javadetails/java−0023.com/javadetails/.class" NAME="applet1" HEIGHT=200 WIDTH=150> </APPLET> <APPLET CODE="Applet2_0022. b = new Button("Receive from Message"). Button a.rgagnon.[HTML] <HTML><HEAD></HEAD><BODY> <APPLET CODE="Applet1_0022.*.*"> <FRAME SRC="java−0023−f1. 1.html" NAME="f1"> <FRAME SRC="java−0023−f2.8 Have Applets on different frames communicates with each other .html)] <HTML><HEAD></HEAD> <BODY> <APPLET CODE="Java0023. public void init() { setLayout(new FlowLayout()).html AND java−0023−f2. public class Java0023 extends Applet { TextField tf.

1.*.rgagnon.02 style evant handling public boolean action(Event e.awt. There is one way to do it by using a Javascript function as a bridge./javadetails/java−0041.setText(StaticMessage.9 Send a message from an Applet to another Applet on a different page . } Try it here.*. } if (e.target instanceof Button) { if (e.9 Send a message from an Applet to another Applet on a different page Current version of this HowTo : http://www. java..target == a) { StaticMessage. } return false. tf = new TextField(20). java. Then SecondApplet decodes the search section of its URL and extract the message coming from FirstApplet.*.target == b) { tf. } return true.*. take a look at this How−to.class" HEIGHT=100 WIDTH=300> /APPLET/BODY/HTML FirstAppletJ. Check this DDJ article for a more elaborate way to implement this principle. } // JDK 1.message).html URL.getText(). Object o) { if (e. } } class StaticMessage { public static String message = "".message = tf.html FirstApplet encodes the message for SecondApplet in the search (or query) section of SecondApplet.event.awt. java.com/javadetails/.applet. FirstAppletJ.net.add(b).java import import import import java. add(tf). 1.html <HTML><HEAD></HEAD><BODY> <APPLET CODE="FirstAppletJ.

TextField add(tf).length()).2.net. } public void actionPerformed(ActionEvent ae) { if (ae. } catch (Exception e) { e. SecondAppletJ extends Applet { init() { new Label("Message from 1st Applet"). public void init() { add(new Label("Message to 2nd applet :")).*. /* with JDK1.substring(s.html?" + "message=" + URLEncoder. add(t= new TextField(20)). import java.URLDecoder. tf = new TextField( 50 ).awt. } } } } SecondAppletJ. import java.getSource() == b) { try { getAppletContext().toString().encode(t.showDocument (new URL(getCodeBase(). "SecondAppletJ. b. // complete current URL String s = getDocumentBase().printStackTrace().java import java.substring("message=". public class public void Label l = add (l).addActionListener(this).class" HEIGHT=100 WIDTH=400> /APPLET/BODY/HTML SecondApplet.*.applet.public class FirstAppletJ extends Applet implements ActionListener { Button b.getText()))).decode(theMessage). 1. add(b = new Button("Load 2nd applet")). // extract the search (or query) section String theMessage = s.*.html <HTML><HEAD></HEAD><BODY> <APPLET CODE="SecondAppletJ. // decode the string (incomplete) theMessage = theMessage.replace('+'.indexOf('?') + 1).net. TextField t.' '). the decoding can be done with java. // remove message header theMessage = theMessage.9 Send a message from an Applet to another Applet on a different page .

The remaining characters are represented by 3−character strings which begin with the percent sign. .Applet. The ASCII characters 'a' through 'z'. 'A' through 'Z'.html) <HTML><HEAD></HEAD><BODY> <APPLET CODE="AppletLoader. "%xy". public class AppletLoader extends Applet implements Runnable.10 Have an applet launch an other applet Current version of this HowTo : http://www.AppletStub. 1. } } You can try it here! NOTE : On IE.html The idea is to load first a small Applet with a quick loading time. AppletStub { String appletToLoad. display a message to the user and then load a larger Applet.. .applet. each character is examined in turn: . you must be connected to the Internet The decoding is incomplete but should be Ok for simple need! If you need to pass the message via the PARAM tag of the SecondApplet then take a look at this How−to./javadetails/java−0025.com/javadetails/.rgagnon. where xy is the two−digit hexadecimal representation of the lower 8−bits of the character. import java. [HTML (testappletloader. and '0' through '9' remain the same.you to convert from a MIME format called "x−www−form−urlencoded" to a String To convert to a String.awt. import java.java)] import java.class" NAME="AppletLoader" HEIGHT=200 WIDTH=200> <PARAM NAME="appletToLoad" VALUE="SecondApplet0025"> <PARAM NAME="SecondAppletParm" VALUE="Hello World"> </APPLET></BODY></HTML> [JAVA source (AppletLoader.10 Have an applet launch an other applet .setText(theMessage). 1.applet. The plus sign '+' is converted into a space character ' '. Thread appletThread.*. */ tf.

public void init() { System.start().stop().. int height ){ resize( width. } } [SecondApplet0025. 30. // Class appletClass = Class. } public void appletResize( int width. public class SecondApplet0025 extends java.out. add(realApplet).. setLayout( new GridLayout(1. realApplet.start().white).out.applet. setBackground(Color. } catch (Exception e) { System.java for demonstration] import java.0)).*.Applet { TextField tf. } public void run() { try { // // REMOVE THIS // for demo purpose only to see // the "loading message! // Thread.setText(s).newInstance(). String s = getParameter("SecondAppletParm").". realApplet.forName(appletToLoad). tf. } validate().drawString("Loading the Second Applet .println("Starting Second applet").init().println( e ).10 Have an applet launch an other applet . } public void start(){ appletThread = new Thread(this). appletThread = null.setStub(this). appletThread. } public void paint(Graphics g) { g. realApplet. add(new Label("Second Applet")). 30). add(tf = new TextField( 10 ) ).awt. height ). } } 1. Applet realApplet = (Applet)appletClass.sleep(2000). } public void stop() { appletThread.public void init() { appletToLoad = getParameter("appletToLoad").

// ex. String name = searchparms.security. public void init() { // dump to the console the URL.security.applet.auth. the search and search values // the URL http://myserver.getProperty("user.NTSystem NTSystem = new com. public class AppletUrlParams extends Applet { Hashtable searchparms..auth. something like an ASP page can be used to detect the current NT user name if the client is configured correcty. String completeURL = getDocumentBase().html import java.toString().com/mypage./javadetails/java−0048.5 public class Test { public static void main(String args[]) { com.get("value2") doit()./javadetails/java−0049.rgagnon. } } In Applet there is no way unless you ask for it or use a signed applet. } public void doit() { int i. import java.module.name").com/javadetails/.sun.11 Get the user name .println(NTSystem.12 Access parameters passed in the URL Current version of this HowTo : http://www.module. or in JDK1. 1.NTSystem(). See this related HowTo for a JSP hack! 1.html In application : String username.sun. System.11 Get the user name Current version of this HowTo : http://www.try it here.rgagnon.util.*.getName()). If you have access to a server−side. username = System.out.*. 1.html?value1=x&value2=y&value3=z // the search value1=x&value2=y&value3=z // the values value1=x // value2=y // value3=z // // then the values are stored in a Hashtable for easy reference..com/javadetails/.

nextElement().println("Search URL: " + searchURL).indexOf("?"). System.keys().println("−−−−−−−−"). java.com/applets/ IE: www. } } public void dumpHashtable() { Enumeration keys = searchparms. while( keys.hasMoreTokens()){ String searchValue=st. StringTokenizer st1 = new StringTokenizer(search. StringTokenizer st = new StringTokenizer(searchURL.put(st2.11 Get the user name .hasMoreElements() ) { String s = (String) keys. but only domain name and directory but without . } System.decode(st2.domain.toString().println("value :" + searchValue).html and parameters.nextToken().com/applets/win.println("−−−−−−−−").domain. So: if we have www. System.html?winner=Maurice 1. dumpHashtable().URLDecoder.nextToken(). " while(st1. System.out.5) it's ok. searchparms. } } Test it here.indexOf("?") + 1). if (i > −1) { String searchURL = completeURL.out.get(s)).substring(completeURL.out.com/applets/win. The resultat in the Java console should be : key : firsparam value : Hello key : secondparam value : World key : thirdparam value : Hello World A note from mm300 Access parameters passed in the URL in line String completeURL = getDocumentBase(). System.out.nextToken(). } initHashtable(searchURL).out.nextToken())). i = completeURL.net. "=").println("Complete URL: " + completeURL). } } public void initHashtable(String search) { searchparms = new Hashtable().println("key : " + s + " value : " + searchparms. " while(st.hasMoreTokens()){ StringTokenizer st2 = new StringTokenizer(st1.out.html?winner=Maurice getDocumentBase () will return: NS: www.System. In IE (5.domain. is a trap: NS won't return the whole URL.

com/javadetails/. public void init() { add(new Button("Real's")).1.awt. x+getFontMetrics(getFont()). int x=20.rgagnon. } 1.add(ut).setSize(100. f. seems enough for the Frame title.awt. public class UnderlineText extends Panel{ String s = "Java Howto". y+2 ). put it in Frame and call the init() method. f. ut.100). import java. // add 20.pack().exit(0).awt. f. }.event.WindowEvent e) { System.*.init(). ut. public static void main(String[] args) { Frame f = new Frame().*. } public void paint(Graphics g) { g.applet.WindowAdapter() { public void windowClosing(java. y+2 .setSize(100.addWindowListener(new java.100 + 20). we simply extend a Panel instead of an Applet.html Take this simple Applet import java. g. // same size as defined in the HTML APPLET f. int y=50. } } You use it with the following HTML <HTML> <TABLE><TR><TD> <APPLET CODE=UnderlineText. import java./javadetails/java−0305.13 Convert an Applet to Application Current version of this HowTo : http://www.show(). int y=50.drawString(s. }). x. public class UnderlineText extends Applet{ String s = "Java Howto". UnderlineText ut = new UnderlineText().event.y).drawLine(x .awt. f.*. int x=20.class WIDTH=100 HEIGHT=100> </APPLET> /HMTL To be able to use the same class as an application.13 Convert an Applet to Application ..stringWidth(s) .

E_RESIZE_CURSOR. } browserFrame = (Frame) parentComponent. 1.14 Change the mouse cursor in Applet . parentComponent = getParent().getParent().WAIT_CURSOR)).0.15 Use an Image as the Applet background Current version of this HowTo : http://www. NE_RESIZE_CURSOR. y+2 ). Component parentComponent./javadetails/java−0228. DEFAULT_CURSOR..Applet.getPredefinedCursor(Cursor. N_RESIZE_CURSOR.drawString(s. g. TEXT_CURSOR. W_RESIZE_CURSOR. SW_RESIZE_CURSOR. } } 1.rgagnon.rgagnon.applet. x+getFontMetrics(getFont()).1] // setCursor is supported at the component level setCursor(Cursor.html [JDK1.WAIT_CURSOR).stringWidth(s) .*.html import java. NW_RESIZE_CURSOR. // // // // TILE BACKGROUND in the HTML use : PARAM NAME="bgImage" VALUE="images/myImage. x.public void init() { add(new Button("Real's")).com/javadetails/.SE_RESIZE_CURSOR. HAND_CURSOR MOVE_CURSOR. S_RESIZE_CURSOR.2] // loop until the browser frame Frame browserFrame. // // // // // // // CROSSHAIR_CURSOR. while ( parentComponent != null && !(parentComponent instanceof Frame)) { parentComponent = parentComponent. } public void paint(Graphics g) { g.jpg" in the APPLET tag public class Tile extends Applet { 1. import java.y). y+2 .14 Change the mouse cursor in Applet Current version of this HowTo : http://www./javadetails/java−0233.com/javadetails/.setCursor(Frame. WAIT_CURSOR [JDK1.drawLine(x . browserFrame..net.

rgagnon.getHeight(null).html Microsoft has now licensed the technologies from Eolas. } setLayout(new FlowLayout()). public void init() { try { MediaTracker tracker = new MediaTracker (this).Image bgImage = null.clearRect(0.width) { g.addImage (bgImage.class WIDTH=150 HEIGHT=150> <PARAM NAME="bgImage" VALUE="images/jht. while(y < size(). 0).height) { x = 0.width. tracker.16 Handle the new Control Activation mechanism in IE Current version of this HowTo : http://www.waitForAll(). size(). this). removing the click to activate requirement in Internet Explorer. More at IEBlog 1. add(new Button("Ok")). 0. x=x+bgImage. } } } <HTML> <TABLE><TR><TD> <APPLET CODE=Tile. } public void paint(Graphics g) { if(bgImage != null) { int x = 0. add(new TextField(10)). size().drawImage(bgImage. } y=y+bgImage. bgImage = getImage (new URL(getCodeBase(). y.com/javadetails/./javadetails/java−0526.getWidth(null). tracker.printStackTrace(). while(x<size(). y = 0. } public void update( Graphics g) { paint(g). } } else { g..16 Handle the new Control Activation mechanism in IE . This change will be made part of the next pre−release versions of Windows Vista SP1 and Windows XP SP3. x.height). 1. getParameter("bgImage"))).gif"> </APPLET> /HMTL Try it here. } catch (Exception e) { e.

Both on the same page (same Applet).class" height="2000" width="196"></applet>') NOTE If you uncheck the Disable Script Debugging (Internet Explorer) option in the Advanced Tab of the Internet Options Control Panel. Interactive controls loaded from external script files immediately respond to user interaction and do not need to be activated. EMBED. each interactive control must be individually activated. NOTE: While inactive controls do not respond to direct user interaction. When a web page uses the APPLET.1 Solution #1 The workaround for an APPLET (to bypass the manual activation) is to generate in Javascript the APPLET tag but you need to generate it from an outside JS page! <html> <body leftmargin=0 topmargin=0 scroll=no> <script src="myapplet. controls will still require activation.js is document. If a page uses these elements to load multiple controls. all you need is to change the content from an outside file.16. Try a page with the regular APPLET tag here. So you need a generic JS function to rewrite the APPLET tag with the original and that's it! The main HTML (in BODY tag we call our "rewrite" function) : <HTML><HEAD></HEAD> 1.js"></script> </body> </html> and the myapplet. 1. here! The workaround suggested by Microsoft is fine with static APPLET tag but if your APPLET tag needs to be generated by a JSP ou Servlet (to adjust the PARAM parameters for example) then you're out of luck because the APPLET declaration is in a JS file which is a static file. Then to activate an interactive control. A tooltip "Click to activate and use this control" is shown.16.2 Solution #2 As seen in this article. This was done to resolve an issue concerning a patent problem with a company called Eolas.1 Solution #1 .The latest IE patch introduces a new behavior with APPLETS or ActiveX controls on a page. the control's user interface is blocked until the user activates it. either click it or use the TAB key to set focus on it and then press the SPACEBAR or the ENTER key.16. Check out this Microsoft's white paper on the subject.write ('<applet code="MyApplet. they do respond to script commands. or OBJECT elements to load an ActiveX control. 1. And now the same APPLET but with an external JS file here.

"> <p>This example "rewrite" the applet tag from an external JS.outerHTML=el.js"> </script> <APPLET CODE="TextFieldWithLimitApplet. the PARAMS can be handled by the main page like before! The trick is to have 2 external JS function.write 1. one to write the <APPLET> tag (and the static PARAM if any) and a second function to write the </APPLET>.js] function writeHeader(urlApplet) { document. • For simple applet with no param.class"') document.ediy.<BODY onload="rewriteApplet(). for(i=0./rewriteapplet.class" HEIGHT=100 WIDTH=300> </APPLET> </BODY></HTML> The generic JS routine to rewrite all APPLET tags.3 Solution #3 . this trick does not work from a FRAME! • If you have PARAM tags associated with the applet then they will be replaced by two strange PARAMS (_CX and _CY)! So beware.nz/internet−explorer−flash−applet−activation−fix−xidc19237.write (' width="100%" height="98%" hspace="0" vspace="0" align="middle" >') document.co. this is an interesting generic solution. This site http://www. Pre−XP SP2 installation are not supposed to do that kind of substitution (not verified!). The enclosed dynamic PARAM parameters are generated by the JSP (ASP page)..length.16. The requirement is to write only the APPLET tag from an outside JS file. 1.2" src=". el.3 Solution #3 This solution is a little bit ugly but there is no better solution when you have dynamic APPLET PARAM generated on the server−side. IMPORTANT NOTES : • AFAIK.html offers a really small JS script (only 292 bytes long) to handle the situation.getElementsByTagName("applet"). This way you can generate the Applet tag from a JSP like before.outerHTML } } Try it here! The same principle can be used for the OBJECT tag. It looks that this behaviour has something to do with the fact that the Java plugin is an ActiveX.16..i++){ var el=v[i]. [rewriteapplet.js] function rewriteApplet() { var v=document.write ('<applet codebase="' + urlApplet + '" code="myApplet. [rewriteapplet.i<v. <P> <script language="Javascript1.

} } else { %> <PARAM NAME="page1" value="<%=fileUrlErr %>"> <% } %> <script> writeFooter().com/javadetails/.. while (itPages. <script> writeHeader('<%=urlApplet %>').2" src="<%= CONTEXT_PATH %>/scripts/rewriteapplet. <script language="Javascript1. Iterator itPages = pages. and add the required parameters in the 4th 1.rgagnon.. %> <PARAM NAME="page<%=i%>" value="<%=url %>"> <% i++.write('</applet>') } The JSP or ASP .17 Pass parameters to the Applet JVM (WIN) . Press View button of the Applet Runtime Settings..html It's possible to pass some parameters to the JVM in Applet but these have to be set in the browser and cannot be controlled by your applet..iterator(). Each user that loads your applet has to adjust the JVM args themselves.. consider making a small donation to show your support for this Web site and its content./javadetails/java−0531.hasNext()) { String url = (String) itPages. /script If you find this article useful. </script> <% if(resultVB.js"> /script . Written and compiled by Réal Gagnon ©1998−2007 [ home ] 1.17 Pass parameters to the Applet JVM (WIN) Current version of this HowTo : http://www.isObjectInResult(idObject)) { int i = 1.(' } <PARAM NAME="printdialog" VALUE="false">') function writeFooter() { document.next(). Open the Java control panel (in Windows: Start > Control Panel > Java) and select the Java tab.

/javadetails/java−0533.com/javadetails/. you set a parameter for JRE Applet runtime. it's in the folder : C:\Documents and Settings\ <username>\ Application Data\ Sun\ Java\ Deployment\ log It's a file with the extension . Written and compiled by Réal Gagnon ©1998−2006 [ home ] 1. You can force the language used in the Java console. you set a parameter for JRE Applet runtime.do?bug_id=4839812.18 See the Java Console Window Log (Java plugin) . • Specify −Duser. otherwise your browser will die when it tries to open the first applet.sun. In java control panel − java tab.language=en to override the default locale in java control panel −> java tab.column..trace If you find this article useful. On the Windows plateform. consider making a small donation to show your support for this Web site and its content. You have to make sure that that the parameter you supply are correct.html The Java Console Window Log is also stored on disk. 1.com/bugdatabase/view_bug. it is editable event if it's grayed. This can be useful to set a JVM property to resolve a compatibilty problem with graphic card like in this bug report : http://bugs.rgagnon.18 See the Java Console Window Log (Java plugin) Current version of this HowTo : http://www.

The log is stored in a file.html See this interesting article : http://windyroad. On the Java tab.. −Djavaplugin. <applet id="applet_name" code="path_to_applet_class/class_name" style="width: 1px. float: left.org/2006/08/14/reintroducing−javascript−and−hidden−applets−jaha/ The recommended way is to a CSS style to hide the Applet.com 1.rgagnon.19 Display debugging infos for an Applet Current version of this HowTo : http://www.rgagnon. on the Advanced tab.exe.com/javadetails/. See this HowTo for an example. Start the Java Configuration Panel via Start−Parameters or you can launch C:\Program Files\Java\jre[version]\bin\javacpl.trace. or you can insert your Applet into an invisible frame. For Windows... the java console will display with a full trace.html Make sure that all browsers and JRE are closed. the file is C:\Documents and Settings\[YourAccount]\Application Data\Sun\Java\Deployment\log\plugin[version]./javadetails/java−0620.option=basic|net|security|ext|liveconnect Next. height: 1px.1.log/trace 1.20 Have an invisible Applet Current version of this HowTo : http://www. click to set the parameter for the applet runtime (plugin).trace=true −Djavaplugin. select Java Console −> Display the console.com/javadetails/.rgagnon.19 Display debugging infos for an Applet .com http://www./javadetails/java−0597. Now add the following parameters in the column parameters." mayscript></applet> . Written and compiled Réal Gagnon ©2007 real@rgagnon. The next time when loading an applet.

} public static void main(String arg[]) { System. import java. return sdf.getTime()).2 Have year on 4 digits from a Date object Current version of this HowTo : http://www. So 100 + 1900 = 2000.getYear() + 1900.Calendar. So for year 2000.rgagnon. SimpleDateFormat sdf = new SimpleDateFormat(dateFormat)./javadetails/java−0096.2 Date and Time 2. SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW). mydate.getYear() will return 100.SimpleDateFormat. public class DateUtils { public static final String DATE_FORMAT_NOW = "yyyy−MM−dd HH:mm:ss".com/javadetails/./javadetails/java−0106. The getYear() method returns the number of years elapsed after the year 1900.text. return sdf. import java.rgagnon.3 Get the current Date and Time Current version of this HowTo : http://www.html You need to add 1900 to it to get the 4 digit year.util.out. } } Here some formatting possibilities available through the SimpleDateFormat class. 2 Date and Time .getTime()).html import java..util.Calendar.SimpleDateFormat.com/javadetails/.1 java−date 2. int year = myDate.now()). 2.getInstance()..format(cal.text.format(cal. public static String now() { Calendar cal = Calendar.getInstance(). import java.println("Now : " + DateUtils. public class DateUtils { public static String now(String dateFormat) { Calendar cal = Calendar.

now("dd MMMMM yyyy")).rgagnon.println(DateUtils.4 Compute days between 2 dates Current version of this HowTo : http://www.text.*.now("yyyy. Guirado for the idea.MM.getTime()) + " day(s) between " + sdf.util.println(DateUtils.out.out.html One technique is to compute by hand the number of milliseconds between two dates and then convert the result in days.SimpleDateFormat sdf = new java.println(DateUtils.out.getTime() − d1.println(DateUtils.z")).println(DateUtils.out.now("EEE. } } Thanks to T.now("dd.getTime() + ONE_HOUR) / (ONE_HOUR * 24)).println(DateUtils.getTime().second.now("MM/dd/yy")). System.out. Calendar second = Calendar.out.getTime()) + " and " + sdf.out. /* * output : * 21 day(s) between 20080801 and 20080822 */ } 2. System.now("yyyyMMdd")).set(2008.} public static void main(String arg[]) { System.. Calendar first = Calendar. System. first.text. import java.dd G 'at' hh:mm:ss z")). System. System. MMM d.out.AUGUST.dd GGG hh:mm aaa")).getTime())).format(first.println(DateUtils. System. public static long daysBetween(Date d1.getInstance().SimpleDateFormat("yyyyMMdd").MMMMM.out.now("H:mm:ss:SSS")). 2. System.println(DateUtils.println (daysBetween(first.now("h:mm a")).out. Calendar.com/javadetails/.4 Compute days between 2 dates .println(DateUtils.MM. Date d2){ return ( (d2. } /* testing */ public static void main(String[] args) { java.format(second.println(DateUtils.now("yyyy. ''yy")). 1).getInstance().now("K:mm a. System. System. System.out.yy"))./javadetails/java−0097. public class DateUtils { private DateUtils() { } static final long ONE_HOUR = 60 * 60 * 1000L.

5 Get the number of days in a month .getInstance(). Calendar second = Calendar.TimeUnit.getTimeInMillis()− a.set(2008.31. The package java.format(first.out. Calendar first = Calendar. See this HowTo. One hour (known as the "fudge" factor) is added to the 2 Dates passed as parameters to take in account the possible DLS (Day Light Saving) one hour missing. TimeUnit.30.31.DAYS) + " day(s) between " + sdf.AUGUST. /* * output : * 21 day(s) between 20080801 and 20080822 */ } } 2. } Actually.TimeUnit. TimeUnit units) { return units. 1). daysInMonths[1] += c.util. public class DateUtils { private DateUtils() { } public static long getDifference(Calendar a. import java.getTime()) + " and " + sdf.convert(b.get(GregorianCalendar.html public static int daysInMonth(GregorianCalendar c) { int [] daysInMonths = {31.31}.MONTH)]. System. the Calendar class provides a method to that very simply. Another way would be to compute the julian day number of both dates and then do the substraction. first.31.getInstance().isLeapYear(c.31.concurrent.SimpleDateFormat("yyyyMMdd").get(GregorianCalendar. Thanks to P..} NOTE: The daysBetween() method works only on Dates set at midnight. import java.com/javadetails/.TimeUnit./javadetails/java−0098.println (getDifference(first. Calendar.text.second. } /* testing */ public static void main(String[] args) { java.concurrent.MILLISECONDS).YEAR)) ? 1 : 0.5 Get the number of days in a month Current version of this HowTo : http://www.*.30.getTime())). For a given Calendar or GregorianCalendar object : 2.30.31. Hill for the tip. return daysInMonths[c.text. provides a class to make conversion between milliseconds and days easier.getTimeInMillis().SimpleDateFormat sdf = new java. Calendar b.rgagnon.format(second.util.30.util.28.

DAY_OF_MONTH) In the Java API documentation there is a note saying that The version (getActualMaximum()) of this function on Calendar uses an iterative algorithm to determine the actual maximum value for the field. } public static void main(String[] args) { System.6 Validate a date Current version of this HowTo : http://www. There is almost always a more efficient way to accomplish this (in most cases.isValidDateStr("1900−12/13")).out.html 2. you can simply return getMaximum()).6 Validate a date .out./javadetails/java−0099.isValidDateStr("1900−12−13")).println(" 1900−12−13 valid ? " + DateUtils.6.println(" 1900−13−12 valid ? " + DateUtils.isValidDateStr("1900−13−12")).text.calObject. // "1990−13−12" throws a IllegalArgumentException System.com/javadetails/..getActualMaximum(calobject. // YYYY−MM−DD df.setLenient(false). } catch (ParseException e) { return false. } catch (IllegalArgumentException e) { return false.*. So it looks like it's a lot more efficient to call getActualMaximum from a GregorianCalendar object than a Calendar object.getActualMaximum(gregCalObject.out. public class DateUtils { public static boolean isValidDateStr(String date) { try { DateFormat df = DateFormat. // this is important! df. Harris for the tip) gregCalObject. GregorianCalendar overrides this function with a more efficient implementation.rgagnon. (Thanks to P.getDateInstance (DateFormat.println(" 1900−12/13 valid ? " + DateUtils.parse(date). // "1990−12/13" throws a ParseException System.SHORT).DAY_OF_MONTH) 2. /* * output : * 1900−12−13 valid ? true * 1900−12/13 valid ? false * 1900−13−12 valid ? false */ } } 2. } return true.1 Using DateFormat import java.

6. // exception thrown here } catch (Exception e) { e.YEAR.println(" 1900−12−13 valid ? " + DateUtils. } catch (IllegalArgumentException e) { return false.setLenient(false).printStackTrace(). /* * output : * 1900−12−13 valid ? true * 1900−12/13 valid ? false * 1900−13−12 valid ? false */ } } 2.MONTH. gc.rgagnon.isValidDateStr("1900−12−13".set(GregorianCalendar. sdf.setLenient(false).out.set(GregorianCalendar.set(GregorianCalendar. import java. // must do this gc.getTime().Using SimpleDateFormat package com."yyyy−MM−dd")).isValidDateStr("1900−13−12". 1).// invalid month gc."yyyy−MM−dd")). // "1990−12/13" throws a ParseException System.out.6."yyyy−MM−dd")). 2003). } } } 2. } return true.2 Using GregorianCalendar import java. } public static void main(String[] args) { System.println(" 1900−13−12 valid ? " + DateUtils. } catch (ParseException e) { return false.util.println(" 1900−12/13 valid ? " + DateUtils.parse(date).isValidDateStr("1900−12/13". 42).DATE. public class DateUtils { public static boolean isValidDateStr(String date.*.*. sdf.howto. gc.text.out.2 Using GregorianCalendar . // "1990−13−12" throws a IllegalArgumentException System. public class jtest { public static void main(String args[]) { try { GregorianCalendar gc = new GregorianCalendar(). gc. String format) { try { SimpleDateFormat sdf = new SimpleDateFormat(format).

0. The operation only affects the specified field while add() adjusts other Calendar fields.20).DAY_OF_WEEK).set(1997. roll() does the same thing except you specify if you want to roll up (add 1) or roll down (substract 1) to the specified Calendar field./javadetails/java−0101. 2.html add() and roll() are used to add or substract values to a Calendar object. You specify which Calendar field is to be affected by the operation (Calendar.out. 20).DATE ) */ 2. int day = newCal.text.DAY_OF_MONTH ) newCal. See the following example. simply use a negative argument.format(c1.get( Calendar.DAY_OF_WEEK_IN_MONTH ) newCal. To substract.get( Calendar.8 Add/Substract Day/Month/Year to a Date Current version of this HowTo : http://www.get( Calendar.DAY_OF_YEAR ) newCal. String DATE_FORMAT = "yyyy−MM−dd".7 Determine to day of the week Current version of this HowTo : http://www. /* also available : newCal.get( Calendar.println("Date + 20 days is : " + sdf. java. Calendar.setTime(newCal.rgagnon.get(Calendar.. roll() makes january rolls to december in the same 2.DAY_OF_WEEK ).7 Determine to day of the week .YEAR.html For the day of the week for today : GregorianCalendar newCal = new GregorianCalendar( ).com/javadetails/.getTime()). newCal.println("Date is : " + sdf. 0). c1.getInstance().format(c1. 1.set(1999. Calendar c1 = Calendar. System. Calendar. the next larger field is modified when the result makes the Calendar "rolls over".SimpleDateFormat sdf = new java. // BUG fix in Calendar class! newCal.rgagnon. 0 .SimpleDateFormat(DATE_FORMAT).out.DATE). 0.2.getTime())). int day = newCal.com/javadetails/.add(Calendar. // 1999 jan 20 System.MONTH./javadetails/java−0100. add() adds or substracts values to the specified Calendar field.DATE.text.. c1.getTime())). For the day of the week for any date : Calendar newCal = new GregorianCalendar().get( Calendar.

out. // roll down.get(GregorianCalendar. String mm = Integer. // 1998 dec 20 Thanks to P.format(c1. } 2.out.rgagnon. System.text. substract 1 month System.toString(d).out.MONTH.println ("Date minus 1 month : " + sdf./javadetails/java−0102.out.get(GregorianCalendar.getTime())). // 1999 jan 20 System.10 Simply format a date as "YYYYMMDD" Current version of this HowTo : http://www.DATE).YEAR) + (m < 10 ? "0" + mm : mm) + (d < 10 ? "0" + dd : dd).MONTH.println("Bad TimeZone from DateFormat : " + df.rgagnon.out. Calendar c1 = Calendar. −1). DateFormat df = DateFormat. c1.setCalendar(Calendar. public static String getStrDate(GregorianCalendar c) { int m = c. java.getTimeZone().html The format "YYYYMMDD" can be useful when sorting records or comparing 2 dates. // substract 1 month System. c1. 20).com/javadetails/. 2.roll(Calendar. String dd = Integer.format(c1.. false). 0 .println("Date is : " + sdf.getID()).9 Get the correct TimeZone on DateFormat . return "" + c.getTime())).format(c1. We must set the TimeZone manually. 0 .SimpleDateFormat sdf = new java.get(GregorianCalendar. System.println("Good TimeZone from Calendar : " + Calendar.9 Get the correct TimeZone on DateFormat Current version of this HowTo : http://www.println("Date is : " + sdf. // 1999 jan 20 System.. // fix the TimeZone df.getTimeZone().SimpleDateFormat(DATE_FORMAT).format(c1.getInstance()).println ("Date roll down 1 month : " + sdf./javadetails/java−0103.getTime())).html There is a bug in the DateFormat/SimpleDateFormat classes. int d = c.out.text.getID()). System.year while add() substract the YEAR field for the correct result. 2.com/javadetails/. // roll down the month c1. String DATE_FORMAT = "yyyy−MM−dd". 20).getTimeZone.set(1999.getInstance().getDateInstance().println("Good TimeZone from DateFormat : " + df.getID()).toString(m). Rehley for the bug fix.add(Calendar. // 1999 jan 20 c1.getInstance().out.set(1999.getTime())).MONTH) + 1.

import java.11 Compare 2 dates .SimpleDateFormat(DATE_FORMAT). SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT).com/javadetails/.Calendar.*.text.text. } } 2.out./javadetails/java−0105. System.getInstance().. public class TestDate { public static void main(String args[]){ String DATE_FORMAT = "yyyyMMdd".rgagnon. } } 2.html 2. import java. if (c1.getInstance().*. } if (c1.. 0 .getTime())).println(sdf. 11 .getTime())).com/javadetails/. // today System.12 Parse a String to obtain a Date/GregorianCalendar object Current version of this HowTo : http://www.print(" is before ").println("Today is " + sdf. import java.*..print(" same as "). Calendar c1 = Calendar.out.print(" is after ").after(c2)) { System. // remember months are zero−based : 0 jan 1 feb .out.text. } System.format(c2.SimpleDateFormat.11 Compare 2 dates Current version of this HowTo : http://www. public class TestDate { public static void main(String args[]){ String DATE_FORMAT = "yyyy−MM−dd". java.html import java.util.getTime())). c2.getInstance(). } if (c1.set(1999.out.out.set(1999.print(sdf.Thanks to Vladimir Garmaev for the bug fix Or you can use the SimpleDateFormat from the java.util. 31).rgagnon.text.util.format(c1. Calendar c2 = Calendar.SimpleDateFormat sdf = new java.format(c1.equals(c2)) { System./javadetails/java−0104.before(c2)) { System.. 30). Calendar c1 = Calendar.text package. c1. import java.out.

cal.html Since the granulaty of a PC can be as high as 55ms (down to 10ms). SimpleDateFormat sdf = new java.text.currentTimeMillis().Date. return cal. public class UniqueID { static long current= System. /* output : Timestamp : 24−Feb−1998 17:39:35 Calendar : 1998−02−24 17:39:35 */ } } 2.getInstance(). System.text. java. static public synchronized long get(){ return current++.println("Calendar : " + sdf.out.Locale.13 Use System time to generate unique ID Current version of this HowTo : http://www. Calendar cal = Calendar.SimpleDateFormat("yyyy−MM−dd HH:mm:ss").parse(timestamp). System. } public static void main (String a[]) throws Exception{ String timestampToParse = "24−Feb−1998 17:39:35". Locale.import import import import java.13 Use System time to generate unique ID .com/javadetails/. java. Date d = sdf. java.US since months are in english */ SimpleDateFormat sdf = new SimpleDateFormat ("dd−MMM−yyyy HH:mm:ss". public class DateUtils { public static Calendar parseTimestamp(String timestamp) throws Exception { /* ** we specify Locale. } } See also this HowTo 2.format(parseTimestamp(timestampToParse).getTime())).println("Timestamp : " + timestampToParse).SimpleDateFormat.rgagnon..Calendar.setTime(d)./javadetails/java−0385.util. you can't use the System time to generate a unique ID because of the risk of getting duplicated IDs.util.out.util.US). This can be solved by using the following technique to make sure that the number returned is unique (in a single JVM).

DateFormatSymbols.getWeekdays().rgagnon.text. import java.DateFormat. Calendar date2 = Calendar.getInstance().14 Get the day name Current version of this HowTo : http://www./javadetails/java−0413.2.format(d).html import java. Date date2 = new Date(). System. System.printStackTrace(). java.DateFormat.. java. System.OCTOBER.text.*.println("Today is a " + sayDayName(date2)).text. try { return f./javadetails/java−0403.out.text. } catch(Exception e) { e.com/javadetails/.14 Get the day name . public class GetDayName { public static void main(String[] args) { Date date1 = (new GregorianCalendar (1989.text. 17)).com/javadetails/.15 Find the current date format Current version of this HowTo : http://www.get(Calendar.out.out.text.println("Today is a " + dayNames[date2.rgagnon. return "".Calendar.*.util.SimpleDateFormat. } } 2.html import java.DAY_OF_WEEK)]).println ("1989−10−17 was a " + sayDayName(date1)). java. public class GetDayName { public static void main(String[] args) { String dayNames[] = new DateFormatSymbols(). } public static String sayDayName(Date d) { DateFormat f = new SimpleDateFormat("EEEE").. 2.util. } } } An alternate way : import import import import java.getTime(). Calendar. import java.SimpleDateFormat.

rgagnon. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 2. } } If you find this article useful.toPattern()).import java.. int day=ymd[2]. 2. * * ref : * Numerical Recipes in C. 3268 (3268−01−22 G). // jan=1. int month=ymd[1]. int julianYear = year.*.C.SHORT). 1582 (2299161) public static int JGREG= 15 + 31*(10+12*1582). System.util. julianMonth += 13.toPattern()). * Remember that the year after 1 B. Locale loc = Locale.D. Cambridge University Press 1992 */ // Gregorian Calendar adopted Oct.getDateInstance(DateFormat. negative year B.5.. df = (SimpleDateFormat) DateFormat.html A Julian date is the number of elapsed days since the beginning of a cycle of 7. The purpose of the system is to make it easy to compute an integer (whole number) difference between one calendar date and another calendar date. if (month > 2) { julianMonth++. 15.com/javadetails/. consider making a small donation to show your support for this Web site and its content.util.980 year cycle). int julianMonth = month.16 Get a julian date Current version of this HowTo : http://www. if (year < 0) julianYear++. public class Dtest { public static void main(String args[]) { SimpleDateFormat df = (SimpleDateFormat) DateFormat.D.println("The short date format is " + df..C.getDateInstance(DateFormat. 2nd ed.out. } else { julianYear−−. The starting point for the first Julian cycle began on January 1. feb=2. was 1 A..println("The short date format is " + df.Calendar.ITALY. public static double toJulian(int[] ymd) { int year=ymd[0].980 years invented by Joseph Scaliger in 1583.. Positive year signifies A./javadetails/java−0506.SHORT. loc). import java.16 Get a julian date . public static double HALFSECOND = 0. public class JulianDate { /** * Returns the Julian day number that begins at noon of * this day. nd will end on January 22.C.out. The following day will begin the first day of the second Julian date period (or 7. 4713 B.. System.

System.25) / 36524. System.out.YEAR). day}.out.year.. if (day + 31 * (month + 12 * year) >= JGREG) { // change over to Gregorian calendar int ja = (int)(0.0). } return java. 23 } )).0 + ((jb − 2439870) − 122..16 Get a julian date .println (". 1968 : " + toJulian( new int[] {1968.6001*julianMonth) + day + 1720995.lang. 5.Math.floor(30.DATE)}). back to calendar : " + results[0] + " " + results[1] + " " + results[2])..25 * julianYear) + java.1.get(Calendar. } jb = ja + 1524. month.je. System..floor(365. year = jc − 4715.get(Calendar. // output : 2440000 int results[] = fromJulian(toJulian(new int[] {1968. ja = ja + 1 + jalpha − jalpha / 4.1) / 365.get(Calendar.Math. jd = 365 * jc + jc / 4.println (". je = (int) ((jb − jd) / 30.day. 2nd ed. today.MONTH)+1. } /** * Converts a Julian day to a calendar date * ref : * Numerical Recipes in C.floor(julian).25 * ja). Cambridge University Press 1992 */ public static int[] fromJulian(double injulian) { int jalpha.println("Julian date for today : " + todayJulian)..out. ja = (int) injulian.out. if (month > 12) month = month − 12. double todayJulian = toJulian (new int[]{today. today. 5. // SECOND TEST today Calendar today = Calendar.6001).println("Julian date for May 23.getInstance().ja.25). jc = (int) (6680.} double julian = (java. results = fromJulian(todayJulian).25). return new int[] {year.lang. julian += 2 − ja + (0.month. 2.lang.6001 * je). // THIRD TEST double date1 = toJulian(new int[]{2005. month = je − 1. back to calendar : " + results[0] + " " + results[1] + " " + results[2]).jb. day = jb − jd − (int) (30. if (ja>= JGREG) { jalpha = (int) (((ja − 1867216) − 0. } public static void main(String args[]) { // FIRST TEST reference point System.jc. 23 })). if (month > 2) year−−. if (year <= 0) year−−.01 * julianYear).1}).jd.Math.0. double julian = injulian + HALFSECOND / 86400.

since 17−July is the 221th day of the year. } private static int age(int y. consider making a small donation to show your support for this Web site and its content. d). You can have the Modified Julian Date (JD) or the Truncated Julian Date (TJD).1.0 days */ } } There is a lot of variation around the idea of a "Julian date".out.get(Calendar.get(Calendar. many applications (especially mainframe systems) were storing dates in a format called "the Julian format"..17 Calculate the age Current version of this HowTo : http://www. 17−July−1998 is stored as 98221.get(Calendar... This format is a 5 digit number. months are 0−based : jan=0 feb=1 .get(Calendar. back to calendar 1968 5 23 Julian date for today : 2453487.get(Calendar.MONTH)) || (cal..println("Between 2005−01−01 and 2005−01−31 : " + (date2 − date1) + " days").get(Calendar. This format is not really useful since Y2K! The main reason for using the 5−digits Julian date was to save disk space and still have a format easy to use to handle dates.util. System.11)).YEAR). int m. m.. consisting of a 2 digit year and a 3 digit day−of−year number.get(Calendar. Calendar now = new GregorianCalendar(). import java.util. For example.0 .31}). if((cal.. } return res.rgagnon... /* expected output : Julian date for May 23.html import java.17 Calculate the age . If you find this article useful. System./javadetails/java−0547.MONTH) == now. System.out.. 2.com/javadetails/. The main difference is the starting for counting the days. public class CalcAge { public static void main(String [] args) { // remember .YEAR) − cal.3)).GregorianCalendar.MONTH) > now.DAY_OF_MONTH) > now. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 2.Calendar. Before Y2K.println ("1999−12−03 : " + age(1999.MONTH) &cal.11. int res = now. int d) { Calendar cal = new GregorianCalendar(y. back to calendar 2005 4 26 Between 2005−01−01 and 2005−01−31 : 30.10.0 . 1968 : 2440000.println ("1962−11−11 : " + age(1962.out.get(Calendar.DAY_OF_MONTH))) { res−−.double date2 = toJulian(new int[]{2005.

". <y> minutes and (z) seconds" */ public static String millisecondToDHMS(long duration) { String res = "". if (temp > 1) { res += "s". if (temp > 0) { res += temp + " minute".18 Format a duration in ms into a string as "Days. long temp = 0. if (temp > 0) { res = temp + " day". ONE_MINUTE * 60. 2. private TimeUtils() { } /** * converts time (in milliseconds) to * "<w> days. if (temp > 1) { res += "s". } duration −= temp * ONE_MINUTE. ONE_HOUR * 24. } } temp = duration / ONE_MINUTE.minutes and seconds" Current version of this HowTo : http://www. if (duration >= ONE_SECOND) { temp = duration / ONE_DAY../javadetails/java−0585.Hours. } } temp = duration / ONE_HOUR. } duration −= temp * ONE_DAY. if (temp > 0) { res += temp + " hour". } duration −= temp * ONE_HOUR.html public class TimeUtils { public public public public final final final final static static static static long long long long ONE_SECOND ONE_MINUTE ONE_HOUR ONE_DAY = = = = 1000. ". ONE_SECOND * 60.minutes and seconds" . if (temp > 1) { res += "s".com/javadetails/. if (duration >= ONE_MINUTE) { res += ". if (duration >= ONE_MINUTE) { res += ".Hours.rgagnon.18 Format a duration in ms into a string as "Days. <x> hours.} } 2.

html We connect to a publicly accessible time server on the internet and parse the result.gov/service/time−servers. 1 hour 1 day.*.util. 1 hour. System.*. Systems that exceed this rate will be refused service.text. In extreme cases. java. 4 hours. List of available time servers : http://tf.*.println(millisecondToDHMS ((5*ONE_DAY) + (4*ONE_HOUR) + ONE_MINUTE + (2 * ONE_SECOND) + 123)). System. } else { return "0 second". java.19 Get the atomic time .19 Get the atomic time Current version of this HowTo : http://www.println(millisecondToDHMS((5* ONE_SECOND) + 123)). 2 minutes 4 days./javadetails/java−0589. systems that exceed this limit may be considered as attempting a denial−of−service attack.out.println(millisecondToDHMS(ONE_DAY + ONE_HOUR)). 3 hours..out. } } return res.net. java. 2 minutes and 1 second 5 days. import import import import java.out. System.println(millisecondToDHMS (ONE_DAY + ONE_HOUR + (2 * ONE_MINUTE))). } } public static void main (String args []) { System. System. if (temp > 0) { res += temp + " second".println(millisecondToDHMS(123)). if (temp > 1) { res += "s".html NOTE : All users should ensure that their software NEVER queries a server more frequently than once every 4 seconds.println(millisecondToDHMS ((4*ONE_DAY) + (3*ONE_HOUR) + (2 * ONE_MINUTE) + ONE_SECOND)).out.rgagnon.com/javadetails/. System.out. /* output : 0 second 5 seconds 1 day.nist.io.*. } } temp = duration / ONE_SECOND. 2. 1 minute and 2 seconds */ } } 2.if(duration >= ONE_SECOND) { res += " and ".out.

String[] date = fields[1].set(Calendar. Integer.format(DateUtils.getInputStream())).getRawOffset() + tz. String[] time = fields[2].getDSTSavings()) / 3600000. String[] fields = atomicTime. } } } public static void main(String args[]) throws IOException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy−MM−dd HH:mm:ss"). calendar. in = new BufferedReader (new InputStreamReader(conn.set(Calendar. } finally { if (in != null) { in.out.close().set(Calendar. System.4.set(Calendar.parseInt(date[2])).parseInt(time[2])). Colorado (time−a.bldrdoc. } /* ref : http://www.bldrdoc. public final static GregorianCalendar getAtomicTime() throws IOException{ BufferedReader in = null.19 Get the atomic time .6.out.split("−").YEAR.SECOND. calendar.HOUR_OF_DAY.println("Atomic time : " + sdf.28:13".gov/doc−tour/atomic_clock.indexOf("*") > −1) { break. Integer. calendar.parseInt(date[1])−1). // NIST. String atomicTime. calendar. calendar. Integer.set(Calendar.html 49825 95−04−18 22:24:11 50 0 0 50. 2000 + Integer.set(Calendar.15. try { URLConnection conn = new URL(ATOMICTIME_SERVER).gov) public static final String ATOMICTIME_SERVER="http://132.getTime())).public final class DateUtils { // NIST. Integer.timefreq.parseInt(time[0]) + gmt). Boulder. System.out. Maryland (time−a. Gaithersburg.0 UTC(NIST) * | | | | | | | | | 2. while (true) { if ( (atomicTime = in.parseInt(date[0])). return calendar.163.gov) // public static final String ATOMICTIME_SERVER="http://129.101:13".println("DEBUG : " + atomicTime).DATE. calendar. int gmt = (tz. } catch (IOException e){ throw e.parseInt(time[1])).getAtomicTime(). } } System.nist.MINUTE. // deals with the timezone and the daylight−saving−time TimeZone tz = TimeZone.split(":").split(" ").openConnection().readLine()).getDefault(). GregorianCalendar calendar = new GregorianCalendar(). Integer.MONTH.println("DEBUG : " + gmt).

*.DATE. Month and Day // thanks to TrueJavaProgrammer for the idea! | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | It's not possible to set your local computer clock in pure Java. 2. import java. sunday) // you will have to adjust this a bit if you want // sunday to be considered as the first day of the week. 1). The returned interval can be the previous week ou the previous month relative to the given reference date.20 Get a date interval .MONTH. −1). public class DateUtils { public enum IntervalType { private DateUtils() { } Month.Month) { // first date of the month startDate.clone()./javadetails/java−0611. // previous month startDate. import java. Calendar reference) { if (reference == null) { reference = Calendar. // previous month. −1).DAY_OF_WEEK).SUNDAY) { startDate.get(Calendar. if (type == IntervalType.rgagnon. while (dayOfWeek != Calendar. } Calendar startDate = (Calendar)reference.util.html This HowTo computes a date interval based on the current date or given reference date..These are the last + five digits of the Modified Julian Date Year.DATE.com/javadetails/..DATE. } else { // previous week by convention (monday .DATE.add(Calendar.set(Calendar.clone().set(Calendar. Calendar endDate = (Calendar)reference. 1). You need to use an external utility provided by the OS or call a JNI routine. // first date of the month endDate.20 Get a date interval Current version of this HowTo : http://www. 2.add(Calendar.*. last date endDate.text.add(Calendar..getInstance(). Week } public static Calendar[] getDateIntervals(IntervalType type. // start date : decrement until first sunday then // down to monday int dayOfWeek = startDate. see this HowTo. −1).

System.get(Calendar. } catch (Exception e) { e. System. decrement until the first sunday dayOfWeek = endDate.getDateIntervals(IntervalType. while (dayOfWeek != Calendar.getDateIntervals(IntervalType. −1). } public static void main(String[] args) { try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy−MM−dd").format(results[0]. results = DateUtils. System.getTime())).getDateIntervals(IntervalType.out. −1).out. 1)).DAY_OF_WEEK). dayOfWeek = startDate.getTime())). dayOfWeek = endDate. } } return new Calendar[] { startDate.get(Calendar.DAY_OF_WEEK). System.Week.getTime())). System. System. 2007) 2.format(results[1]. System.Month. System. System. new GregorianCalendar(2007.println(sdf.println("** previous week (relative jan 1.out. 2007) week (relative jan 1.SUNDAY) { endDate.format(results[1].dayOfWeek = startDate. System.println("** previous week (relative today)").add(Calendar.getTime())).out.DATE. 00.get(Calendar.println("** previous month (relative jan 1.println(sdf.println(sdf.out. null).out. null). 2007)"). 2007)").printStackTrace().println(sdf. } // end date .getTime())).out. 1)).format(results[0].getTime())).getTime())).DAY_OF_WEEK).format(results[1].getDateIntervals(IntervalType.println("** previous month (relative today)").out.println(sdf.DATE.MONDAY) { startDate. } } /* output : ** previous 2008−06−01 2008−06−30 ** previous 2008−06−30 2008−07−06 ** previous 2006−12−01 2006−12−31 ** previous 2006−12−25 2006−12−31 */ month (relative today) week (relative today) month (relative jan 1.out.Week. new GregorianCalendar(2007.getTime())).get(Calendar.println(sdf. 00. System. } while (dayOfWeek != Calendar. Calendar [] results = DateUtils.format(results[0].20 Get a date interval . results = DateUtils.format(results[1].DAY_OF_WEEK).println(sdf.format(results[0]. System.out.Month. endDate }.out.println(sdf.out.add(Calendar. results = DateUtils.

} /** * @param target hour to check * @param start interval start * @param end interval end * @return true true if the given hour is between */ public static boolean isHourInInterval(String target. } /** * @param start interval start * @param end interval end * @return true true if the current hour is between */ public static boolean isNowInInterval(String start. out. return hour.getTime()). System.compareTo(start) >= 0) && (target. 17:15 private static String HOUR_FORMAT = "HH:mm".Calendar. start.format(cal.getCurrentHour(). String hour = sdfHour./javadetails/java−0624.isHourInInterval (DateUtils. String end = "14:26". import java.getCurrentHour().println(now + " between " + start + "−" + end + "?").21 Determine if an hour is between an interval .html import java. 12:12 . String end) { return ((target. String end) { return DateUtils.} 2. out.getInstance(). end). public class DateUtils { // format 24hre ex.text.rgagnon. } private DateUtils() { } public static String getCurrentHour() { Calendar cal = Calendar.. String start. static { sdfHour = new SimpleDateFormat(HOUR_FORMAT).util. System.compareTo(end) <= 0)).start.21 Determine if an hour is between an interval Current version of this HowTo : http://www.com/javadetails/. String start = "14:00".end)). private static SimpleDateFormat sdfHour. } // TEST public static void main (String[] args) { String now = DateUtils.SimpleDateFormat.println(DateUtils.isHourInInterval(now. } } 2.

jobject obj.rgagnon. jshort hour.wHour = hour.html 2. the JNI function JNIEXPORT void JNICALL Java_JavaHowTo_setSystemTime (JNIEnv *env. SetLocalTime( } The Java JNI wrapper would be class JavaHowTo { public native void setSystemTime( short hour. minutes).setSystemTime(hour.22 Set the computer clock .. to use it public class JNIJavaHowTo { public static void main(String[] args) { short hour = 10.22 Set the computer clock Current version of this HowTo : http://www.html Define the following prototype in the header file JNIEXPORT void JNICALL Java_JavaHowTo_setSystemTime (JNIEnv *.rgagnon. // set the time at 10h21 jht.2.wMinute = minutes. } } And finally.loadLibrary("javahowto"). jshort minutes) { SYSTEMTIME st. jshort. } } 2. jshort). // this example will set the system at 10h21 using the Windows API // SetLocalTime.com/javadetails/. short minutes)./javadetails/java−0385.23 Use System time to generate unique ID Current version of this HowTo : http://www./javadetails/java−0285.. GetLocalTime( st. JavaHowTo jht = new JavaHowTo(). jobject.com/javadetails/. static { System. st. short minutes = 21.

you can't use the System time to generate a unique ID because of the risk of getting duplicated IDs.currentTimeMillis().22 Set the computer clock .com http://www.rgagnon. This can be solved by using the following technique to make sure that the number returned is unique (in a single JVM).com 2. public class UniqueID { static long current= System. } } See also this HowTo Written and compiled Réal Gagnon ©2007 real@rgagnon.Since the granulaty of a PC can be as high as 55ms (down to 10ms). static public synchronized long get(){ return current++.

awt.setBackground(new Color(0). import java. setLayout(new FlowLayout()).b3.*. new FlowLayout(). t1 = new TextField(8).p3. public class CardLayoutDemo extends Applet implements ActionListener{ Panel p1.applet.awt. 100.blue.100).2 Use The CardLayout manager Current version of this HowTo : http://www.b2.1 java−awt 3. Button b1. new FlowLayout().addItem("Option 1")./javadetails/java−0237. // the third Card p3 = new myPanel(new Color(0). // Main card (receive the other) p0 = new myPanel(new Color(0). 100). p1.add(t1).rgagnon.3 AWT 3.c2.addItem("Option A"). c2. Choice c1..100) . // The second Card p2 = new myPanel(new Color(0). c2. 100. 100.addItem("Option C"). import java.add(c1).black.*. new CardLayout(0. t2.white. Choice c1 = new Choice(). t1.addItem("Option B"). b4.p2. new FlowLayout().add(c2).0). p2. // Add cards 3 AWT .white).com/javadetails/. 100.red. TextField t1. p3. public void init() { // The first Card p1 = new myPanel(new Color(0). c2 = new Choice(). add(p0).event.addItem("Option 2"). 100). c1. c2. c1.html import java.*.p0.

"3rd card").getComponents(). } else if (e. break. LayoutManager la.length. p1).getSource() == b4) { // get the current card Component c[] = p0. } public Dimension getPreferredSize() { 3 AWT . myPanel(Color co.getSource() == b1) { //Show the first list ((CardLayout)p0.show(p0. int h. add(b2 = new Button("card 2")). setBackground(co). add(b4 = new Button("Which card is selected ?")). w = width. p3).add("3rd card". "2nd card").addActionListener(this). p0.add("First card". b1. int i = 0. setLayout(la). } else if (e. p2).p0.getSource() == b2) { //Show the second list ((CardLayout)p0. "First card").show(p0. int height){ super(). } else if (e. int width. add(t2 = new TextField(2)). p0. while (i < j) { if (c[i].add("2nd card".getLayout()). } else i ++. } } } } class myPanel extends Panel{ int w.addActionListener(this).show(p0. h = height.isVisible()) { t2. b4.getLayout()). int j = c. b2.h). add(b3 = new Button("card 3")). add(b1 = new Button("card 1")).setText("" + (i+1)).getLayout()). b3. } public Dimension getMinimumSize() { return new Dimension(w.addActionListener(this).addActionListener(this). } public void actionPerformed(ActionEvent e) { if (e.getSource() == b3) { //Show the third list ((CardLayout)p0.

rgagnon.util.return new Dimension(w.rgagnon.length &!comps[i]. 3.4 Use Popups Current version of this HowTo : http://www.length) ? null : comps[i]. MouseListener { Hashtable popupTable = new Hashtable(). consider making a small donation to show your support for this Web site and its content.class WIDTH=300 HEIGHT=300> </APPLET> /HMTL Try it here. import java..isVisible()) ++i. import java. } } <HTML> <TABLE><TR><TD> <APPLET CODE=CardLayoutDemo.com/javadetails/.3 Detect which card is visible with a CardLayout .awt. return (i == comps. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 3.html Component getComponentShowing(Container c) { Component[] comps = c.com/javadetails/.1] import java.*.addActionListener(this).event. m.Hashtable./javadetails/java−0423. item. public PopupTest() { /* ** regular menu */ Menu m = new Menu("file"). } If you find this article useful.*. public class PopupTest extends Frame implements ActionListener. while(i < comps. MenuItem item = new MenuItem("file−1")..3 Detect which card is visible with a CardLayout Current version of this HowTo : http://www.h).html [JDK1./javadetails/java−0238.getComponents().add(item). int i = 0. item = new MenuItem("file−2"). 3.awt.

println(" command=" + e.m. } public void actionPerformed(ActionEvent e) { /* ** handle actions related to popup */ System.out.out. setMenuBar(mb). 100).getActionCommand()). mb.println(" param=" + e.red). add(l. "North"). addPopup(p. /* ** label with a popup */ Label l = new Label("label"). addPopup(l. } 3.3 Detect which card is visible with a CardLayout . add(p. /* ** button with popup */ Button b = new Button("button"). addPopup(b. "Center"). /* ** panel with popup */ Panel p = new Panel(). System.getSource()).out.add(item). System. MenuBar mb = new MenuBar().exit(0).paramString()). p. setLayout(new BorderLayout()).add(m). } public void mouseClicked (MouseEvent e) { } public void mouseEntered (MouseEvent e) { } public void mouseExited (MouseEvent e) { } public void mousePressed (MouseEvent e) { mouseAction(e). event=" + e ).println(" source=" + e. } } ). } public void mouseReleased (MouseEvent e) { mouseAction(e). "Panel"). addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { System. "label"). add(b.setBackground(new Color(0). "button"). "South").out. setVisible(true). System. setSize(100.println("actionPerformed.

} void setHash(Component c.*.getSize().rgagnon. } public static void main (String argv[]) { new PopupTest().addMouseListener(this).addActionListener(this). } } /* ** */ initialize a Popup for a particular Component void addPopup(Component c. } PopupMenu getHash(Component c) { /* ** return a Popup associated with a particular Component */ return (PopupMenu)(popupTable.height/2).awt.add(pm).put(c.com/javadetails/.add(mi1). } } 3./javadetails/java−0247. We must use the setFile method instead to set a filter. c. MenuItem mi1 = new MenuItem(name + "−1").isPopupTrigger()) { PopupMenu pm = getHash(c). p). String name) { PopupMenu pm = new PopupMenu(). mi1.get(c)).html On the Win platform. c. PopupMenu p) { /* ** associate a Component with a particular Popup */ popupTable. pm. if (e.width/2. MenuItem mi2 = new MenuItem(name + "−2").5 Use a File Dialog . mi2. setHash(c. pm.show(c.getSize(). pm.. import java.5 Use a File Dialog Current version of this HowTo : http://www.add(mi2). c. pm). c.void mouseAction (MouseEvent e) { /* ** determine if we have to show a Popup */ Component c = e. public class UseFileDialog { 3.addActionListener(this). the setFilenameFilter method don't work.getComponent().

3. return fd.4] The names of the most common fonts supported by Java are TimesRoman.rgagnon. return fd. String name){ return (name.. "*./javadetails/java−0270. then you simply do : fd. setFilenameFilter may do the job.getProperty("file.setDirectory(defDir).. } public String saveFile (Frame f. fd.setLocation(50.exit(0).setDirectory(defDir).out. System. FileDialog.endsWith(". "Open. title.setFilenameFilter(new FilenameFilter(){ public boolean accept(File dir. } }).out.html [JDK1. On other plateforms.show().endsWith(". fd.gif")). String title.com/javadetails/. 50). Courier.getFile().SAVE).. fd.setFile(fileType). String defDir. fd.". fd.".getFile()..6 Use TrueType font .setFile(fileType). fd. } } to work with the full pathname. String fileType) { FileDialog fd = new FileDialog(f.jpg") || name. 3. String title.6 Use TrueType font Current version of this HowTo : http://www.\\". "Save.setLocation(50. and Helvetica.getFile().saveFile(new Frame(). String fileType) { FileDialog fd = new FileDialog(f. by return fd. } public static void main(String s[]) { UseFileDialog ufd = new UseFileDialog(). System.java")). FileDialog.getDirectory() + System.\\". ". String defDir.println ("Saving : " + ufd.loadFile(new Frame().separator") + fd. "*. fd.public String loadFile (Frame f. ".println ("Loading : " + ufd. title.java")). 50). fd. System.LOAD).show(). replace return fd.getFile()..

getDefaultToolkit().5] @todo 3. i < j . I add the following line in the properties. To be able to use this font.getAvailableFontFamilyNames(). NOTE: The three common fonts are the only ones guaranteed to be supported across all systems.i++ ) { System. in a java program : setFont(new Font("Kaufmann". I have a font called Kaufmann.getLocalGraphicsEnvironment().2] import java. } } } [JDK1.To add fonts. public class FontList { public static void main(String args[]) { GraphicsEnvironment ge = GraphicsEnvironment. for (int i = 0 . you must modify the properties.BOLD. On a Windows system.awt.7 Display available fonts Current version of this HowTo : http://www.com/javadetails/. Font.i++ ) { System. Choose a font and doubleclick on it. [JDK1. i < j .getFontList(). go in the Font applet in the Parameters folder./javadetails/java−0278. public class FontList { public static void main(String args[]) { String[] fontNames = Toolkit. the real name is "Kaufmann BT".html [JDK1.out.out.font file and these new fonts are not cross−plateform compatibles.println(fontNames[i]). int j = fontNames. String fontNames[] = ge.font file located in the lib of your JDK installation. 20)).0=Kaufmann BT.7 Display available fonts . ANSI_CHARSET To use it.awt.*. simply edit the properties.1] import java. to check what are the fonts available. } } } 3. int j = fontNames. For example. for (int i = 0 . To be able to use other fonts.font file in the section called # for backword compatibility.rgagnon.println(fontNames[i]).. Kaufmann.*. Check the name of the font. on my system.length.length.

g.setSize(600. 102.255.html import java. f.3.10). 100).awt. // white } public void paint(Graphics g) { g.0)). g.8 Font with 3D effect Current version of this HowTo : http://www.setColor(getBackground()).0.awt.0)). 101. 201). } 3. g. 100. jc. import java.com/javadetails/.drawString("Real's HowTo". public class Java2Clipboard implements ClipboardOwner { public static void main(String[] args) throws Exception { Java2Clipboard jc = new Java2Clipboard().setColor(getBackground()).*. // black g.8 Font with 3D effect .class WIDTH=410 HEIGHT=500> </APPLET> </HMTL> try it here 3. public class SimpleApplet extends Applet { public void init() { setBackground(new Color(255.drawString("Real's HowTo".PLAIN.drawString("Real's HowTo".rgagnon. f.datatransfer.setFont(new Font("Helvetica". Font. 100. 42)). } } <HTML> <TABLE><TR><TD> <APPLET CODE=SimpleApplet.0.show(). 100).setColor(new Color(0.*.rgagnon.9 Use the System Clipboard Current version of this HowTo : http://www. import java.drawString("Real's HowTo".drawString("Real's HowTo". 100./javadetails/java−0382.*. 202).0.toClipboard().drawString("Real's HowTo". Frame f = new Frame ("Open a text editor and paste the message from Java")..applet.html import java.setColor(new Color(0. g. 101). g.awt.*.. // black g.setColor(new Color(0. g./javadetails/java−0312.255)). g. 200). // blue g. g.255)). 101.com/javadetails/.

checkSystemClipboardAccess(). setState()..GetDefaultToolkit()..*.10 Maximize a Frame Current version of this HowTo : http://www.4).awt./javadetails/java−0222.println("Full screen not supported"). 3. cp.out. device = GraphicsEnvironment. after the show() this. } } NOTE: You can only use text (no graphic) with this functionality provided by the current JDK (1.setContents(st.ICONIFIED).html // place this in the Frame constructor. JDK1.getScreenSize()). if ( device. In this mode you can change the resolution import java. Transferable tr) { System.4 import java.awt. . if (sm != null) { try { sm.move(0.printStackTrace().2 offers a new method.} } Toolkit tk = Toolkit. GraphicsDevice device.getSystemClipboard(). JDK1.println("Lost Clipboard Ownership?!?"). getDefaultScreenDevice().getSecurityManager().err. // minimize the frame Latest JDK provides more ways to do that. } else { System. Frame frame = new Frame(). 3. getLocalGraphicsEnvironment().rgagnon. StringSelection st = new StringSelection("Hello world from Java").10 Maximize a Frame .. resize(Toolkit.setState(Frame.isFullScreenSupported() ) { device. } public void lostOwnership(Clipboard clip.public void toClipboard() { SecurityManager sm = System. this).com/javadetails/. Clipboard cp = tk.setFullScreenWindow(frame). } catch (Exception e) {e. } The "full−screen" Frame is in exclusive mode.*. to minimize or maximize a Frame.getDefaultToolkit().0). frame.

doit(). To remove (manually) the "exclusive mode" on the JFrame : device.setFullScreenWindow(null).setExtendedState(Frame.err. super.REFRESH_RATE_UNKNOWN )). GraphicsDevice device. the original resolution is restored. // frame.com/javadetails/.class ScreenRes { public static void main(String args[]) { new ScreenRes(). } } } When the JFrame is destroyed.setDisplayMode( new DisplayMode( 1024.isDisplayChangeSupported()) { device. 3.1] // (put that in the Frame/Dialog class) public void centerScreen() { Dimension dim = getToolkit().width − abounds.. } } else { System. device = GraphicsEnvironment.html // centers the dialog within the screen [1.11 Center a Frame/Dialog Current version of this HowTo : http://www. 8. getDefaultScreenDevice().isFullScreenSupported() ) { device. Rectangle abounds = getBounds().setFullScreenWindow(frame).MAXIMIZED_HORIZ).width) / 2./javadetails/java−0223.MAXIMIZED_BOTH). if (device.height) / 2). // bitDepth − 8 bits 256 colors DisplayMode.println("Full screen not supported"). getLocalGraphicsEnvironment(). 3.3 JFrame frame = new JFrame().height − abounds.getScreenSize(). } else { System. // can be // frame. if ( device.MAXIMIZED_VERT). setLocation((dim.setVsible(true).err.setExtendedState(Frame. } public void doit() { Frame frame = new Frame().println("Change display mode not supported").rgagnon. (dim. frame. 768. SWING jdk1.11 Center a Frame/Dialog .setExtendedState(Frame.

100).y.setVsible(true).x. return true. For a JWindow or a JFrame with no parent.exit(0). setLocation (x. } return super. if (parentSize.1 Method 1] public aFrame extends Frame implements WindowListener { public aFrame(){ addWindowListener( this ).x.0.setSize(100. // Find out our parent Container myParent = getParent().rgagnon.id == Event.com/javadetails/. if (parentSize.12 Close a Frame Current version of this HowTo : http://www. else y = topLeft.y.height > mySize. else x = topLeft.WINDOW_DESTROY) { System.setLocationRelativeTo(NULL).width)/2) + topLeft. then f.getSize().4.12 Close a Frame .. Dimension parentSize = myParent.height − mySize. y). } // centers the dialog within the parent container [1.height)/2) + topLeft./javadetails/java−0225. } 3.width) x = ((parentSize.html [JDK1.getLocationOnScreen().requestFocus(). requestFocus().1] // (put that in the Dialog class) public void centerParent () { int x. Point topLeft = myParent.width − mySize. f. } [JDK1.height) y = ((parentSize. int y.2] public boolean handleEvent(Event evt) { if (evt.width > mySize. super. JDialog has method to position a JDialog relative to a parent. 3.handleEvent(evt). } New with JDK1. Dimension mySize = getSize().

} } [JDK1.dispose(). class SimplePopUp extends Dialog { SimplePopUp() { super(new Frame().exit(0) may not be appropriate. a System. } } )./javadetails/java−0268. } } For a Dialog or a Window.1 Method 2] public class aFrame extends Frame { public aFrame(){ addWindowListener( new Terminate() ).1 Method 3] public class aFrame extends Frame { public aFrame() { addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { System.html 3. this. } 3.exit(0).public public public public public public public } void void void void void void void windowActivated(WindowEvent e){} windowDeactivated(WindowEvent e){} windowOpened(WindowEvent e){} windowClosing(WindowEvent e){ System.rgagnon.13 Call events on a Frame from a Panel . "simple popup").getWindow(). } } class Terminate extends WindowAdapter{ public void windowClosing(WindowEvent e){ System. } } ).exit(0).13 Call events on a Frame from a Panel Current version of this HowTo : http://www.addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { e.exit(0).com/javadetails/. } windowClosed(WindowEvent e){} windowIconified(WindowEvent e) {} windowDeiconified(WindowEvent e) {} [JDK1.. call the dispose() method instead.

setSize(400.awt.*. The first button on the Panel will generate an event for the button on the Frame while the second panel button will trigger a request to close the Frame and the application.awt. b1 = new Button("A dummy button").event. a Frame contains 1 button and a Panel with 2 buttons on it.13 Call events on a Frame from a Panel . } 3.getScreenSize().addActionListener(this).black). setLayout(new FlowLayout()).A component on a Panel can easily call events on the parent Frame.d. add(b1).java] import java.awt. TestEventPanel(){ super(). This way. p1 = new TestEventPanel(). b2 = new Button("close the parent frame"). TestEventFrame(String title){ super(title).height/3). add(b1). p1. [TestEventFrame. we can put all the logic in one place. add(b2). Button b1.b2. [TestEventPanel. setVisible(true).*. createFrame().awt.width/4. In this example.100).event. WindowListener { TestEventPanel p1. public class TestEventFrame extends Frame implements ActionListener. // the Panel with 2 buttons on it add(p1). setLayout(new FlowLayout()).*. p1. setLocation(d. addWindowListener(this).b2. import java. setBackground(new Color(0). will act as an ActionListener for events for the 2 Panel buttons. } } The Frame after adding the Panel.addActionListener(this).*.addActionListener(this).java] import java. } void createFrame() { Dimension d = getToolkit(). b1 = new Button("call event on the frame"). import java.b1. public class TestEventPanel extends Panel { Button b1. // add the actionlistener b1.

getSource()==b1) { System.html There is a bug in JDK1.java] import java.awt.14 Set the small top−left icon on a Frame Current version of this HowTo : http://www. } if (ae.b1) { System.0.applet.getActionCommand()).getSource()==p1. public class Java0268 extends java.2 for Windows.b2) { System..out. so you are stuck with the JAVA coffee cup.println("dummy receive :" + ae.dispose().dispatchEvent (new_ae). b1. ActionEvent new_ae = new ActionEvent (b1. System.println(ae.Applet { TestEventFrame myTestEventFrame.exit(0). } public void windowActivated(WindowEvent e) { public void windowDeactivated(WindowEvent e) public void windowDeiconified(WindowEvent e) public void windowClosed(WindowEvent e) { } public void windowIconified(WindowEvent e) { public void windowOpened(WindowEvent e) { } } } { } { } } and finally [Java0268.println(ae.ACTION_PERFORMED. WindowEvent.out. } } Try it here. 3. ActionEvent.rgagnon.out.getSource()==p1./javadetails/java−0246.com/javadetails/.public void actionPerformed(ActionEvent ae){ if (ae. 3.*. processEvent(new WindowEvent(this. } if (ae.getActionCommand()). } } public void windowClosing(WindowEvent e) { this.14 Set the small top−left icon on a Frame . "Panel b1 is calling the dummy button").WINDOW_CLOSING)).getActionCommand()). public void init() { myTestEventFrame = new TestEventFrame("TestEvent Frame").

you can use a PNG or JPG file. } } class MyFrame extends Frame { public MyFrame(String title){ super(title).theFrame = new MyFrame("A Dummy Frame"). t.awt. You have to use a GIF file (not ICO file!).*.png") ).In JDK1.gif"))). import java.class.getImage(getClass().html import java..setVisible(true).5.getResource("logo.event. do : frame. // no minimize or maximize this. public class TestNoMaximize { MyFrame theFrame.15 Prevent a Frame to be resized . } } ).*. this is fixed. getResource("images/myIcon. 3.exit(0).setIconImage(Toolkit.setSize(200. } public void paint(Graphics g) { 3. public static void main (String args[]){ TestNoMaximize t = new TestNoMaximize().getDefaultToolkit().getDefaultToolkit() . this.15 Prevent a Frame to be resized Current version of this HowTo : http://www.setResizable(false). You set the icon with : frame. With 1.setIconImage (Toolkit.1.com/javadetails/.getImage() ). or frame.getImage("myIcon.theFrame. addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { System. To get the image from a Jar instead./javadetails/java−0252.rgagnon.gif")). The GIF dimension should be 16x16.200).awt. t.setIconImage( new ImageIcon( YourApp.

. The result is not too good with Label. } } class MyFrame extends Frame { public MyFrame(String title){ super(title)..exit(0).awt.awt./javadetails/java−0302.200). addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { System. It's a feature. 50. } } ). } public void paint(Graphics g) { Dimension d = this.setVisible(true). { 3.g. t.theFrame = new MyFrame("A Dummy Frame"). } } NOTE: These How−to may not work with the Microsoft JVM.event. 3. if (d.event.".html A given image is tiled as the frame background. 50. 50).16 Embed an image into a Frame . import java.200).*.com/javadetails/.".awt. 50). public static void main (String args[]){ TestNoMaximize t = new TestNoMaximize(). g.getSize().drawString("try to maximize me.getWidth() != 200) this.getHeight() != 200 &d..*.drawString("try to resize me. public class TestNoMaximize { MyFrame theFrame..rgagnon. import java.. public class ImageFrame extends Frame private Image image. import java. this.16 Embed an image into a Frame Current version of this HowTo : http://www.awt.setSize(200..*...theFrame.*. t. import java.setSize(200.. } } There is no way to allow minimizing but not maximizing unless you trap the maximizing in the paint method and then resize to the original size.

} } ). change the method to retrieve the image // and of course use your own image! image = Toolkit. // for Applet.println("Bye.addImage(image.16 Embed an image into a Frame . } } static public void main(String[] args) { ImageFrame iframe = new ImageFrame(). } } 3.setVisible(true)."). } y = y + image. getSize().ImageFrame() { super("").20))... } public void paint(Graphics g) { if(image != null) { int x = 0.width) { g.getDefaultToolkit(). } catch (Exception e) { e. x= x + image. while(x< getSize(). 0. 500). add(new Button("hello")). add(new Label("Hello")).height). try { MediaTracker mt = new MediaTracker (this). y = 0.getImage("images/jht. getSize(). mt. while(y < getSize(). iframe. x.out. mt. this).waitForID(0).getWidth(null). add(new TextArea(20.printStackTrace(). } setLayout(new FlowLayout()).width.height) { x = 0. } } else { g. addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { // change this for an Applet System. System. setSize(500. // Label may not look too good . y.drawImage(image. add(new List(20)). 0). } public void update( Graphics g) { paint(g).gif").exit(0).clearRect(0.getHeight(null). add(new TextField(10)).

/* * @param frame parent frame * @param msg message to be displayed * @param okcan true : ok cancel buttons. this simple class can be used as a Message Box. With plain AWT. boolean okcan){ super(frame. addOKCancelPanel(okcan).html If using Swing then look at the JOptionPane component.awt. createFrame(). String msg){ 3.17 Display a message box Current version of this HowTo : http://www. public boolean isOk = false.can.*. public class MsgBox extends Dialog implements ActionListener { private Button ok.event. false : ok button only */ MsgBox(Frame frame. setLayout(new BorderLayout()).. import java. setVisible(true).rgagnon.com/javadetails/.17 Display a message box .awt./javadetails/java−0242. add("Center".new Label(msg)). pack(). true). } MsgBox(Frame frame. import java. String msg. "Message".The result : 3.*.

msg. add("South".rgagnon.dispose().this(frame. true).d. "Hey you user.setSize(200. can.18 Display a Splash screen .200). f. createOKButton( p ).isOk) System.p). message. setLocation(d. setVisible(false). are you sure ?".println("Ok pressed").setLayout(new FlowLayout()). } void createOKButton(Panel p) { p.add(can = new Button("Cancel")).getScreenSize(). if (message.println("Cancel pressed"). } else if(ae. false).getSource() == ok) { isOk = true.html 3. } void addOKCancelPanel( boolean okcan ) { Panel p = new Panel(). } void createFrame() { Dimension d = getToolkit()./javadetails/java−0267. f. if (okcan == true) createCancelButton( p ).out. } void createCancelButton(Panel p) { p. } } public static void main(String args[]){ Frame f = new Frame().addActionListener(this).addActionListener(this).18 Display a Splash screen Current version of this HowTo : http://www. } } 3. if (!message.width/3.setVisible(true).isOk) System.out. MsgBox message = new MsgBox (f . p. ok.height/3).add(ok = new Button("OK")). } public void actionPerformed(ActionEvent ae){ if(ae..getSource() == can) { setVisible(false).com/javadetails/.

imgWidth. When the parent is activated. imgHeight. showSplashScreen(). } catch (Exception e) { e.*. setBackground(BORDERCOLOR). try { tracker. BORDERSIZE. } } } 3. imgHeight.width − w) /2.*. Image result.printStackTrace(). } public void showSplashScreen() { Dimension screenSize = tk. } public void paint(Graphics g) { g. setVisible(true).imgName = imgName. int w = imgWidth + (BORDERSIZE * 2).getScreenSize(). public Splash(Frame f.18 Display a Splash screen . this. private static final Color BORDERCOLOR = Color. String imgName) { super(f). tracker. dispose(). f. this).This Splash class display a window containing a specified image while a parent Frame is doing its initialization. h). splashImage = loadSplashImage().addWindowListener(new WindowListener()). } class WindowListener extends WindowAdapter { // was windowActivated.event. thanks to H. private int imgWidth. result = tk. w.getWidth(this).drawImage(splashImage. private String imgName. int x = (screenSize.Grippa for the fix! public void windowOpened(WindowEvent we) { setVisible(false). imgHeight = result. setBounds(x.waitForAll(). } public Image loadSplashImage() { MediaTracker tracker = new MediaTracker(this).addImage(result. } imgWidth = result. import java.awt. int y = (screenSize. private static final int BORDERSIZE = 5. tk = Toolkit.1] import java.blue. the Splash window is destroyed.getDefaultToolkit(). BORDERSIZE. return (result). Toolkit tk.awt. [JDK1. public class Splash extends Window { private Image splashImage. int h = imgHeight + (BORDERSIZE * 2).getHeight(this).height − h) /2. y. 0).getImage(imgName).

private final static int VIBRATION_VELOCITY = 5. } } ).awt. (jht.html This HowTo is based on this post : http://sdnshare. } } class MyFrame extends Frame { Splash mySplash.rgagnon. i++) { System. import java.gif) as the splash image.gif"). } } 3.com/javadetails/. t.println(i) . "jht. theFrame. i < 3000. import java. public class FrameUtils { private final static int VIBRATION_LENGTH = 20. public class TestSplash { MyFrame theFrame.200).event. } setSize(200.out. addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { System. mySplash = new Splash(this..setVisible(true).jsp?id=2326 This can be useful to make a visual effect when an event is occuring.*.19 Vibrate a Window Current version of this HowTo : http://www.*.com/view.*. // dummy delay so we can see the Splash! for(int i = 0.exit(0). public MyFrame(String title){ super(title)./javadetails/java−0622.awt.createMainFrame().sun.The following example use this image import java. private FrameUtils() { } 3. } private void createMainFrame() { theFrame = new MyFrame("A Dummy Frame"). public static void main (String args[]){ TestSplash t = new TestSplash().19 Vibrate a Window .awt.

setLocation(originalX. import java.getLocationOnScreen().*. you need the DirWatcher and DirFilterWatcher classes). setSize(600. public class DirWatchWindow extends Frame { Label folder. setVisible(true). originalY − VIBRATION_VELOCITY).awt. for(int i = 0. add(folder.NORTH). info = new Label(""). frame. BorderLayout. simply pass a Frame to the vibrate method. you change the method signature for a JFrame instead. Thread. originalY). add(info. setLayout(new BorderLayout()). We display a small window.sleep(10). 3.getLocationOnScreen().awt.*. Plus the following classes. folder = new Label(""). frame. import java. First get the code to detect a file modfication in a folder (in this HowTo.setLocation(originalX.sleep(10). originalY + VIBRATION_VELOCITY).SOUTH).19 Vibrate a Window .event. final int originalY = frame.y. public DirWatchWindow() { setTitle("DirWatchWindow"). originalY). addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { System. the window is shaking for a brief moment and display the event.public static void vibrate(Frame frame) { try { final int originalX = frame. Thread. Thread. BorderLayout. } } } To use it.exit(0). Label info. FrameUtils. } } catch (Exception err) { err.vibrate(myFrame).setLocation(originalX + VIBRATION_VELOCITY. the folder c:/temp is used but you can specify another one on the command line. Here an example. frame. When a file is added or deleted. By default. i < VIBRATION_LENGTH.x. } } ). 100).sleep(10).sleep(10). frame. i++) { Thread.setLocation(originalX.printStackTrace(). To make it more Swing−oriented.

} }.html 3.io.*. 1000 ).jar c:/myfolder to specify your own folder.20 Limit TextField input to numeric value Current version of this HowTo : http://www.com/javadetails/.length > 0) { folderToWatch = args[0].getName() +" action: " + action).20 Limit TextField input to numeric value .} public void setInfo(String text) { info. public class DirWatchTest { public static void main(String args[]) { String folderToWatch = "c:/temp".setFolder(folderToWatch).rgagnon. FrameUtils. new Date(). TimerTask task = new DirWatcher(folderToWatch.. } public void setFolder(String dir) { folder. } } You can download an executable JAR here To launch the demo java −jar DirWatch. This demo is watching for files with the extension txt only. } } import java. if (args./javadetails/java−0226. } final DirWatchWindow dww = new DirWatchWindow(). 3. Timer timer = new Timer().setText("Watching folder : " + dir).util.setText(text). timer. dww. import java.jar to watch the default directory c:/temp or java −jar DirWatch.*.schedule( task . "txt" ) { protected void onChange( File file.setInfo("File : "+ file. String action ) { // here we code the action on a change dww.vibrate(dww).

consume() .id == Event.KEY_PRESS) { char c = (char)event.VK_ENTER) || (c == KeyEvent.KeyAdapter .awt. } } [JDK1.1] thanks to Lionel Giltay import java.applet. } else { // discard Character return true.awt. } } }).key.*. 3. } else if (Character.awt.isDigit(c)))) { e.2] // You still have to trap the InvalidNumberFormat // Exception when converting textfield content to numeric // bug fixed! 980211 thanks to JM Guerra Chapa import java.isISOControl(c)) { // keep control character (like del. add(textField1).Applet { TextField textField1. if (! ((c==KeyEvent.VK_TAB) || (Character. public void init() { setLayout(new FlowLayout()). bksp) return super.20 Limit TextField input to numeric value .event.event. } public boolean handleEvent(Event event) { if (event.handleEvent(event).handleEvent(event).VK_DELETE) || (c== KeyEvent. public class app extends java.awt. if (c >= '0' &c <= '9') { // keep digit return super. } } return super. import java. this.addKeyListener(new KeyAdapter() { public void keyTyped (KeyEvent e) { char c = e.0.TextField . import java. int _col) { super (_initialStr.handleEvent(event). _col) .VK_BACK_SPACE) || (c==KeyEvent.[JDK1. textField1 = new TextField(10).KeyEvent .target==textfield1 &event. public class NumericTextField extends TextField { public NumericTextField (String _initialStr.getKeyChar() .

addKeyListener(this).. } } } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { } } 3. } public void keyPressed(KeyEvent e) { char c = e.isActionKey()) return. else { e.awt. import java.*.rgagnon. _col) .21 Limit TextField input to a maximum length .21 Limit TextField input to a maximum length Current version of this HowTo : http://www.consume().event.VK_BACK_SPACE)|| (c==KeyEvent.VK_DELETE) || (c==KeyEvent. public class TextFieldWithLimit extends TextField implements KeyListener { private int maxLength. } public TextFieldWithLimit (int col.} public NumericTextField (int _col) { this ("".com/javadetails/.col).int col. } } If you find this article useful. if (len <maxLength) { return.VK_TAB)|| e.getKeyChar().VK_ENTER)|| (c==KeyEvent. consider making a small donation to show your support for this Web site and its content.length().*. public TextFieldWithLimit (String initialStr.col. } else { if((c==KeyEvent.int maxLength) { super(initialStr.awt. this. int len = getText().maxLength)./javadetails/java−0227.maxLength = maxLength.html [JDK11] import java. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 3.int maxLength) { this("".

getDefaultToolkit(). add(t).println("ENTER pressed").*.println("ENTER pressed").*. public void init(){ TextField t = new TextField("press ENTER"). import java.addKeyListener(this). } } } Or the short version using the KeyAdapter class.getDefaultToolkit().html import java. t.getKeyCode()./javadetails/java−0254./javadetails/java−0253.*.awt.beep(). public class testENTER extends Applet implements KeyListener { TextField t.awt.out.VK_ENTER) { Toolkit.html 3. import java.awt. import java. public void init(){ TextField t = new TextField("press ENTER").22 React to the ENTER key in a Textfield .22 React to the ENTER key in a Textfield Current version of this HowTo : http://www. add(t). if (key == KeyEvent.applet.3.getKeyCode().com/javadetails/.. t. if (key == KeyEvent. import java.*.23 Make the ENTER key act like the TAB key Current version of this HowTo : http://www.event.beep().rgagnon.com/javadetails/.applet.*.VK_ENTER) { Toolkit. System. System. } public void keyTyped(KeyEvent e) {} public void keyReleased(KeyEvent e) {} public void keyPressed(KeyEvent e) { int key = e. import java.out..addKeyListener (new KeyAdapter() { public void keyPressed(KeyEvent e) { int key = e.rgagnon.awt.*. } } } ).event. public class testENTER extends Applet{ TextField t. } } 3.

*. add(b = new Button("reset TextFields")).*./javadetails/java−0274.24 Reset all textfields in one shot Current version of this HowTo : http://www. public class MyTextField extends TextField { MyTextField(int len) { super(len). import java. addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evt) { int key = evt.add(t4onPanel). TextField t2.applet. import java. add(t1). 3.html import java.}}). TextField t4onPanel.event. t2.awt.event.yellow).*. Panel p1. public void init() { add(t1= new TextField(20)). try something like this import java..*. if (key == KeyEvent.awt.awt.*.com/javadetails/. public void init(){ MyTextField t1 = new MyTextField(10). p1.awt.getKeyCode().24 Reset all textfields in one shot . p1 = new Panel(). public class TestEnterAsTab extends Applet { MyTextField t1. public class FirstApplet extends Applet implements ActionListener { TextField t1. add(t2= new TextField(20)). import java. t4onPanel = new TextField(20).VK_ENTER) transferFocus(). MyTextField t2 = new MyTextField(10).awt.*.rgagnon.event. add(t3= new TextField(20)). TextField t3.First create a TextField that listen to the Enter and react like a Tab key [JDK11] import java. } } to use it.add(t2).*. Button b. add(p1). import java.setBackground(new Color(0). import java.awt. } } 3.applet. p1.*.

b. } public void actionPerformed(ActionEvent ae) { if (ae. else if (components[i] instanceof TextField) ((TextField) components[i]). } } ). addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System. pack().setModifiers(Event.*.com/javadetails/. add(tf). tf. TextField tf = new TextField(10). import java.isLetter(e.exit(0). for (int i = 0. i <components.getKeyChar())) e. } public UpperTF() { setLayout(new FlowLayout()). } }).getComponents().rgagnon.setVisible(true).*.getSource() == b) resetTextFields(this).25 Limit a TextField to Uppercase Current version of this HowTo : http://www.event.addActionListener(this). } 3.class" NAME="myApplet" HEIGHT=200 WIDTH=200> </APPLET></BODY></HTML> 3. } } } <HTML><HEAD></HEAD><BODY> <APPLET CODE="FirstApplet.awt.1] import java.html [JDK1.25 Limit a TextField to Uppercase . public class UpperTF extends Frame { public static void main(String argv[]) { new UpperTF()./javadetails/java−0279.awt. } public static void resetTextFields(Container c) { Component [] components = c.addKeyListener( new KeyAdapter() { public void keyPressed(KeyEvent e) { if (Character..setText("") .SHIFT_MASK).length. i++ ) { if (components[i] instanceof Container) resetTextFields((Container) components[i]) .

down=false. Also a method to disable the button by using a special filter is given.getImage(down). import java.com/javadetails/.h.java] import java. tracker = new MediaTracker(this).h). This ImageButton needs 2 GIF images representing the normal and pressed state ( ). URL down_b) { clicked=false.new ImageButtonDisableFilter())). boolean clicked.awt.event.200). Image DOWNimage. DOWNimage = getToolkit(). tracker. int w.1 and is a good example of the new Event architecture. w=UPimage.down_b).public Dimension getPreferredSize() { return new Dimension(200. public ImageButton(URL up_b. URL down) { MediaTracker tracker.addImage(DOWNimage./javadetails/java−0245.getImage(up).1). } } 3.printStackTrace().net.26 Have an ImageButton Current version of this HowTo : http://www. } public void InitImage(URL up. addMouseListener(new ImageButtonMouseListener()). Image UPimage.html This implementation of an ImageButton requires JDK1.addImage(UPimage. enabled=true.awt. [ImageButton. tracker.*.getWidth(this).waitForAll().0). try { UPimage = getToolkit(). setSize(w.*. Image disabledimage.image.26 Have an ImageButton .awt. tracker.*. boolean enabled. } disabledimage=createImage(new FilteredImageSource (UPimage.. 3. public class ImageButton extends Canvas { protected ActionListener actionListener = null. } catch (InterruptedException e) { e. import java. addMouseMotionListener(new ImageButtonMouseMotionListener()). import java.*.getSource().rgagnon. InitImage(up_b. boolean down.

if (actionListener != null) { actionListener.0.26 Have an ImageButton .x > 0)&&(p.0.0.0.x < w)&&(p. } public void addActionListener(ActionListener l) { actionListener = AWTEventMulticaster.drawImage(disabledimage. } else { g. l).this).remove(actionListener. repaint().x < w)&&(p.this). } public void removeActionListener(ActionListener l) { actionListener = AWTEventMulticaster. } public boolean isEnabled() { return (enabled). } } public class ImageButtonMouseMotionListener extends MouseMotionAdapter { public void mouseDragged(MouseEvent e) { 3.h=UPimage.y < h)&&(p.l).getPoint().y > 0)&&(enabled==true)) { clicked=true.add(actionListener.drawImage(DOWNimage.this).x > 0)&&(p. } public class ImageButtonMouseListener extends MouseAdapter { public void mousePressed(MouseEvent e) { Point p = e.getComponent().actionPerformed(ae). } } public void mouseReleased(MouseEvent e) { Point p = e.y > 0)&&(clicked==true)) { ActionEvent ae = new ActionEvent(e.getPoint(). if ((p.getHeight(this).0. } if ((p. } else { if (enabled) { g.0. down=true. repaint(). } } clicked=false. } } } public void setEnabled(boolean b) { enabled=b.drawImage(UPimage. } public void paint(Graphics g) { if (down) { g. if (down) { down=false. repaint().0."click").y < h)&&(p.

c. java. java.getHeight(this))).net.Point p = e. add(ib). UPimage.26 Have an ImageButton .*. } } } } public Dimension getPreferredSize() { return (new Dimension(UPimage. } 3.addActionListener(this). repaint().awt.printStackTrace(). } public int filterRGB(int x.awt.y < h)&&(p. repaint(). Checkbox c.getWidth(this). if ((p. } } else { if (down==true) { down=false. } public Dimension getMinimumSize() { return getPreferredSize(). "Gumbyblu. try { ib = new ImageButton (new URL(getCodeBase(). "Gumby.java] import import import import java.getPoint(). int y. } class ImageButtonDisableFilter extends RGBImageFilter { public ImageButtonDisableFilter() { canFilterIndexColorModel=true.addItemListener(this).gif"). ib.*.applet.event.x > 0)&&(p.gif")). new URL(getCodeBase(). add(c).x < w)&&(p. int rgb) { return (rgb &~0xff000000) | 0x80000000. c = new Checkbox("disable").*.ItemListener { ImageButton ib.*. public class TestImageButton extends Applet implements ActionListener. } } } [TestImageButton. } catch (Exception e) { e.y > 0)&&(clicked==true)) { if (down==false) { down=true. java. public void init() { setLayout(new FlowLayout()).

html The width can be specified via the preferredSize method. Font.com/javadetails/.com/javadetails/. cbg.html import java.setState( false ). import java. m. add(new Button("clear radio")). new Font("Courier".} public void actionPerformed(ActionEvent e) { if (e.*. } } 3./javadetails/java−0231.awt. return true. add(new Checkbox("American Express". This class lets you specify a font (fixed pitch) and calculate the appropriate width in pixels.. public void init() { add(new Label("Payment mode?")). cbg = new CheckboxGroup().27 Reset a checkbox group . false)).setEnabled(!ib. class myListbox extends List { int width. Object o) { if (o. boolean m){ // (r) line number. cbg. current. 3. } public boolean action(Event e. int height. cbg. add(new Checkbox("Mastercard".setCurrent( null ). (m) multiselect this(r. public myListbox(int r.out. false)). } return false. n.rgagnon. false)). true)). cbg. } } 3.. 10)).BOLD.getCurrent(). (n) width.isEnabled()).28 Set the listbox width Current version of this HowTo : http://www.*.equals("clear radio")){ Checkbox current = cbg. cbg.27 Reset a checkbox group Current version of this HowTo : http://www.println("Click ImageButton"). public class radio extends Applet { CheckboxGroup cbg.rgagnon. } public void itemStateChanged(ItemEvent ie) { ib. add(new Checkbox("Visa".applet. add(new Checkbox("Cash"./javadetails/java−0221.getSource() == ib) System. int n.

my. 3. setFont(f). String spaces10 = " ". height = r. When inserting a line.List and override the addItem method..rgagnon. Font f){ super(r.10−col2. // the character W used as reference return new Dimension (fm.html The trick is to use a FIXED width character set like "Courier". String col3) { String spaces2 = " ".BOLD. 10)).. boolean m. width = n.com/javadetails/. the preferred way would be to extend the java. String col1.awt. Here the first column is 20 characters wide. ml = new List().substring(0.substring(0. the second 10 and the last one the remaining.length()) + col3). int n. Font. "ARCHIVE"./javadetails/java−0271.com/javadetails/. String col2.m). fm./javadetails/java−0244. lbx. } public myListbox(int r.length()) + spaces2 + col2 + spaces10. String spaces20 = spaces10 + spaces10.29 Align the column in a List Current version of this HowTo : http://www.rgagnon.width = n.html 3. height = r. we simply pad spaces as needed. } } 3. "PORT").29 Align the column in a List . public void insertItem(List lbx.charWidth('W')*width.30 Have a srolling text display Current version of this HowTo : http://www.getHeight()*height). "STATUS".20−col1.setFont(new Font("Courier". insertItem(ml. } public Dimension preferredSize (){ FontMetrics fm=getFontMetrics(getFont()).addItem(col1 + spaces20. } In real life.

import java. public class TelnetLikeDisplay extends Applet implements ActionListener { Button b. this. } public void actionPerformed(ActionEvent ae) { String newLine = "Line #" + i. add(b = new Button("New Line")). In this snippet. It's a good idea to limit the amount of data kept in the List .com/javadetails/.setForeground(new Color(0). if (i <LINE_BUFFERED) { l. l.resize (aLabel.yellow).makeVisible(LINE_DISPLAYED). you have to validate() the layout to redraw the components invalidated. List l./javadetails/java−0232. l.. b.*. l. import java.addItem(newLine). Label aLabel = new Label("short label").awt. LINE_DISPLAYED). try something like this: aLabel.rgagnon.31 Label dynamic resizing .setText ("A very long label"). we are using a List component to display the data. } } 3. add(l = new List(5)). aLabel.setSize(100.remove(0).setBackground(new Color(0).100).*.addActionListener(this).event. l. } else { l.A srolling text display can be used to log informations or events.31 Label dynamic resizing Current version of this HowTo : http://www. static final int LINE_BUFFERED = 10. l. } i++. aLabel.validate().makeVisible(i).awt.black). l. in fact we have no choice because the maximum capacity is about 32k (Win).html If there is no Layout Manager installed. With a Layout Manager.setText ("A very long label").add(newLine.LEFT)).preferredSize()). int i = 0. 3. We are keeping only the last 10 events. public void init() { setLayout(new FlowLayout(FlowLayout. static final int LINE_DISPLAYED = LINE_BUFFERED − 1.

getSource() == b2) { p.31 Label dynamic resizing .drawString(someString. 10. on IE4/5 there is no resizing. l = new Label("label text").*.invalidate().awt. public void init() { setLayout(new FlowLayout()). aLabel. add(t2). Label l. } public void actionPerformed(ActionEvent e) { if (e. b1 = new Button("Change Label").getSource() == b1) { l.*.addActionListener(this).validate(). import java. TextField t1.repaint(). t2.applet.getText(). add(b1). add(t1). } 3. add(l).event. MyPanel() { super(). p. b2. b2 = new Button("Change drawString").While this method works in Netscape or the Appletviewer.*.setText(""A very long label"). validate().setText(t1.someString = t2.invalidate(). import java. public class TestPaint extends Applet implements ActionListener { MyPanel p.getText()). add(p). import java. } if (e.addActionListener(this). // a Panel with a drawString call p = new MyPanel(). Button b1. This example how to change a Label or a String drawn with the drawString method by clicking on a button. add(b2). l.50). } } } class MyPanel extends Panel { String someString = "drawstring". b2. aLabel. You may want to try this instead (thanks to Dan for the tip): Label aLabel = new Label("short label"). t1 = new TextField(10). b1. // make sure the component is marked as non−valid this.awt. t2 = new TextField(10). } public void paint (Graphics g) { g.

32 Make a TextArea "word−wrap" Current version of this HowTo : http://www. i++) { choice. i<10.awt. class ChoiceEx extends Frame implements ItemListener { Choice choice = new Choice().NORTH).event.34 Display underlined text Current version of this HowTo : 3.rgagnon. import java. BorderLayout. } // Set listeners choice. TextArea. ChoiceEx() { super("").setText("Item #" + choice.awt. } // When list or choice is updated public void itemStateChanged(ItemEvent evt) { textarea. for (int i=0.100).*. BorderLayout. } } 3. myTextArea = new TextArea ("text".public Dimension getPreferredSize() { return new Dimension (100. add(textarea. add(choice.addItemListener(this). } } 3./javadetails/java−0281. pack()..SOUTH). 3 ..html import java. } static public void main(String[] args) { new ChoiceEx().com/javadetails/.rgagnon. 3.33 Synchronize a TextArea vs a Choice Current version of this HowTo : http://www.html Simply create the TextArea with no horizontal scrollbar.*.32 Make a TextArea "word−wrap" . 100 . TextArea textarea = new TextArea(). setVisible(true).addItem("item "+i).getSelectedIndex()).SCROLLBARS_VERTICAL_ONLY)./javadetails/java−0241.com/javadetails/.

public void init() {} public void paint(Graphics g) { g.j+1). int x=10.4] import java.getHeight()+1. public class verticalText extends Applet { String s = "Vertical text". int y=10.html import java. import java.rgagnon.x.y).out. y+2 . import java. public void paint(Graphics g){ 3.*.substring(j.http://www.println(v).35 Display vertical text Current version of this HowTo : http://www. x.substring(j).awt. int k= s. import java.com/javadetails/.getFontMetrics(getFont()).awt. int y=10. int j =0.awt.AffineTransform.rgagnon. else g. while(j < k+1) { if (j == k) g. y+(j*v)).stringWidth(s) . } } Check this How−to for underlined text with a Label component.*. x+getFontMetrics(getFont()).. j++.35 Display vertical text .geom. y+(j*v)). g. int v. Check this How−to for underlined text in Swing.applet./javadetails/java−0258. System.drawString(s.*.drawString(s.Graphics2D.com/javadetails/. } } } [JDK1. 3.drawString(s.awt.x.length().drawLine(x ..*. y+2 ).applet.html import java. public void init() {} public void paint(Graphics g) { v=g./javadetails/java−0259. public class underlineText extends Applet{ String s = "Underlined text". int x=10.

private int line_widths[]. private int y = 0. public class MultiLineLabel extends Canvas { public static final int LEFT = 0. Lines can be left. MultiLineLabel.0. setBorder(b).36 Have Label with many lines ./javadetails/java−0269. private String text.drawString("Vertical text".rgagnon.*. } 3. int i.0. width/2. boolean b) { // s the label // i alignement MultiLineLabel. private boolean border.com/javadetails/.RIGHT. } public MultiLineLabel(String string. Dimension offDimension. g2d. private int alignment. g2d.0).black..CENTER. private int line_ascent.setToRotation(−Math. height/2.LEFT // default MultiLineLabel. // clockwise 90 degrees AffineTransform at = new AffineTransform().*. there is a possibility to have a border around the label. private int topBottomMargin. } 3. false). Henle for the bug fix! at. The following class implements a multi−line Label. import java.PI/2. private String lines[]. private int line_height. public static final int CENTER = 1. Lines are separated byt the token "\n".C. right or center justified. Plus. Image offImage.LEFT // b border present or not setAlignment(i). // thanks to M. private int num_lines.36 Have Label with many lines Current version of this HowTo : http://www. public MultiLineLabel(String s. y). private int x = 0. import java.util.awt. setText(s). Graphics offGraphics. Color borderColor = new Color(0). private int leftRightMargin. int i) { this(string.Graphics2D g2d = (Graphics2D)g. private int max_width. public static final int RIGHT = 2. i.html The Label component included in the AWT do not support "\n" in its definition. // MultiLineLabel.setTransform(at). x.

break. num_lines * line_height + topBottomMargin * 2). repaint().public MultiLineLabel(String string) { this(string.LEFT! if (i >= 0) leftRightMargin = i .width = 10. } public void setLeftRightMargin(int i) { // make sense only if alignment is MultiLineLabel. } public void setFont(Font font) { super.addNotify().setFont(font). 0).36 Have Label with many lines . } public void setTopBottomMargin(int i) { if (i >= 0) topBottomMargin = i. } public int getAlignment() { return alignment. 0). } public Dimension getMinimumSize() { Dimension d = new Dimension (max_width + leftRightMargin * 2. public void setY(int i) { y = i. } public MultiLineLabel() { this("". } public int getTopBottomMargin() { return topBottomMargin. } public void setX(int i) { x = i. calc(). calc(). 3. if (d. } public void setAlignment(int i) { switch (alignment) { case 0: case 1: case 2: alignment = i.width == 0) d. default: throw new IllegalArgumentException(). } public void addNotify() { super. } } public int getLeftRightMargin() { return leftRightMargin. } repaint().

} d. for (int i = 0.paint(g).36 Have Label with many lines . max_width = 0.nextToken(). line_widths = new int[num_lines]. lines = new String[num_lines]. if (line_widths[i] > max_width) max_width = line_widths[i]. } public void setText(String s) { // parse the string . "\n" is a the line separator StringTokenizer st = new StringTokenizer(s. } public void setBorderColor(Color c) { borderColor = c. 3.countTokens(). i < num_lines.if (d. i++) { line_widths[i] = fm. line_ascent = fm. calc(). num_lines = st. } public Color getBorderColor() { return borderColor. i < num_lines.height == 0) return d. text = new String(s). repaint(). } private void calc() { // calc dimension and extract maximum width Font f = getFont(). if (f != null) { FontMetrics fm = getFontMetrics(f).getAscent(). for (int i = 0. } public boolean getBorder() { return border.stringWidth(lines[i])."\n"). public Dimension getPreferredSize() { return getMinimumSize(). } public void setBorder(boolean flag) { border = flag. } } } } public void update(Graphics g) { super.getHeight(). } public String getText() { return text. i++) lines[i] = st. if (fm != null) { line_height = fm.height = 10.

Button b = new Button("Dummy").height). switch (alignment) { case 0: i = 0. offGraphics.setColor(borderColor).setLeftRightMargin(15).setVisible(true). mll1. } g.0. ) { int i. true).0. j + y). offGraphics.200).width != offDimension. f.this).blue).width) || (d.setSize(200.width − 1.setColor(getForeground()).setColor(getBackground()). offGraphics = offImage. f.width − 1.height − num_lines * line_height) / 2. mll1. y. // mll1. f. 3.add(b). MultiLineLabel mll1 = new MultiLineLabel ("This a test!\nsecond line\nthird line".drawImage(offImage.setLayout(new FlowLayout()). case 2: i = d. break. getSize().getGraphics(). getSize(). offGraphics. if ( (offGraphics == null) || (d. for (int k = 0. k < num_lines. d.setBorderColor(new Color(0).height != offDimension. } public static void main(String args[]){ Frame f = new Frame("Test MultiLineLabel").width − line_widths[k]. k++. getSize().LEFT. j += line_height. getSize().add(mll1). f.drawRect (x. default: i = (d. } offGraphics. offImage = createImage(d. break. } public void paint(Graphics g) { update(g).drawString(lines[k]. y. offGraphics. break.width − line_widths[k]) / 2.setTopBottomMargin(15). if (border) { offGraphics. i + x.height − 1).height) ) { offDimension = d.36 Have Label with many lines . f.Dimension d = getSize().fillRect (x. } int j = line_ascent + (d. } i += leftRightMargin.width. MultiLineLabel.height − 1).

html [UnderlinedLabel. } } { [TestUnderlinedLabel.MultiLineLabel mll2 = new MultiLineLabel ("123\n4\n567".getFontMetrics(this..height − this. public class TestUnderlinedLabel extends Applet { public void init() { UnderlinedLabel ul1 = new UnderlinedLabel ("Java How−to").getFont()). add(ul1).black).getDescent()). r. r.com/javadetails/. import java.height − this.java] import java.paint(g).getFont()). public class UnderlinedLabel extends Label public UnderlinedLabel(){ this("").add(mll2). } } 3. mll2. false). } } [testapplet.setForeground(new Color(0).awt. f. this./javadetails/java−0272.validate().class" 3.getDescent().*.rgagnon. } public void paint(Graphics g) { Rectangle r.getFontMetrics(this.getClipBounds().37 Have a Label with underlined text . super.*.html] <HTML><HEAD></HEAD><BODY> <APPLET CODE="TestUnderlinedLabel.awt.drawLine (0.java] import java. mll2.setBackground(new Color(0).RIGHT.getFontMetrics(this. } public UnderlinedLabel(String text){ super(text).getFont()).getText()).yellow). r = g. f.37 Have a Label with underlined text Current version of this HowTo : http://www. MultiLineLabel.stringWidth(this.applet. g.*.

private Color visitedURL = Color. java. private String target = "". String text){ this(applet. } } public void paint(Graphics g) { Rectangle r.. url. "_self").NAME="myApplet" HEIGHT=200 WIDTH=200> /APPLET/BODY/HTML Check this How−to for underlined text in Swing.*.event.html [URLLabel. try { this. public URLLabel(Applet applet .getFontMetrics(this.getFontMetrics(this.getDescent(). g. } catch (Exception e) { e. } public URLLabel (Applet applet . this.url = new URL(url).getFont()).stringWidth(this.target = target.java] import import import import java.getFontMetrics(this.applet.rgagnon. this.38 Have a Label acting as HTML HREF (URLLabel) Current version of this HowTo : http://www. setForeground(unvisitedURL).*. java. } public void setUnvisitedURLColor(Color c) { unvisitedURL = c. String target){ super(text). 3. java.net.blue. private Color unvisitedURL = Color. String url./javadetails/java−0273.printStackTrace().awt.com/javadetails/.applet. r. this.38 Have a Label acting as HTML HREF (URLLabel) . public class URLLabel extends Label { private java. super. addMouseListener( new Clicked() ). r. String url. String text.drawLine(0.paint(g). private URL url. text.height − this.*.*.getClipBounds().height − this.getFont()). r = g.green.applet = applet. } public void setVisitedURLColor(Color c) { 3.getText()).Applet applet.getDescent()).getFont()).awt.

rgagnon.rgagnon. "http://www.applet.html import java. target). URLLabel ull4 = new URLLabel(this.com/bigindex. public class TestURLLabel extends Applet { public void init() { URLLabel ull1 = new URLLabel(this.java] import java.awt. "http://www. add(ull2).awt.39 Display a GIF in a Canvas Current version of this HowTo : http://www.com/javadetails/java−0001. import java.39 Display a GIF in a Canvas . import java.html". 3.awt.class" NAME="myApplet" HEIGHT=200 WIDTH=200> </APPLET></BODY></HTML> Try it here.html] <HTML><HEAD></HEAD><BODY> <APPLET CODE="TestURLLabel.com/javadetails/java−0002. "Java How−to"). 3. public class ImageCanvas extends Canvas { Image image. validate().getAppletContext()./javadetails/java−0229. URLLabel ull3 = new URLLabel(this.showDocument(url. applet. URLLabel ull2 = new URLLabel(this. } } [testapplet.*. "http://www.*.visitedURL = c.*. "Java How−to 0001").rgagnon.html".. add(ull3). add(ull1).*.image. "Java How−to BigIndex"). add(ull4).com/howto.html".rgagnon. } } } [TestURLLabel. } class Clicked extends MouseAdapter{ public void mouseClicked(MouseEvent me){ setForeground(visitedURL). "Java How−to 0002").com/javadetails/. "http://www.rgagnon.html".

mt.*. // for Applet. frame.400).length <1) { System.drawImage(image. } { 3.addImage(image.waitForID(0).public ImageCanvas(String name) { MediaTracker media = new MediaTracker(this). this). mt.rgagnon. frame.40 Embed an image into a Frame Current version of this HowTo : http://www. new ImageCanvas(argv[0])).waitForID(0). import java.resize(400. frame. ImageFrame() { super("").. } catch (Exception e) {} } public ImageCanvas(ImageProducer imageProducer) { image = createImage(imageProducer).40 Embed an image into a Frame . } public static void main(String argv[]) { if (argv.show(). } public void paint(Graphics g) { g.com/javadetails/. The result is not too good with Label.event.getDefaultToolkit(). try { media. public class ImageFrame extends Frame private Image image.*.setLayout(new BorderLayout()).add("Center".awt.0.addImage(image.class [image file name]"). System. import java.html A given image is tiled as the frame background.gif"). try { MediaTracker mt = new MediaTracker (this). } } 3.. 0).println ("usage: ImageCanvas. frame.out.getDefaultToolkit(). image = Toolkit. media..getImage("images/jht.exit(0).awt./javadetails/java−0302.getImage(name). } Frame frame = new Frame(argv[0]). change the method to retrieve the image // and of course use your own image! image = Toolkit. 0. 0).

add(new Label("Hello")).40 Embed an image into a Frame .width.clearRect(0. iframe. y = 0. 500). } public void update( Graphics g) { paint(g).getHeight(null)."). add(new List(20)).setVisible(true)..printStackTrace().20)). // Label may not look too good . add(new TextField(10)).out.height). } } The result : 3. getSize(). this).println("Bye. } } else { g. } } static public void main(String[] args) { ImageFrame iframe = new ImageFrame(). setSize(500. while(x< getSize().height) { x = 0. add(new TextArea(20.. getSize(). x= x + image. } y = y + image.drawImage(image. System.exit(0). addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { // change this for an Applet System.catch (Exception e) { e. while(y < getSize(). } } ). 0.width) { g. x. } setLayout(new FlowLayout()). add(new Button("hello")). } public void paint(Graphics g) { if(image != null) { int x = 0. y.getWidth(null).

io.net. 0. You may want to get this GIF ( ) if you want to try the example on your workstation! import import import import java.awt. } { this). public void loadImages(String s) { MediaTracker t=new MediaTracker(this).applet. 0. Image icon[] = new Image[iconCount].gif").3.*. 0. int iconWidth = 16. this). 0. this). java.41 Load several images from a single GIF Current version of this HowTo : http://www.*. public void init(){ loadImages("item. In the following snippet.drawImage(icon[0]. java.. public class strip extends Applet{ int iconHeight = 16./javadetails/java−0239. g.drawImage(allIcons. Image allIcons. int iconCount = 2. 40. 20. 3.drawImage(icon[1]. I assume that all images are the same height and width.41 Load several images from a single GIF . } public void paint(Graphics g) g.*. java.html It's a good idea to combine small GIFs into a single big one to speed up the loading process.*.com/javadetails/.rgagnon. g.

out. URL imgURL = getClass().html [JDK1. img = tk. // for example 3. Image img = null./javadetails/java−0240. } for (int i=0.clipRect(0. } try { t.jpg".getDefaultToolkit().this). m.−i*iconWidth. } catch (InterruptedException e) { System.getImage(u). } } } 3.iconHeight).println("interrupted"). it's not possible with some browser (like Netscape) to use the getResource() method from an Applet.com/javadetails/. Graphics g=z. Image img = null.getResourceAsStream("img/image. i < iconCount. t.addImage(allIcons.rgagnon.printStackTrace(). Instead we must use the getResourceAsStream method. try { MediaTracker m = new MediaTracker(this).42 Load an Image from a JAR file Current version of this HowTo : http://www.1 applet] Because of some security reason. 0).waitForAll().gif"). i++) { Image z=createImage(iconWidth.gif"). g. allIcons=Toolkit.1 application] String imgName = "image. Toolkit tk = Toolkit.getResource(imgName). icon[i]=z. try { MediaTracker m = new MediaTracker(this).1).allIcons=createImage(1.drawImage(allIcons.waitForAll(15000).getImage(imgURL).iconWidth. } catch (Exception e) { e.out.42 Load an Image from a JAR file .0.0. InputStream is = getClass().0).getDefaultToolkit(). m.getGraphics(). try { URL u=new URL(getCodeBase(). g. } [JDK 1.getResourceAsStream("image. } catch (MalformedURLException me) { System.println("MalformedURLException: " + me).addImage(img.. s). // // if your image is in a subdir in the jar then // InputStream is = getClass().iconHeight).

getSystemResource(name)).setIcon(new ImageIcon(url)).gif").waitForAll(). 0). Remember that it is always possible to the Java built−in icons so that you don't have to include your own standard icons. int byteRead = bis..getDefaultToolkit().warningIcon"). // a buffer large enough for our image // // can be // byte[] byBuf = = new byte[is.43 Load an Icon from a jar (again) Current version of this HowTo : http://www. } ImageIcon img = getImageIcon("resources/images/icone.com/javadetails/./javadetails/java−0436. img = Toolkit. byte[] byBuf = = new byte[10000].getIcon("OptionPane.read(byBuf).rgagnon. case 2: return UIManager.questionIcon").errorIcon").getClass().2 application] URL url = this.informationIcon"). } [JDK 1.getIcon("OptionPane.// BufferedInputStream bis = new BufferedInputStream(is).printStackTrace(). button.read(byBuf. or something like that. m..html public static ImageIcon getImageIcon(String name) { return new ImageIcon(ClassLoader.10000).available()].getResource("myIcon.43 Load an Icon from a jar (again) . public static Icon getIconForType(int iconType) { switch (iconType) { case 0: return UIManager.. } return null. } } catch(Exception e) { e.0.getIcon("OptionPane.getIcon("OptionPane. case 3: return UIManager. } 3. case 1: return UIManager.gif"). // is.createImage(byBuf). consider making a small donation to show your support for this Web site and its content.addImage(img. If you find this article useful. m. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 3.

*.10. import java.io.*. java.*. try { media. media. 3. 80.replicate).html import java. media. half the original size ImageFilter replicate = new ReplicateScaleFilter (source. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 3. } } Try it here. import import import import import java. java.getHeight(this)/2). consider making a small donation to show your support for this Web site and its content. g.awt.44 Scale an Image . java.awt. ImageProducer prod = new FilteredImageSource(source.getWidth(this)/2.1).waitForID(1).waitForID(0).awt.*.rgagnon.this).*.addImage(source.*.net.com/javadetails/.Applet { Image source.44 Scale an Image Current version of this HowTo : http://www.drawImage(resizedImage. public void init() { MediaTracker media = new MediaTracker(this).gif"). The following exampe takes a JPG file as input ..this).10.applet. media.getSource(). rescale it to the passed parameters and writes the result in the specified output file. can be JPG source = getImage(getDocumentBase().imageio.awt. 10. source.A list of what icons are available can be found here If you find this article useful. import java.". resizedImage = createImage(prod).image. Image resizedImage.geom./images/jht.0). Modern JDK has now a complete library devoted to graphic manipulation. // scale down.addImage(resizedImage. javax./javadetails/java−0243.*.image. // java how−to image for example.drawImage(source. } catch(InterruptedException e) {} } public void paint(Graphics g) { g.awt.*.. public class app extends java.

} } } Example : >java ScaleJPG javahowto.image.getHeight()).*.getScaleInstance((double)width/bsrc. g.TYPE_INT_RGB). } public static void main(String[] args) { if (args.*. } } else { System.html This example display a GIF with a fade−in. java."JPG". int width.awt. int height. 3./javadetails/java−0249.at).45 Fade an image Current version of this HowTo : http://www. java.*. Graphics2D g = bdest.jpg Input: Ouput: 3.45 Fade an image .length == 4) { try { ScaleJPG. fade−out effect. BufferedImage bdest = new BufferedImage(width.rgagnon.createGraphics().com/javadetails/. Integer. ImageIO. BufferedImage. args[3]).Integer. import import import import java. height.new File(dest)).awt.public class ScaleJPG { public static void scale(String src.read(new File(src)).*.printStackTrace().applet.write(bdest. AffineTransform at = AffineTransform.parseInt(args[2]). String dest) throws IOException { BufferedImage bsrc = ImageIO.println("\nUsage: java ScaleJPG src width height dest\n").jpg 250 70 javahowto2. java.getWidth(). (double)height/bsrc..out.drawRenderedImage(bsrc.scale (args[0]. } catch (Exception e) { e.parseInt(args[1]).net.

fis = new FilteredImageSource(img. } repaint().0.createImage(fis). tracker = new MediaTracker(this). FilteredImageSource fis. tracker. if (faded != null) faded.0. int level. } f = new AlphaFilter(). 20).gif")).sleep(1000).start().waitForID(0). level += sign. if (level &lt.getSource().setLevel(level). f. ft. MediaTracker tracker.public class FadeImage extends Applet { Image img. try { img = getImage(new URL(getDocumentBase(). faded = this. } } public void fadeIt() { Graphics g = this. } if (level &gt. AlphaFilter f. tracker.this). tracker. 255) { level=255. } class FadeThread extends Thread { 3. faded.addImage(faded.addImage(img.45 Fade an image ./images/gumby. ".0). f) .getGraphics(). public void init() { level = 0.drawImage(faded. ft. try { Thread. sign.setLevel(level). sign = sign * −1. } catch (Exception e) {} } f. } public void paint(Graphics g) { if (faded != null) { g..delayedFading(this. sign = 15. 0) { level=0.printStackTrace(). } catch (Exception e) { e. } catch (Exception ex) { ex. sign = sign * −1. try { tracker.waitForID(0).flush().0). FadeThread ft = new FadeThread().printStackTrace().

} public int filterRGB(int x. int delay. import java.printStackTrace(). return (rgb & 0x00ffffff) | a.rgagnon. public class rotateGumby extends Applet { Image img = null. import java.FadeImage fadeApplet. int delay) { this. 3.html The following snippet rotates an image (90 degrees). } public void run() { while (true) { try { sleep(delay). } catch (Exception e) { e. 3.*. fadeApplet. this.Applet.46 Rotate an image Current version of this HowTo : http://www. You may want to grap this image for testing purpose. public AlphaFilter() { canFilterIndexColorModel = true..com/javadetails/. } public void setLevel(int lev) { level = lev. Image rot = null.net. int buffer[] = new int[32 * 32].fadeApplet = f.applet.46 Rotate an image . int rotate[] = new int[32 * 32]. The applet assumes the dimension 32x32 for the image. int rgb) { int a = level * 0x01000000.fadeIt(). } } } Try it here./javadetails/java−0248. public void delayedFading(FadeImage f. int y.delay = delay. } } } } class AlphaFilter extends RGBImageFilter { private int level.

} catch (Exception e) { e.printStackTrace().printStackTrace(). x < 32. 32. public class RotatePanel extends JPanel { private Image image.grabPixels(). } catch (Exception e) { e. 0. java.awt.geom. } } rot = createImage(new MemoryImageSource(32. 32.drawImage(rot. } for(int y = 0. 0.drawImage(img.*. x++) { rotate[((32−x−1)*32)+y] = buffer[(y*32)+x]. } } public void update( Graphics g) { paint(g). } } The next example will rotate a picture 5 degrees at a time. 0).image = image. y < 32. We are using the Java2D package (and Swing).waitForID(0). } public void paint(Graphics g) { g. 0. 0. 0). tracker. javax.46 Rotate an image . this).event.gif")). 32). import import import import java.awt. 32. public RotatePanel(Image image) { this.*.waitForAll(). img = getImage(new URL(getDocumentBase(). 0. buffer.*. g.swing.*. } } public void rotate() { 3. 40. y++) { for(int x = 0.awt. private double currentAngle. tracker. mt. java. MediaTracker mt = new MediaTracker(this).addImage(image.this).0. "gumby.public void init() { try { MediaTracker tracker = new MediaTracker (this). 0. PixelGrabber grabber = new PixelGrabber(img. } catch(InterruptedException e) { e.addImage (img.printStackTrace(). try { mt. try { grabber. rotate. 32)).

yRot). } protected void paintComponent(Graphics g) { super. Container cp = f. } public static void main(String[] args) { JFrame f = new JFrame(). b.*. import java.rotate().getHeight(this))/2.paintComponent(g). int y = (getHeight() − image. } } 3. BorderLayout.getWidth(this))/2. } repaint()..getDefaultToolkit(). f.SOUTH)./javadetails/java−0230.gif").getTransform(). } }). newXform. final RotatePanel rotatePanel = new RotatePanel(testImage). f.setTransform(origXform).add(rotatePanel. g2d. g2d.add(b.getHeight(this)).getContentPane().setVisible(true).awt.CENTER). public class apptest extends Applet { 3.0) { currentAngle = 0.setLayout(new BorderLayout()). if (currentAngle >= 360. JButton b = new JButton ("Rotate"). y. cp.com/javadetails/. int yRot = this. Graphics2D g2d = (Graphics2D)g. cp. image. //center of rotation is center of the panel int xRot = this.getWidth(this).getImage("c:/temp/gumby.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { rotatePanel.setTransform(newXform). this). Image testImage = Toolkit. BorderLayout.toRadians(currentAngle). cp. AffineTransform newXform = (AffineTransform)(origXform. //draw image centered in panel int x = (getWidth() − image.html JDK1. } public Dimension getPreferredSize() { return new Dimension (image.//rotate 5 degrees at a time currentAngle+=5.getWidth()/2.rgagnon. x.1 using a ScrollPane import java.*.47 Create a scrollable canvas .rotate(Math. AffineTransform origXform = g2d.getHeight()/2.47 Create a scrollable canvas Current version of this HowTo : http://www. xRot.clone()).0.drawImage(image.pack().applet. g2d.

} public void initpaint(Graphics g) { try { buffImage = this. public void init() { setLayout(new BorderLayout()).drawImage(buffImage. s).white). Color. public void init() { setLayout(new FlowLayout()). 0.47 Create a scrollable canvas . ScrollPane s.setSize(500. add(sc).0. } catch (Exception e) { e. add("Center".150. 42)).printStackTrace(). this).setFont(new Font("Courier".white). else g. } } } } JDK1. offscreen.black.*. s = new ScrollPane().setColor(Color.0.awt. offscreen. this). 300.fillRect(0.ITALIC.drawImage(buffImage.drawString("Hello World!". 500. Font. 500). this). 50). import java. s.setColor(Color.300). c = new myCanvas().add(c). 500). g. myCanvas() { super(). } 3. } public void paint(Graphics g) { if (!initDone) initpaint(g).200. } public void update(Graphics g) { g. initDone = true.0.applet. 0.*. boolean initDone = false. } class myCanvas extends Canvas { Image buffImage.setSize(100.createImage(500.getGraphics(). offscreen. Color.2 using a Canvas with Scrollbar import java.drawImage(buffImage. 0. sc = new ScrollCanvas (150.black).100). c. offscreen. offscreen.Canvas c. s. 0. Graphics offscreen. public class apptest extends Applet { ScrollCanvas sc. offscreen = buffImage. 0. 0.

SCROLL_PAGE_DOWN: case Event.47 Create a scrollable canvas . c = new myCanvas(vw. } } class myCanvas extends Canvas { int vw. vh. int rw.HORIZONTAL.VERTICAL. vh. sh). myCanvas c. rh). Color b. int rw1. rw = rw1.public boolean handleEvent(Event e) { if (e. rh = rh1. int rh1.0. vw = vw1. sh. rw).redraw().f. return true. setLayout(new BorderLayout()).SCROLL_LINE_UP: case Event. Color f1) { super(). 3. sv = new Scrollbar (Scrollbar. c. 0. vh = vh1. } } class ScrollCanvas extends Panel { int vw. Scrollbar sv. int vh1.getValue().SCROLL_PAGE_UP: case Event.draw(x. sh = new Scrollbar (Scrollbar.rh. add("South". 0. 0.vh.getValue(). } } return super.y). b = b1. b . // constructor // visible h w // real h w // background foreground ScrollCanvas (int vw1.id) { case Event. ScrollIncrement. rh. c).handleEvent(e). sv). Color b1.vh).SCROLL_ABSOLUTE: case Event. int x = sh.vh).SCROLL_LINE_DOWN: sc. ScrollIncrement. add("East". rw. add("West". } public Dimension minimumSize() { return new Dimension(vw. } public Dimension preferredSize() { return new Dimension(vw. f = f1. } public void redraw() { int y = sv.target instanceof Scrollbar) { switch (e. int ScrollIncrement = 10.f).

vh = vh1.int rw.0. b = b1.ITALIC.createImage(rw. offscreen. } public void update(Graphics g) { g.drawImage(buffImage. this). repaint(). rw = rw1. int x. y. } public Dimension preferredSize() { return new Dimension(vw. Image buffImage. x.out. } } public void draw (int x1.setFont(new Font("Courier". } catch (Exception e) { System. Color f1) { super(). offscreen.vh). vw = vw1. f. 42)). Graphics offscreen. g. int y1) x = −x1. initDone = false. rw. x. 0. rh). } } { 3.drawImage(buffImage. y.vh).fillRect(0.. offscreen = buffImage.setColor(b). this). y. update(getGraphics()). boolean initDone. myCanvas (int vw1.drawString("Hello World!". y = −y1.setColor(f). initDone = true.println("oups. Color b1. offscreen. Color b. } public Dimension minimumSize() { return new Dimension(vw. int rw1. } public void paint(Graphics g) { if (!initDone) initpaint(g). rh. this). offscreen.getGraphics().0. } public void initpaint(Graphics g) { try { buffImage = this. rh = rh1. f = f1.drawImage(buffImage."). rh). 50). else g. int vh1.. 0.47 Create a scrollable canvas . int rh1. Font. offscreen.

// // // // TILE BACKGROUND in the HTML use : PARAM NAME="bgImage" VALUE="images/myImage. add(new TextField(10)). } public void update( Graphics g) { paint(g). 0. getParameter("bgImage"))).*.printStackTrace().getWidth(null). 0).gif"> </APPLET> /HMTL 3.com/javadetails/. } setLayout(new FlowLayout()).html import java.waitForAll(). tracker.getHeight(null).applet. y = 0. } public void paint(Graphics g) { if(bgImage != null) { int x = 0.jpg" in the APPLET tag public class Tile extends Applet { Image bgImage = null.. this). } } } <HTML> <TABLE><TR><TD> <APPLET CODE=Tile. x.height).class WIDTH=150 HEIGHT=150> <PARAM NAME="bgImage" VALUE="images/jht. } y=y+bgImage.48 Use an Image as the Applet background .net. x=x+bgImage. public void init() { try { MediaTracker tracker = new MediaTracker (this).3. } } else { g. while(x<size(). size(). tracker.clearRect(0.rgagnon./javadetails/java−0233.height) { x = 0.drawImage(bgImage. } catch (Exception e) { e.width. while(y < size(). size(). bgImage = getImage (new URL(getCodeBase().width) { g. y.Applet. add(new Button("Ok")). import java.addImage (bgImage.48 Use an Image as the Applet background Current version of this HowTo : http://www.

String url[] = new String[50].gif|Powerbuilder How−to [application version] import import import import java.awt. add(lbx). 0). // to close the Frame addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { System.awt.49 Have a simple Image browser .49 Have a simple Image browser Current version of this HowTo : http://www. java. java./javadetails/java−0277.getDefaultToolkit().*. setVisible(true). Image image = Toolkit. lbx = new List().txt] jht. 3..*. setSize(800. MediaTracker media = new MediaTracker(this).com/javadetails/.gif|Javascript How−to pht. } } class AFrame extends Frame implements ActionListener { List lbx.getImage(theUrl).2)).addImage(image.net.getSelectedIndex()].*. public AFrame() { setTitle("Image selection. setLayout(new GridLayout(1. } } ). MyCanvas can. try { 3.addActionListener(this).gif|JAVA How−to jsht.*.rgagnon.600).Try it here. public class ImageBrowser { public static void main(String s[]) { AFrame f = new AFrame().html [imagelist. add(can). java. media.io. can = new MyCanvas(). // action on listbox double click lbx.exit(0). } public void actionPerformed (ActionEvent ae) { String theUrl = url[lbx. initLbx().event. double click to display").

StringTokenizer(aLine. java.util. "Center"). java.*. } } NOTE : You can download this example here [applet version] import import import import import java.util. } public void paint(Graphics g) { if (image != null) g.drawImage(image.0. lbx. } catch (Exception e) { e.*.} } } class MyCanvas extends Canvas { private Image image.readLine())) { java.nextToken()). add(p. public class ImageBrowserApplet extends Applet { public void init() { APanel p = new APanel(this).awt.nextToken(). } } class APanel extends Panel implements ActionListener { private List lbx.*.txt")). // lbx.waitForID(0). BufferedReader in = new BufferedReader(new FileReader("imagelist. } } catch(Exception e) { e. try { String aLine = "".applet. while(null != (aLine = in. public MyCanvas() { super().io. private MyCanvas can.*.StringTokenizer st = new java.} } public void initLbx() { int i = 0. 0. java.event. setLayout(new BorderLayout()).awt. can.printStacktrace(). 3. url[i++] = st.nextToken()).printStackTrace(). "|").add(st.setImage(image). repaint().addItem(st. java.*.net.media. this). } public void setImage(Image i) { image = i.49 Have a simple Image browser .

txt"). try { String aLine = "".getSelectedIndex()]). url[i++] = st.getDefaultToolkit(). initLbx(). setBackground(new Color(0).nextToken()).readLine())) { java.setImage(image). can.addActionListener(this). // action on listbox double click lbx.2)).} } public void initLbx() { int i = 0.getCodeBase().nextToken()).util.addImage(image. Image image = Toolkit. URL source = new URL(parent.getCodeBase(). public APanel(Applet a) { parent = a.nextToken().printStackTrace(). MediaTracker media = new MediaTracker(this). add(lbx). media. } public void setImage(Image i) { image = i. lbx. } public void actionPerformed (ActionEvent ae) { try { URL theUrl = new URL(parent. lbx = new List().add(st. url[lbx.addItem(st.StringTokenizer(aLine.printStackTrace(). public MyCanvas() { super().StringTokenizer st = new java. add(can). } catch (Exception e) { e. while(null != (aLine = in.private Applet parent = null.util.getImage(theUrl). private String url[] = new String[50]. repaint(). } } catch(Exception e) { e. "imagelist.openStream())).} } } class MyCanvas extends Canvas { private Image image. media. BufferedReader in = new BufferedReader (new InputStreamReader(source. setLayout(new GridLayout(1.white). // lbx. "|"). 0). } public void paint(Graphics g) { if (image != null) 3.waitForID(0). can = new MyCanvas().49 Have a simple Image browser ..

50 Simulate a "mouse over" event to toggle an image .this). tracker. this). [JDK1.getImage(n2).printStackTrace().awt. } } } public Dimension getPreferredSize (){ return new Dimension (img1.0.*.rgagnon.getHeight(this). tracker.com/javadetails/. tracker.waitForAll().event.this). public ToggleGifCanvas(URL n1.addImage(img2.0. } } NOTE : You can try this example here 3.drawImage(image.0. img2.g.getWidth(this)).0). int index = 0./javadetails/java−0264.addImage(img1. index++..*. } catch (Exception e) { e. MediaTracker tracker.awt.0.0.1] import java. addMouseListener(this). } else { g. URL n2) { tracker = new MediaTracker(this). index−−. and using a MouseListener simply toggle the image. import java. import java.drawImage(img2.drawImage(img1.getDefaultToolkit(). img2.html Use a special Canvas to preload 2 GIFs.*. } public void mouseClicked(MouseEvent e) {} 3. } } public void paint(Graphics g) { if (img1 != null) { if (index == 0) { g. img2 = Toolkit.50 Simulate a "mouse over" event to toggle an image Current version of this HowTo : http://www.net.getImage(n1).getDefaultToolkit().1). 0. try { img1 = Toolkit. public class ToggleGifCanvas extends Canvas implements MouseListener { Image img1.

public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) { index = 1.createImage( new MemoryImageSource(16./javadetails/java−0440.rgagnon.html One way is to use a transparent GIF as the cursor or create one.applet. 0. new URL(getDocumentBase().getDefaultToolkit().net. } } } Try it here. Image image = Toolkit. 3. 16. public void init() { try { tgc = new ToggleGifCanvas (new URL(getDocumentBase(). 3.awt. This example needs our Gumby GIFs ( ).gif").*. public class TestToogleGifCanvas extends Applet { ToggleGifCanvas tgc. } } To use such Canvas. "invisibleCursor").com/javadetails/."images/gumby.createCustomCursor (image. import java. and import java. pixels.*. Cursor transparentCursor = Toolkit.. repaint().51 Hide the mouse cursor Current version of this HowTo : http://www. repaint(). 16)). } public void mouseExited(MouseEvent e) { index = 0.gif")). try something like this. int[] pixels = new int[16 * 16].getDefaultToolkit(). } catch (Exception e) { e."images/gumby2.51 Hide the mouse cursor .printStackTrace(). import java. 0).*. new Point(0. add(tgc).

*. Image GifModifiedWithTransparentBackground. import java. All we have to do is to look for the blue color with the "Alpha bits" set to opaque and make them transparent.gif").*.*.getSource(). } else { // nothing to do return rgb. } } }.image.3. try { media.waitForID(0).*. int rgb) { if ( ( rgb | 0xFF000000 ) == markerRGB ) { // Mark the alpha bits as zero − transparent return 0x00FFFFFF &rgb.com/javadetails/.rgagnon.applet.*. filter). public void init() { setBackground(new Color(0). ImageProducer ip = new FilteredImageSource(im.getRGB() | 0xFF000000. Alpha bits are set to opaque public int markerRGB = color.addImage(GifOriginalWithWithBlueBackground.java] import java..createImage(ip). int y. Gumby with a blue background GifOriginalWithWithBlueBackground = getImage(getDocumentBase().java] import java. final Color color) { ImageFilter filter = new RGBImageFilter() { // the color we are looking for.awt.. return Toolkit.white). import java. // image of our friend.html Here we have an Image with a blue background like and we want to display it in an Applet with a white background. } } [app.image.getDefaultToolkit().52 Make a color transparent .awt. [Transparency. import java. public class Transparency { public static Image makeColorTransparent (Image im.Applet { Image GifOriginalWithWithBlueBackground. public class app extends java.52 Make a color transparent Current version of this HowTo : http://www. MediaTracker media = new MediaTracker(this). GifModifiedWithTransparentBackground = 3.net. public final int filterRGB(int x.awt.0)./javadetails/java−0265.awt."gumbyblu.. media.

80.this).html Take a look at the following package : http://www.53 Save an Image as a GIF or JPEG file . g. } catch (JimiException je) { je.0.drawImage(GifModifiedWithTransparentBackground.rgagnon. Jimi.class" NAME="myApplet" HEIGHT=200 WIDTH=200> </APPLET> </BODY></HTML> 3.blue).com/javadetails/.drawImage(GifOriginalWithWithBlueBackground.image.html] <HTML><HEAD></HEAD><BODY> <APPLET CODE="app. double h = 200./javadetails/java−0266.(int)h.2] // img is a Java Image // BufferedImage bimg = null.jrf.new FileOutputStream(f)).putImage("image/jpeg". With this package.getGraphics().10.jpg"). 10.sun. g.53 Save an Image as a GIF or JPEG file Current version of this HowTo : http://www.h). double w = 200.jpeg package.acme. 3.obrador. // [JDK1..0.getSource()). BufferedImage image = new BufferedImage( (int)w. } catch(InterruptedException e) {} } public void paint(Graphics g) { g. Sun introduces a new package called JIMI (available for download at their Web site. it's easy to convert a Java Image to a JPEG image file.BufferedImage.makeColorTransparent (GifOriginalWithWithBlueBackground.createRasterImage(image.drawLine(0.htm for JPEG http://www. JimiRasterImage jrf = Jimi.codec. new Color(0). try { File f = new File("myimage.Transparency.com/essentialjpeg/jpeg.2.printStackTrace().gov/ij/ can display BMP and save as GIF or TIFF With JDK1. Graphics2D g = (Graphics2D)image. } } [x.10.} Another way is to use the undocumented com.w.info.this).nih.com for GIF http://rsb.TYPE_INT_RGB).0.

} bimg = new BufferedImage(w. Since JDK1.h.int w = img. instead of Image you use BufferedImage which is a subclass of Image.4. With ImageIO. } } 3. bimg.printStackTrace().html // in the HTML. int h = img.file).encode(bimg).0.0.intValue()).pixels.*.pixels.setRGB(0. import java. import javax.write(bufferedImage.imageio.h.54 Use the same background color as the browser . use // PARAM NAME="bgColor" VALUE="B8B5AE" // (where VALUE is the same hexadecimal value // as the HTML COLOR value) // in the APPLET tag // in the JAVA init method : Color bgcolor = new Color( Integer.BufferedImage. jpeg.image.awt.getWidth(null). PixelGrabber pg = new PixelGrabber(img.54 Use the same background color as the browser Current version of this HowTo : http://www./javadetails/java−0234. // Encode as a JPEG FileOutputStream fos = new FileOutputStream("out."jpg". } catch(InterruptedException ie) { ie.createJPEGEncoder(fos). } public static void writeImageToJPG (File file. try { pg.jpg"). setBackground(bgcolor).*..close().BufferedImage bufferedImage) throws IOException { ImageIO.grabPixels(). fos.getHeight(null).0.0.rgagnon. javax.ImageIO lets you save and restore Images to disk in a platform independent format. int [] pixels = new int[w * h]. 3. JPEGImageEncoder jpeg = JPEGCodec. 16). import java.w.2.read(file).w.com/javadetails/.valueOf(getParameter("BGCOLOR"). "png" and "jpeg" format are supported.0. public class FileOperations { public static BufferedImage readImageFromFile(File file) throws IOException { return ImageIO.w).*.h.w).imageio.io.TYPE_INT_RGB).

addImage(img[1].addImage(img[0]. try { // images loading img[0] = getImage(new URL(getDocumentBase().com/javadetails/.image. "images/gumby.1).this). img[1] = getImage(new URL(getDocumentBase(). } catch (Exception e) { e.html By using a Thread.start(). public class AnimationGifApplet extends Applet { Image [] img. tracker. java.*./javadetails/java−0262. at.0. } } public void animate() { repaint(). } class AnimationThread extends Thread { AnimationGifApplet animationApplet. tracker.printStackTrace(). int index = 0.length − 1. int delay.*. "images/gumby2.delay = delay.awt. MediaTracker tracker.55 Do simple animation using Images .. } public void paint(Graphics g) { if (img[0] != null) { g. tracker.drawImage(img[index].*.0.animationApplet = a.delayedAnimation(this. java. public void init() { img = new Image[2]. public void delayedAnimation(AnimationGifApplet a. 500). } 3.awt.55 Do simple animation using Images Current version of this HowTo : http://www. this.gif")). tracker = new MediaTracker(this). } AnimationThread at = new AnimationThread().net. java. int delay) { this. index = (index <maxImg) ? index + 1 : 0.rgagnon. at. we switch between 2 GIFs ( and ) import import import import java.*. // 2 images in animation maxImg = img. int maxImg.gif")).waitForAll().applet.3.0).

we switch between 2 GIFs.56 Do simple animation to show "work in progress" Current version of this HowTo : http://www.awt. boolean working = false. and public class AnimationProgress extends Applet implements ActionListener{ Image [] img. b. int index = 0. click again to terminate the "work in progress" [JDK1. animationApplet. add(b = new Button("Working")).gif")).html Like the previous How−to. for example ( ).awt. public void init() { setLayout(new FlowLayout(FlowLayout.LEFT)).printStackTrace().rgagnon. img[1] = getImage(new URL(getDocumentBase(). img = new Image[2].applet. "gumby.56 Do simple animation to show "work in progress" .image. Button b. // 2 images in animation maxImg = img. int maxImg. java.*. java. } } } } } Try it here. tracker = new MediaTracker(this).1] import import import import import java.*.*.gif")). MediaTracker tracker. java. } catch (Exception e) { e.addImage(img[0].event./javadetails/java−0263.net. using a Thread.public void run() { while (true) { try { sleep(delay). java.addActionListener(this).*.length − 1.com/javadetails/. "gumby2.awt. tracker. try { // images loading img[0] = getImage(new URL(getDocumentBase(). 3. 3. Click the button to simulate some work.0).*..animate().

} AnimationThread at = new AnimationThread(). } class AnimationThread extends Thread { AnimationProgress animationApplet.com/javadetails/. animationApplet. index = (index <maxImg) ? index + 1 : 0.printStackTrace(). int delay.waitForAll(). 500)..animationApplet = a. } } } public void animate() { repaint().1).68. } public void actionPerformed(ActionEvent ae) { working = !working. tracker.57 Get the color of a specific pixel Current version of this HowTo : http://www.animate().html We assume that we have an Image called picture pixels = new int[width*height]. } public void paint(Graphics g) { if (img[0] != null) { if (working) { g. at. int delay) { this.addImage(img[1].0.delay = delay. } public void run() { while (true) { try { sleep(delay).this). at.57 Get the color of a specific pixel . public void delayedAnimation(AnimationProgress a. 3.rgagnon./javadetails/java−0257. } } } } } 3.drawImage(img[index]. } catch (Exception e) { e.tracker.printStackTrace().start(). } catch (Exception e) { e.delayedAnimation(this. this.

btnUndo. int blue = c &0x000000ff. int red = (c &0x00ff0000) >> 16. add(btnClear). btnClear = new Button("Clear").yl.rgagnon. try { pg. 0.grabPixels(). BufferedImage image = ImageIO.ImageIO. 0.read(urlImage). int c = image.imageio.green.getRGB(x. int c = pixels[index].green.image. Button btnClear. add(btnUndo). int xl. 3..Vector. Image offImg.awt. height. import java. int np = 0..58 Do "rubber−band" drawing Current version of this HowTo : http://www..58 Do "rubber−band" drawing . int blue = c &0x000000ff. Vector lines = new Vector(). individual pixel can be accessed via the pixels array.blue). pixels.html import java. int x2. // and the Java Color is .awt.. Color c = new Color(red.PixelGrabber pg = new PixelGrabber(picture. public void init() { setLayout(new FlowLayout()). int x1. 0. int green = (c &0x0000ff00) >> 8. int h = 200. setBackground(new Color(0). // and the Java Color is .*. // or pixels[x * width + y] int red = (c &0x00ff0000) >> 16..y1..com/javadetails/. width.*. 3.y). } catch (InterruptedException e) { } From here. public class SimpleCAD extends Applet { int w = 200.BufferedImage .applet. import java. int green = (c &0x0000ff00) >> 8. width). btnUndo = new Button("Undo"). Graphics offGra.black). Color c = new Color(red. Here another way to achieve this import javax.y2.blue)./javadetails/java−0251..util. import java.

0. offGra. } } // put the OffScreen image OnScreen g. } public void Dragupdate(Graphics g) { /* ** rubber−band effect */ g.elementAt(i).blue).getGraphics().x.width.x.0. for (int i=0. if (p. if (xl != −1){ // erase the old line g.white).y.white).y.y.width. xl. y1 = e.height). // x2 y2 last current point x2 = e.fillRect(0. dim. offGra = offImg. case Event.MOUSE_DRAG: // xl yl line to be erased xl = x2. p.0. e.black). e. 3. } public boolean handleEvent(Event e) { switch (e. x2 = xl = −1. if (x2 != −1) { // draw the new one g. } offGra.drawImage(offImg.MOUSE_DOWN: // new starting point x1 = e. y2).setColor(new Color(0).width.setXORMode(getBackground()).width != −1) { offGra. offGra. p.setForeground(new Color(0). yl).drawLine(p. np++.58 Do "rubber−band" drawing .height).id) { case Event. setForeground(new Color(0).y)).x. return true. y2 = e. i < np. } } } public void update(Graphics g) { // draw an offScreen drawing Dimension dim = getSize(). case Event. x2. return true.setColor(new Color(0). // begin an new drawing process x2 = −1.MOUSE_UP: // end a drawing process lines. offGra.x.height).dim. y1.addElement(new Rectangle(x1. p. dim. repaint(). y1. y1.drawLine(x1. yl = y2.setPaintMode().drawLine(x1.null). if (offGra == null) { offImg = createImage(dim. i++) { Rectangle p = (Rectangle)lines.

Color c = new Color(i.rgagnon.println("Color2Hex r g b"). repaint().. } else { int i = Integer.Dragupdate(getGraphics()).rgagnon. public class Color2Hex { public static void main( String[] args ) { if (args.parseInt(args[0]). Object o) { if (e./javadetails/java−0255.com/javadetails/. } } } 3.toHexString( c.59 Convert RGB value to Hexadecimal (to be used in HTML for example) Current version of this HowTo : http://www. if (e.handleEvent(e).. return true. } } 3.com/javadetails/. } public void undo() { if (np>0) { lines.html 3.parseInt(args[1]). } } public void resetDrawing() { lines.html import java. } public boolean action(Event e.60 Draw a line or set a pixel in my own image Current version of this HowTo : http://www.removeElementAt(np−1).59 Convert RGB value to Hexadecimal (to be used in HTML for example) .getRGB() &0x00ffffff ) ). } return super. int j = Integer. np−−.*. System.length != 3) { System.parseInt(args[2]).awt.k).target == btnClear) resetDrawing(). repaint(). return true.target == btnUndo) undo(). int k = Integer./javadetails/java−0250.j. np=0.out.println ( "hex: " + Integer.out.removeAllElements().

awt. counter++. } double linelength=Math. } public void setPixel (Image image.com/javadetails/.drawLine((int) (x1+xincdashspace*counter). y.getGraphics(). public void init() { int x = 100.dispose( ). double spacelength) { if((x1==x2){ g.i<linelength−dashlength. 1 ). import java. (int) (y1+yincdashspace*counter+yincdash)).int y2.drawLine((int) (x1+xincdashspace*counter). return.*.61 Draw a dashed line Current version of this HowTo : http://www. g. (int) (y1+yincdashspace*counter). new Color(0). import java.setColor( color ). g.x.y2).*. double xincdashspace=(x2−x1)/(linelength/(dashlength+spacelength)). } } 3. 50. 1. Graphics g = myImage.blue).drawLine(x1.sqrt((x2−x1)*(x2−x1)+(y2−y1)*(y2−y1)). 3. int y = 100. myImage = createImage(x. double dashlength.y1.awt.drawImage(myImage.*. double yincdash=(y2−y1)/(linelength/(dashlength)). Color color ) { Graphics g = image.drawLine(0.html public void drawDashedLine(Graphics g.image.int x2. double xincdash=(x2−x1)/(linelength/(dashlength)).int y1..0./javadetails/java−0224.y). i+=2){ setPixel(myImage. (int) (x1+xincdashspace*counter+xincdash). i <x.drawLine(x.fillRect( x. for(int i=0.i+=dashlength+spacelength){ g. double yincdashspace=(y2−y1)/(linelength/(dashlength+spacelength)).y). } } public void paint(Graphics g) { g.x2.import java.int x1.0. int y.0. int x. } if ((dashlength+spacelength)*counter<=linelength) g.0. for (double i=0.getGraphics( ). 50.y). public class CreateAnImage extends Applet { Image myImage.rgagnon.0. setPixel(myImage. g. new Color(0). int counter=0. i.this).green). g.61 Draw a dashed line . double yincrement=(y2−y1)/(linelength/(dashlength+spacelength)). g.applet. i.

5 : −0. getSize(). drawThickLine (g./javadetails/java−0260.. int y2. 0.width. dy.62 Draw a line with a thickness . getSize(). getSize(). import java.blue). 0. int xPoints[] = new int[4].height. // The double double ddx += ddy += int dx int dy x.. // line length double lineLength = Math. drawThickLine (g.. = (int)ddx.5 : −0.black). dy. Color c) { // The thick line is in fact a filled polygon g.green). = (int)ddy. new Color(0).html import java. int x1.width/2.height. int yPoints[] = new int[4].y increments from an endpoint needed to create a rectangle. (ddx > 0) ? 0.height. xPoints[0] xPoints[1] xPoints[2] xPoints[3] = = = = x1 x1 x2 x2 + − − + dx. getSize(). 0. 5. 12. (ddy > 0) ? 0.. double scale = (double)(thickness) / (2 * lineLength).*. dx. new Color(0).*. getSize(). getSize().awt.rgagnon. int dX = x2 − x1. ddy = scale * (double)dX.(int) (y1+yincdashspace*counter).width.applet. getSize(). yPoints[0] yPoints[1] yPoints[2] yPoints[3] = = = = y1 y1 y2 y2 + − − + dy.com/javadetails/.sqrt(dX * dX + dY * dY). getSize(). 8. int dY = y2 − y1. dx.y2).red). dy. } public void drawThickLine( Graphics g. 0.62 Draw a line with a thickness Current version of this HowTo : http://www.5. new Color(0). 0. ddx = −scale * (double)dY. } 3. int x2. 4). public class thickLine extends Applet { public void init( ) { } public void paint( Graphics g ) { drawThickLine (g. int thickness.fillPolygon(xPoints..width. } 3. // Now we can compute the corner points. new Color(0).setColor(c).height/2. 5. x2. g. yPoints. drawThickLine (g. int y1.width/2. getSize(). getSize().height/2.5. dx. 0.

3 import javax.add( panel. g2. } } class MyPanel extends JPanel { final static BasicStroke stroke = new BasicStroke(2.setStroke(new BasicStroke(width)). import java.draw(new Line2D.draw(new Line2D. getContentPane().0)). BasicStroke bs = new BasicStroke(width). "Center" ). } On a Component int width = 10. tl.*.0f). x2. 50.geom. Using JDK1.0.KEY_ANTIALIASING.0.100). public TestLine() { setSize(200.setVisible( true ).VALUE_ANTIALIAS_ON).drawLine(0. int width = 10.Double(10. l.0.setRenderingHint (RenderingHints. g2.0f).0.62 Draw a line with a thickness . 50. y2). } } 3.*. 200).*. 100. JLabel l = new JLabel().setStroke( stroke ). panel = new MyPanel().awt.swing. RenderingHints.drawLine(x1. g2.setStroke( wideStroke ).awt. g2d. import java. public MyPanel(){} public void paintComponent( Graphics g ){ Graphics2D g2 = (Graphics2D)g. 10. y1.setStroke(bs).0. 10. g2. 100. } public static void main( String [] args ){ TestLine tl = new TestLine().0.0. l. final static BasicStroke wideStroke = new BasicStroke(8.2 public void paint(Graphics g){ Graphics2D g2d = (Graphics2D)g.100.Double(10.getGraphics(). g2. public class TestLine extends JFrame{ private MyPanel panel. g2d.0)).} Using JDK1.

i)).blue).floatValue().63 Draw a pie chart . colors. public void init() { float value. Color.cyan). colors.green). } resize(c.intValue() : 20. setLayout(new BorderLayout()).put("blue".substring(0.put("magenta". colors. numSlices = 0. value[] = new float[10]. Color.valueOf(at). while (t.awt.put("pink". depth = (at != null) ? Integer.com/javadetails/. radius = (at != null) ? Integer. import java.addSlice(value. Color./javadetails/java−0261. colors. Color color[] = new Color[10]. radius. Color.black).pink).put("white". (Color)colors. i = s. Image gfxBuff. float total = 0.width. colors.indexOf('−'). c. import java. colors.substring(i + 1))).put("yellow".getMinimumSize(). String at = getParameter("width"). // Create Hashtable to map color name (String) to Color type Hashtable colors = new Hashtable().util. depth.")..html import java. Color. } } class PieChartCanvas extends Canvas { /* ** author Ciaran Treanor ciaran@broadcom. int i." StringTokenizer t = new StringTokenizer(at.get(s. Color. colors.put("orange".. Color. at = getParameter("depth").ie */ final double aspectFudge = 2.. PieChartCanvas c = new PieChartCanvas(radius. c).white).intValue() : 100.getMinimumSize().*. int radius. Color.put("red".Applet. colors. Color.put("green". depth).*.red).valueOf(s. public class Graph extends Applet { int depth.63 Draw a pie chart Current version of this HowTo : http://www.valueOf(at). colors. add("Center".put("black". Graphics offGraphics. called = 1.rgagnon. colors. ". c.nextToken().applet.put("cyan".5.3. // "value−color. value = Float.hasMoreTokens()) { s = t.yellow).orange).value−color. at = getParameter("values"). String s. Color.magenta). 3.height)..

offGraphics.depth = depth. null). } } [JavaPie.round(360 * (value[i] / total)). } } // draw the pie slice startAngle = −45.setColor(color[i]. } public void addSlice(float value. (int)(radius / aspectFudge). this. this. total += value. radius. i++) { offGraphics. offGraphics.radius = radius. (int)((radius / aspectFudge) + depth)). offGraphics = gfxBuff. x. (int)(radius / aspectFudge).public PieChartCanvas(int radius. this. i++) { offGraphics. if(gfxBuff == null) { gfxBuff = createImage(d.width. angle = Math.round(360 * (value[i] / total)). x >= 1.color = color. this. x−−) { startAngle = −45. offGraphics.fillArc(0. (int)angle). radius. angle = Math. } g.height). 0. } public void paint(Graphics g) { int startAngle. (int)angle).setColor(getBackground()).fillRect(0. 0.darker()). i < numSlices. for(int i = 0. d.value[numSlices] = value. startAngle += angle. Color color) { this.color[numSlices++] = color. int depth) { this. float angle. d.width. } public Dimension getPreferredSize() { return getMinimumSize(). i < numSlices. } // do the 3d effect for(int x = depth. Dimension d = getSize(). d.setColor(color[i]). 0. startAngle.class WIDTH=150 HEIGHT=150> 3.63 Draw a pie chart .hmtl] <HTML> <TABLE><TR><TD> <APPLET CODE=Graph.fillArc(0. startAngle += angle. startAngle. offGraphics.height). } public Dimension getMinimumSize() { return new Dimension(radius.value = value. for(int i = 0. 0.drawImage(gfxBuff.getGraphics().

because one of them is completely native.currentTimeMillis().130).awt.event.50). long t=System. g.0.<PARAM NAME="depth" VALUE="30"> <PARAM NAME="width" VALUE="120"> <PARAM NAME="values" VALUE="1−red. } t=System. c.currentTimeMillis()−t.10. import java. t=System.i<10000.7−blue"> </APPLET> <TD> <TABLE> <TR><TD>item 1<TD BGCOLOR="#FF0000"> <TR><TD>item 2<TD BGCOLOR="#008000"> <TR><TD>item 3<TD BGCOLOR="#0000FF"> </TABLE> </TABLE> </HMTL> Try it here 3.i++){ g.valueOf(t).70).5−green.drawString(String.200. } public static void main (String[] args){ Class1 c=new Class1().awt. for(int i=0.html Thanks to Chikirev Sergey It seems that drawRoundRect(…. c.10.drawRoundRect(10.100.setSize(300.paint(g).addActionListener(c).300).) .currentTimeMillis()−t. b.0). b).5 faster then drawRect(….show().drawRect(10.. Button b=new Button("Refresh").com/javadetails/.drawString(String.valueOf(t).130. for(int i=0.64 Draw faster rectangles . } } 3. public class Class1 extends Frame implements ActionListener{ public void paint(Graphics g){ super.SOUTH . import java.100..i<10000.*.) 1.currentTimeMillis(). c.add(BorderLayout. c.10. g. } public void actionPerformed(ActionEvent p1){ repaint(0.300).64 Draw faster rectangles Current version of this HowTo : http://www.rgagnon./javadetails/java−0364.i++){ g. } t=System.*.setLayout(new BorderLayout()).70.50.

getX(). java.write(screencapture.png"). } } To capture a specific area BufferedImage screencapture = new Robot()..BufferedImage.awt. javax.Robot.getScreenSize()) ).awt.getDefaultToolkit().65 Get a screen capture and save it as a JPEG .rgagnon. class ScreenCapture { public static void main(String args[]) throws AWTException.rgagnon.awt.awt.com/javadetails/.Toolkit.createScreenCapture( new Rectangle( 15. // Save as PNG // File file = new File("screencapture. // Save as JPEG File file = new File("screencapture.66 Display a TIF Current version of this HowTo : http://www.write(screencapture.html 3. // ImageIO. java.io..Robot. myframe.getY().Rectangle. file). To capture a specific visual object BufferedImage image = new Robot(). import import import import import import import java. "jpg". If you find this article useful. 15.AWTException.html The screen capture is done with java. 150.65 Get a screen capture and save it as a JPEG Current version of this HowTo : http://www. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 3.ImageIO. IOException { // capture the whole screen BufferedImage screencapture = new Robot(). myframe.*.3. java.getHeight() ) ). myframe./javadetails/java−0489.image.awt. ImageIO.imageio.getWidth().com/javadetails/. file).createScreenCapture( new Rectangle(Toolkit.createScreenCapture( new Rectangle( myframe./javadetails/java−0605. java. "png".jpg"). consider making a small donation to show your support for this Web site and its content. 150)). java.awt.

codec.getAsBufferedImage(). "c:/applications/sidebar.codec.ByteBuffer.media.allocate((int)channel. FileChannel channel = in.array()).JLabel.getChannel(). RenderedImage im = dec. java.awt.. com.length==0) { path = JOptionPane.channels.getDecoderNames(stream). you must use the JAI (Java Advanced Imaging) package.. new JLabel( new ImageIcon( imageScaled )) ). // JOptionPane.decodeAsRenderedImage(). java.nio.sun.media.media. // System. GIF. com.JOptionPane. ByteBuffer buffer = ByteBuffer. channel. BMP or PNG file with the package ImageIO.jai. −1.jai. return image.swing. String[] names = ImageCodec. "Image Path". image = PlanarImage.The regular JDK can only deal with JPG. stream. This example will display a given TIF file.awt.showInputDialog(null. java.RenderedImage.jai. SeekableStream stream = new ByteArraySeekableStream(data)..ImageDecoder. null).FileChannel. } FileInputStream in = new FileInputStream(path).nio. ImageDecoder dec = ImageCodec. import javax.wrapRenderedImage(im).io.read(buffer).swing. com.65 Get a screen capture and save it as a JPEG .out. } else { path = args[0].ImageCodec. // make sure that the image is not too big // scale with a width of 500 Image imageScaled = image.SeekableStream. if (args. To deal with TIF file.createImageDecoder(names[0].jai.media. It will also display other types (JPG.SCALE_SMOOTH). com.getScaledInstance(500. Image. public class ImageViewer { static Image load(byte[] data) throws Exception{ Image image = null.ByteArraySeekableStream. see this HowTo.ImageIcon.size()).Image.println("image: " + path + "\n" + image).swing.sun.) by detecting the type. java. } } 3. import javax.media.PlanarImage.FileInputStream. import javax.sun.sun. java. Image image = load(buffer.showMessageDialog(null. import import import import import import import import import import javax. } public static void main(String[] args) throws Exception{ String path.codec.image.codec.jai.tif").

including photographs and line art.codec.jai. ss. TIFFEncodeParam param = new TIFFEncodeParam().setCompression(TIFFEncodeParam. rather than have each company promulgate its own proprietary format. // Intel System.getCanonicalPath()).media.sun. com.com/products/java−media/jai/index.html Tagged Image File Format (abbreviated TIFF) is a file format for mainly storing images.renderable.com/javadetails/. null).media.media. see this HowTo 3.jai. java. This is done with the JAI (Java Advance Image) package. File f = new File("d:/single_" + i + ".io. i < count.setLittleEndian(false). TIFF was originally created as an attempt to get desktop scanner vendors of the mid−1980's to agree on a common scanned image file format.sun.ImageDecoder.67 Convert a multi−page TIF into single−page TIF Current version of this HowTo : http://www./javadetails/java−0535.codec. System. ImageDecoder dec = ImageCodec.createImageDecoder("tiff".jai.java.media.println("Saving " + f.RenderedOp.FileSeekableStream.tif"). param.media.tif"). public class TestTiff { public static void main(String[] args) throws IOException { new TestTiff().sun.decodeAsRenderedImage(i).codec.rgagnon.doitJAI().jai.media.image.jar and jai_codec.sun. } public void doitJAI() throws IOException { FileSeekableStream ss = new FileSeekableStream("d:/multi. com.net/#Downloads To write a TIF file.image.The JAI package is composed of 2 jars : jai_core.sun. int count = dec.jai. param. javax. java.out.getNumPages().67 Convert a multi−page TIF into single−page TIF ..dev.JAI.RenderedImage. import import import import import import import import com. http://java.awt.jar http://java.TIFFEncodeParam.println("This TIF has " + count + " image(s)"). javax. This HowTo takes a multi−page TIF (from a FAX) and convert it into many single−pages TIF.*.out.jsp > import java.COMPRESSION_GROUP4). com.jai. for (int i = 0.com/javase/technologies/desktop/media/jai/ https://jai.ParameterBlock. i++) { RenderedImage page = dec.sun.ImageCodec.codec.awt. 3.

RenderedOp r = JAI. You may want to consider to use an external utility to do this kind on conversion. A nice one is irfanview (win)./javadetails/java−0601. Written and compiled by Réal Gagnon ©1998−2006 [ home ] 3. 0.tif) /killmesoftly irfanview is an amazing software when it comes to transform a graphic format to another one.awt. pb. } 3. use this command line : C:\IrfanView\i_view32" d:\multi.imageio.add("tiff").im.toString()). bg.TYPE_INT_RGB). If you find this article useful.*. public class ImageUtils { public static BufferedImage imageToBufferedImage(Image im) { BufferedImage bi = new BufferedImage (im. javax.addSource(page).dispose().irfanview.*.*.getHeight(null).pb)..68 Convert an Image to a BufferedImage Current version of this HowTo : http://www. r. return bi.tif /extract=(d:\.html import import import import java.create("filestore". consider making a small donation to show your support for this Web site and its content.drawImage(im.BufferedImage. java.image.com/javadetails/. bg.io.68 Convert an Image to a BufferedImage .add(f. 0.rgagnon.getGraphics(). Graphics bg = bi.*. pb. pb. http://www. You can use it from a command line or from a GUI.add(param).read(file).com/ To do a TIF conversion. pb. } } } This solution is working but JAI is a slow performer. } public static BufferedImage readImageFromFile(File file) throws IOException { return ImageIO. java.awt.getWidth(null).ParameterBlock pb = new ParameterBlock().dispose(). a (free) multi−purpose graphic utility. null).

write(bufferedImage.com/javadetails/."png". // last mouse down time int lastX=0. 3.lastY=0.when−timeMouseDown) < dClkRes)) { System. } return true. timeMouseDown = event.println("double click " + currentTime). // double−click speed in ms long timeMouseDown=0. But since BufferedImage extends Image. public class d extends Applet { int dClkRes = 300. // last x and y public boolean mouseDown(Event event. lastX=x.html [JDK1.rgagnon.public static void writeImageToPNG (File file./javadetails/java−0235.out.when.println("simple click " + currentTime). int x. lastY=y. return false. if ((lastX==x) &(lastY==y) & ((event. import java..02] import java. int y){ /* ** check for double click */ long currentTime = event.awt. it's not needed. so there isn't a back−conversion.*.out.when.BufferedImage bufferedImage) throws IOException { ImageIO. } else { //single click action could be added here System.file).BufferedImage bufferedImage) throws IOException { ImageIO.write(bufferedImage. } } [JDK11] 3. } public static void writeImageToJPG (File file.file).applet."jpg". } } You need to do something to transform an Image to BufferedImage.69 Detect a double click vs simple click Current version of this HowTo : http://www.*.69 Detect a double click vs simple click .

import java. break.getX() + ":" + e. } public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseClicked(MouseEvent e) { System. if (e.event.applet.*.event.10).*.html [JDK11] import java. } public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseClicked(MouseEvent e) { switch(e.*.getClickCount() == 2) System.awt.println ( "Click at (" + e.awt. public class d extends Applet implements MouseListener { public void init() { this. import java. 10.getModifiers()) { case InputEvent.import java.awt.println("That's the LEFT button").println( " and it's a simple click!"). } } 3. } public void paint(Graphics g) { g.drawString("Click here".out.BUTTON1_MASK: { System.applet.*. import java.70 Detect the mouse button used when clicking .com/javadetails/.drawString("Click here". 3. 10.rgagnon.awt..70 Detect the mouse button used when clicking Current version of this HowTo : http://www. } public void paint(Graphics g) { g.out.10).println( " and it's a double click!").addMouseListener(this).addMouseListener(this).getY() + ")" )./javadetails/java−0236. public class d extends Applet implements MouseListener { public void init() { this. import java.*. else System.out.*.out.

} case InputEvent. System. break. new MenuShortcut(KeyEvent.VK_X))). show().add(m). addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { // unique exit point System. } } } } 3.add(new MenuItem("Exit". setSize(300. add(new Label ("You can quit by clicking on the menu item 'Exit'"). setMenuBar(mb).println("That's the RIGHT button"). ExitFromMenu() { super(""). WindowEvent.*. break."Center"). import java.getActionCommand(). } public void actionPerformed(ActionEvent evt) { String what = evt.println("Bye.println("That's the MIDDLE button").awt. MenuItem m1 = m.setActionCommand("Exit").awt.exit(0)./javadetails/java−0276. add(new Label ("You can quit by clicking on the 'X'").*.out.addActionListener(this). } } ). MenuBar mb = new MenuBar(). 300). add(new Label ("You can quit with the MenuShortcut 'ctrl−x'").")."North"). 3.71 Exit an application from a menu .out.rgagnon.."South"). if (what. m1.BUTTON3_MASK: { System. m.out.} case InputEvent.WINDOW_CLOSING)).event. mb. public class ExitFromMenu extends Frame implements ActionListener { Menu m = new Menu("Exit From Here").equals("Exit")) processEvent(new WindowEvent(this.71 Exit an application from a menu Current version of this HowTo : http://www.BUTTON2_MASK: { System.com/javadetails/.html import java.

*. import java. } if (e.addActionListener(this). add(b2). b1 = new Button("Output"). public void init() { setLayout(new FlowLayout()). import java.getSource() == b1) { t1. t1 = new TextField(30).awt.*.*.*. } public void actionPerformed(ActionEvent e) { if (e. } } } With Swing (japplet) import java.dispatchEvent(ae). ActionEvent.ACTION_PERFORMED. we trigger the action attached to the another Button. Toolkit.72 Trigger a click on a Button .postEvent(ae). public class TestEvent extends Applet implements ActionListener { Button b2. we creating an event to trigger a click // on the b1 button ActionEvent ae = new ActionEvent((Object)b1.awt.com/javadetails/.rgagnon.addActionListener(this).event..getSource() == b2) { // from the b2 button. import javax.awt. import java.72 Trigger a click on a Button Current version of this HowTo : http://www.html In this example.} static public void main(String[] args) { new ExitFromMenu(). when we click on a Button.event.swing. add(t1). Regular AWT (applet) import java. ""). } } 3. b2. b1. b2 = new Button("Fire event 1st button"). can be used too. TextField t1.setText("1st button clicked").awt. public class TestEventSwing extends JApplet implements ActionListener { 3.getDefaultToolkit().applet.*. b1.getSystemEventQueue(). // b1.*./javadetails/java−0468. add(b1).

t1 = new JTextField(30). b1. } } } Written and compiled Réal Gagnon ©2007 real@rgagnon. b2.addActionListener(this). b2. } if (e.rgagnon.72 Trigger a click on a Button . we trigger a click on the b1 button.getSource() == b2) { // from the b2 button.getSource() == b1) { t1. b1 = new JButton("Output"). // As an added bonus.JButton b1.addActionListener(this).setText("first button clicked").com http://www.doClick().com 3. add(t1). we have visual effect on b1! b1. } public void actionPerformed(ActionEvent e) { if (e. JTextField t1. add(b2). b2 = new JButton("Fire event 1st button"). add(b1). public void init() { setLayout(new FlowLayout()).

indexOf("windows 9") > −1) { p = r. One approach (not the easiest one). is to use a JNI call to fetch the variables. Properties envVars = new Properties().exec( "cmd.2 Read environment variables from an application Current version of this HowTo : http://www.toLowerCase(). JDK up to 1.com /c set" ).indexOf("windows xp") > −1) ) { // thanks to JuanFran for the xp fix! p = r. see this HowTo.5 or better provides a simpler way to achieve this.4 Environment 4. the name of the variable to be passed to the JVM.name").getRuntime(). import java. see this HowTo. if (OS.indexOf("nt") > −1) || (OS. Runtime r = Runtime.getProperty() method. String myothervar = System..*.io.getProperty("myothervar").println(OS).com/javadetails/. import java. } else if ( (OS. } else { 4 Environment . is to launch the appropriate call to the operating system and capture the output. The following snippet puts all environment variables in a Properties class and display the value the TEMP variable. // System./javadetails/java−0150.util.getProperty("myvar"). public class ReadEnv { public static Properties getEnvVars() throws Throwable { Process p = null. String OS = System.*.indexOf("windows 2000") > −1 ) || (OS.rgagnon. A more low−tech way. then there is no 100% Java way to retrieve them.html NOTE: JDK1. SET myvar=Hello world SET myothervar=nothing java −Dmyvar="%myvar%" −Dmyothervar="%myothervar%" myClass then in myClass String myvar = System.exec( "command. If you don't know in advance.4 Start the JVM with the "−D" switch to pass properties to the application and read them with the System.exe /c set" ).out.1 java−env 4.getProperty("os.

indexOf( '=' ). } public static void main(String args[]) { try { Properties p = ReadEnv." So either that has to be added to the bunch of tests or just relax the comparison strings a bit: else if ( (OS.indexOf("windows xp") > −1) ) { // ok // but specific to 2003 else if ( (OS.getInputStream() ) )." I suppose. we assume Unix (thanks to H. value ). String line. String value = line.substring( idx+1 ). instead of calling directly the SET command. while( (line = br. after the SET command we print a known string.getProperty("TEMP")).substring( 0. System. The only thing to watch out for is to not overlap with "windows 9. the property value for "os. pre−JDK 1. Then. First.out." On Windows. } catch (Throwable e) { e.out.// our last hope.indexOf("windows 2000") > −1 ) || (OS. // since no other OS would // return "windows" || (OS.name" is actually "windows 2003. when we read this known string.indexOf("windows 20") > −1 ) // better.getEnvVars().indexOf("nt") > −1) || (OS. An update from Van Ly : I found that.println( key + " = " + value ).exec( "env" ).setProperty( key. idx ).rijnders for the w2k fix.printStackTrace(). it never returns. } } } thanks to w.readLine()) != null ) { int idx = line.indexOf("windows xp") > −1) ) { I started with "windows 200" but thought "what the hell" and made it "windows 20" to lengthen its longivity. String key = line.2 JVM has trouble reading the Output stream directly from the SET command. You could push it further and use "windows 2. 4 Environment . we exit from loop. } return envVars. on Windows 2003 server. we use a BAT file. // System.indexOf("nt") > −1) || (OS. in Java. envVars.println("the current value of TEMP is : " + p.indexOf("windows 2003") > −1 ) || (OS. Ware for the fix) p = r. Here 2 ways to bypass this behaviour. } BufferedReader br = new BufferedReader ( new InputStreamReader( p.

value ).indexOf("windows") > −1) { p = r. the TEMP and PATH environment variables (on Windows). if (OS.get("MYENV_VAR"). To read only one variable : // NT version .bat" ).. } Properties env = getEnvironment()...IOException { Properties env = new Properties().exe /c echo %MYVAR%"). BufferedReader br = new BufferedReader ( new InputStreamReader( p.load(new FileInputStream("envvar. hash.exec("env").exec("cmd. Java's System properties contains some useful informations about the environment. return env. .. while( (line = br.indexOf("nt") > −1) || (OS.exec( "cmd.readLine(). String value = line.getRuntime(). Thanks to JP Daviau // UNIX public Properties getEnvironment() throws java. if (OS.println(myvar). adaptation for other OS is left as an exercise..load(Runtime. } .getRuntime().getInputStream() ) )..exec( "env. Process p = Runtime.io.indexOf("windows 9") > −1) { p = r. String key = line. idx ). } The other solution is to send the result of the SET command to file and then read the file from Java. } .indexOf("**end")>−1) break.. p.bat] @set @echo **end [java] .txt")). String myEnvVar = env.txt" ).substring( 0.println( key + " = " + value )..indexOf("windows xp") > −1) ) { // thanks to JuanFran for the xp fix! p = r.[env.substring( idx+1 ). for example.exe /c set > envvar.put( key. String myvar = br.com /c set > envvar. System.out. int idx = line.readLine()) != null ) { if (line. System. // then read back the file Properties p = new Properties().getInputStream()). env.txt" )..indexOf("windows 2000") > −1 || (OS..indexOf( '=' ). public class ShowSome { 4 Environment .exec( "command. } else if ( (OS.out.

System.d:\cfn\bin. // ex.D:\orant\bin.d:\cfn\bin. Ware about the PATH on different OS.println("TEMP : " + System. (java added all those except /lib and /usr/lib).path")).2\bin..D:\jdk1.println("the current value of PATH is: p. d:\Program Files\Symantec\pcAnywhere. In unixes.} LIBPATH: {/usr/lib/j2re1.out.println("PATH : " + System. d:\Program Files\Symantec\pcAnywhere. C:\Program Files\Executive Software\DiskeeperServer\..3/lib/i386:/usr/lib:/lib} on my linux workstation.path")).d:\OrbixWeb3.D:\Program Files\IBM\GSK\lib. } } Here some tips from H.2\bin.public static void main(String args[]){ System.D:\jdk1.library. they are completely different−−−the libraries typically have their own directories.dir")).C:\WINNT\system32.println("SYSTEM DIR : " + System.println("CURRENT DIR: " + System.getProperty("java.c:\depot\cdk\main\cdk\bin.path")+"}").3/lib/i386:/usr/lib/j2re1.class.out.c:\depot\cdk\main\cdk\. {" + gives the current value of PATH is: {/home/hware/bin:/usr/local/bin:/usr/xpg4/bin:/opt/SUNWspro/bin: /usr/ucb:/bin:/usr/bin:/home/hware/linux−bin:/usr/openwin/bin/: /usr/local/games:/usr/ccs/lib/:/usr/new:/usr/sbin/:/sbin/: /usr/openwin/lib:/usr/X11/bin:/usr/bin/X11/:/usr/local/bin/X11: /usr/bin/pbmplus:/usr/etc/:/usr/dt/bin/:/usr/lib: /usr/lib/nis:/usr/share/bin:/usr/share/bin/X11: /home/hware/work/cdk/main/cdk/.\bin.\bin.} LIBPATH: {D:\jdk1. H:\pvcs65\VM\win32\bin. System.. 4 Environment .C:\Program Files\Dell\OpenManage\ResolutionAssistant\Common\bin. C:\WINNT.out.c:\depot\ cdk\main\cdk\. PATH is not quite the same as library path. C:\WINNT\system32..println("LIBPATH: {" + System.home")).C:\WINNT.out.3/lib/i386/client:/usr/lib/j2sdk1.c:\cygnus\cygwin−b20\H−i586−cygwin32\bin.c:\cygnus \cygwin−b20\H−i586−cygwin32\bin.C:\WINNT\System32. c:\depot\cdk\main\cdk\bin. But these two lines aren't the same on window either: This system is windows nt the current value of PATH is: {d:\OrbixWeb3.getProperty("java.3\bin..getProperty("PATH")+"}").out.getProperty("java.library. c:\windows on Win9x System.println("CLASSPATH : " + System.getProperty("user.2\bin.getProperty("user.H:\pvcs65\VM\win32\bin.getProperty("java.io.C:\WINNT. System. d:\OrbixWeb3.out.3\bin.3\bin./bin:.tmpdir")).out.D:\Program Files\IBM\GSK\lib. System. D:\orant\bin.3/lib/i386/native_threads: /usr/lib/j2re1. System.

consider making a small donation to show your support for this Web site and its content.com/javadetails/. you can use −D switch to retrieve named environment variable and pass them to the JVM (see this HowTo) or use this JNI routine : JNIEXPORT jstring JNICALL JavaHowTo_getenv (JNIEnv *env. the getenv() method was removed from the JDK.C:\Program Files\Executive Software\DiskeeperServer\. jclass c..5) .println("PATH = " + System. public class Test { public static void main(String args[]) { // just one System. ) { Map. But for now. System. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 4.com/javadetails/.*. See this Howto for common XP environment variables If you find this article useful. } } } See also this HowTo.3 Retrieve environment variables (JDK1.rgagnon.5) Current version of this HowTo : http://www. } const char *name = (*env)−>GetStringUTFChars(env.4 Retrieve environment variable (JNI) Current version of this HowTo : http://www.println(entry.rgagnon./javadetails/java−0466. 4. jname.Entry)it.Entry entry = (Map./javadetails/java−0460.getenv("PATH")).html For some odd reasons.5 System.5 (see this HowTo).} Java is prepending itself! That confused me−−− and broke my exec from ant.iterator(). // all of them Map env = System.getenv() is back! import java.html JDK1. for (Iterator it=env. it.util. Rumors is that a mechanism to retrieve an environment will be back in JDK1. jstring jname){ if ( jname == NULL ) { return NULL . 4. (jboolean *)NULL) .out.next().getenv().hasNext().3 Retrieve environment variables (JDK1.out.getValue()).entrySet().getKey() + " = " + entry..

/javadetails/java−0158.class SOURCEFILES = GetImage.3 JAVAC= $(JAVAHOME)\bin\javac PATH=$(JAVAHOME)\bin.com/javadetails/.class \ myCanvas.jar $(JARFILE): $(CLASSFILES) $(SOURCEFILES) jar cfm0 $(JARFILE) <<manifest.tmp $(DATAFILES) Name: GetImage.5 Use a MAKE file Current version of this HowTo : http://www. See also this HowTo.java # begin −−−− JAR support −−−−−−−−−− JARFILE= theJAR.class .$(JSDKHOME)\lib\classes.$(JAVAHOME)\lib\classes.. (*env)−>ReleaseStringUTFChars(env.zip.class Java−Bean: True << $(CLASSFILES) 4. consider making a small donation to show your support for this Web site and its content.class Java−Bean: False Name: myCanvas. jname.java.mak doc # to generate JAVADOC . return value ? (*env)−>NewStringUTF(env. } NOTE : This is fine if the environment variable contains only regular 7−bit ASCII characters.const char *value = getenv(name) ..zip DEST=.html # jMAKEFILE a MAKEFILE for JAVA development # (Microsoft nMAKE) # nmake /f j.java JAVAHOME=c:\windev\jdk1.$(PATH) CLASSPATH=.makefile. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 4.1.class: $(JAVAC) −classpath $(CLASSPATH) $(JAVACFLAGS) $< CLASSFILES = GetImage.class . If you find this article useful.SUFFIXES: . value) : NULL .SUFFIXES: .rgagnon.java . JAVA=$(JAVAHOME)\bin\java JAVACFLAGS=−deprecation .java \ myCanvas.5 Use a MAKE file . name) . DOC=.

} return true.ms.6 Detect the browser/JVM type . 4. } catch (ClassNotFoundException e) { System.").AppletViewer")) theBrowser = "APPLETVIEWER". if (appletContext.println("This browser is a Microsoft Browser.toString()./javadetails/java−0160.rgagnon.forName("netscape.MozillaAppletContext").").println("This browser is not a Microsoft Browser.out.out. return false.applet. } catch (ClassNotFoundException e) { System.").applet.. } return true.GenericAppletContext"). String appletContext = getAppletContext().html One way is to instanciate a known browser−specific method and catch the Exception if not found import java.6 Detect the browser/JVM type Current version of this HowTo : http://www. } public static boolean isNetscape() { try { Class.# end −−−− JAR support −−−−−−−−−− all : $(JARFILE) $(CLASSFILES) doc doc : $(CLASSFILES) javadoc −version −author −d $(DOC) $(SOURCEFILES) install : copy $CLASSESFILE $(DEST) clean: del $(CLASSFILES) 4.com/javadetails/. } public static boolean isMicrosoft() { try { Class.println("This browser is a Netscape Browser. return false.").forName("com. public class BrowserDetector extends Applet { public void init() { if ( isNetscape() ) System.startsWith("sun.out. } } Or by examining the string representation of the getAppletContext() method String theBrowser = "APPLICATION".println("This browser is not a Netscape Browser.out.*.applet.applet. if ( isMicrosoft() ) System.

6 Detect the browser/JVM type .AppletPlugin")) theBrowser = "NETSCAPEPLUGIN".windows.applet. if (isBrowser("Microsoft".startsWith( "com.hotjava.viewer.startsWith("sunw. The idea is to put all the required classes in an ARCHIVE file.plugin. versionOk = false.startsWith( "sun.v) { browserOk = false.jar". <HTML></HTML><HEAD> <SCRIPT> function isBrowser(b.jar".win32.plugin.WToolkit")) theJVM = "JVIEW".ms.equals("APPLICATION") { if (toolkit.toString().applet. } else { if isBrowser("Netscape".startsWith ( "sun.plugin.appVersion)). else if (appletContext.getDefaultToolkit().class" HEIGHT=100 WIDTH=400 ARCHIVE=}.awt.ocx.ActiveXApplet")) theBrowser = "MICROSOFTPLUGIN. 4) { archiveToBeUsed = "n4. During layout time.tags.awt. else if (toolkit. } For example. we detect the JVM type String theJVM = "".startsWith("com. } archiveToBeUsed = "java102. > </APPLET> </BODY></HTML> 4.4. 4)) { archiveToBeUsed = "ie4. By using a javascript entities. For an application.IExplorerAppletContext") theBrowser = "MICROSOFTPLUGINJRE1. the javascript entity is remplaced by the right archive name.WToolkit")) theJVM = "JAVA". else if (appletContext. our MyApplet.")) theBrowser = "MICROSOFT".appName.jar". else if (appletContext. the other is a JDK1. else if (appletContext.else if (appletContext. } } </SCRIPT></HEAD><BODY> <APPLET CODE ="MyApplet. else if (appletContext.ms. browserOk = (navigator.indexOf(b) != −1).TagAppletPanel")) theBrowser = "HOTJAVA".1 applet and finally a version for JDK102−only browser.navig. if (theBrowser.context. String toolkit = Toolkit. return browserOk &versionOk. versionOk = (v <= parseInt(navigator.")) theBrowser = "NETSCAPE".startsWith( "sun. by looking at the string representation of the getDefaultToolkit() method.class exists in three versions. we decide which archive to use.startsWith("netscape. One is using Microsoft−specific classes.startsWith( "sun.

This is used by the browser JVM as a quick check of whether the called file is really a Java class.200).com/javadetails/.html The "magic number" is represented by the first few bytes of a given file.10 Ant For simple need. //@ENDDEBUG@// f. the magic number is 0xCAFEBABE (you can verify this by viewing a class file with hexadecimal editor or the DOS Debug utility). public class Example { public static void main(String args[]){ JFrame f = new JFrame(). package com.rgagnon. f.rgagnon.html 4.getTitle() + " DEBUG version").com/javadetails/.setVisible(true). It is used to identified the file type.9 Open source packages Check this list of what is available. f. //@STARTDEBUG@// f.JFrame. 4.setTitle("HowTo"). If the message is displayed and you are sure that you have uploaded a "real" class to web server then it's probably because the FTP download has been done in TEXT mode instead of BINARY so the resulting file on the server is corrupted.EXIT_ON_CLOSE)..7 Fix the "Wrong magic number" error message Current version of this HowTo : http://www. 4. 4. Ant can be used to do substitution in your sources. Let's say we use //@STARTDEBUG@// and //@ENDDEBUG@//.setSize(300. We insert into the code a special tag to delimit code that need to be stripped by the Ant script.rgagnon./javadetails/java−0163. f.NOTE: You may need to use the document.swing.howto.7 Fix the "Wrong magic number" error message .write() method to generate the right APPLET tag instead of a the Javascript entity to be compatible with Netscape and IE..setDefaultCloseOperation(JFrame./javadetails/java−0164. import javax. For Java classes.setTitle(f. Also take a look at JEnable 4.8 Use a precompiler "à la C" with Java Current version of this HowTo : http://www.

.JFrame. This technique relies on the compiler optimization which remove code in the bytecode generated because it will never be executed.setTitle("HowTo"). f./out" /> </target> <target name="compiledebug"> <javac srcdir="..setVisible(true). */ f.200). the source (in the . The Ant script to remove the debugging code is : <project default="buildme"> <target name="compileprod"> <copy todir=".howto.11 Simple boolean flag See this HowTo.setDefaultCloseOperation(JFrame.\out directory) package com. f..setSize(300.} } If you execute this code. public class Example { public static void main(String args[]){ JFrame f = new JFrame().getTitle() + " DEBUG version"). /* f. the JFrame title will have the word "DEBUG" appended to it. import javax."> <include name="**/*.swing.setTitle(f. 4." /> </target> <target name="buildme" depends="compileprod" /> </project> After running this script. f.EXIT_ON_CLOSE).11 Simple boolean flag . } } 4.rgagnon.java" /> </fileset> </copy> <javac srcdir="./out" includeEmptyDirs="false"> <filterchain> <tokenfilter> <replacestring from="//@STARTDEBUG@//" to="/*" /> <replacestring from="//@ENDDEBUG@//" to="*/" /> </tokenfilter> </filterchain> <fileset dir=".

jar in the lib directory contains the resource bundle standard.com/javadetails/. The default is 1Mb.properties used by Javadoc to generated the labels.rgagnon.12 Determine what are the classes actually used in a Java Applet or application . If your program allocates a lot of memory.. 4.13 Set the memory available to the JVM Current version of this HowTo : http://www.rgagnon.com/javadetails/. Execute your applet. Press "9" to set the Debug level 3. the JVM will use up to 16Mb of RAM.html By default.2..4. appending "m" to n will specified the number in megabytes./javadetails/java−0165./javadetails/java−0131. Open the Java console 2. appending "m" to n will specified the number in megabytes. you may need to increase this value to give more room to the garbage collector.14 Generate the Javadoc "en français" Current version of this HowTo : http://www. two parameters can be adjusted to suit your memory needs : −mx n Sets the maximum size of the memory allocation pool where n is in bytes. you need to create the appropriate resource bundle. 4. With JDK1. Check the console and take note of the loaded classes. that syntax have changed.. In application java −verbose:class MyApp NOTE: This can be useful if you want to trim a JAR to include only classes actually used./javadetails/java−0437.com/javadetails/.rgagnon.html In Netscape 1. To add a new language.12 Determine what are the classes actually used in a Java Applet or application Current version of this HowTo : http://www. no space between ms/mx and the value : java −mx20m myApp 4. The tools. in our case for 4. for example to set the maximum at 20Mb : java −mx 20m myApp −ms n Sets the startup size of the memory allocation pool. When starting the JVM. where n is in bytes.html The javadoc utility uses the regular Java mechanism to internationalize its output.

tools.12 Determine what are the classes actually used in a Java Applet or application .jar.tools..Packages=Packages doclet.Generated_Docs_Untitled=Generated Documentation (Untitled) [standard_fr.java" destdir="javadoc/Client" author="true" version="true" use="true" private="true" windowtitle="Client"> <doctitle><![CDATA[<h1>Client</h1>]]></doctitle> <bottom><![CDATA[<i>Copyright &#169. The new file must be in the package com. Extract from tools. the standard.properties files (keep the directory structure).. 2003 Real's Howto.Warn_inline_taglet=Inline tag {0} should only be used with a {1}. Translate it (or you can download my "incomplete" version here).Window_Split_Index={0}\: {1}−Index doclet. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 4. doclet.sun.Packages=Paquetages doclet. we need a file called standard_fr.ClassUse_Subinterface=Subinterfaces of {0} in {1} doclet.jar making sure that the file is located in the right package (along standard.properties (extract)] doclet. use the −locale switch on the command line javadoc −locale fr .Since=Depuis\: doclet.ClassUse_Subinterface=Sous−interfaces de {0} dans {1} doclet.properties. put your standard_fr. NOTE : Make sure the −locale switch is the first one.doclets.resources).french.SerialData=Serial Data\: doclet.Since=Since\: doclet. To generate in french.standard.SerialData=Donn\u00E9e s\u00E9rialis\u00E9e\: doclet.Warn_inline_taglet=Inline tag {0} should only be used with a {1}. doclet.properties (extract)] doclet. consider making a small donation to show your support for this Web site and its content. Using Ant.properties.Window_Split_Index={0}\: {1}−Index doclet.properties in com.sun.resources.properties into the tools.standard.. [standard. Copy it under the name standard_fr.Generated_Docs_Untitled=Documentation g\u00E9n\u00E9r\u00E9e Once everything translated.doclets. <javadoc locale="fr" sourcefiles="c:/client/Client.Frame_Version=Version avec cadres doclet.</i>]]></bottom> </javadoc> If you find this article useful.Frame_Version=Frame version doclet.

15 Use JDK1.com/javadetails/.5. } } • Compile it (again you may need to specify the complete path to the compiler if the PATH is not set correctly): "c:\program files\java\j2sdk1.Calendar.html The first 4 bytes are a magic number.5 new features Current version of this HowTo : http://www. to identify a valid class file then the next 2 bytes identify the class format version (major and minor).5". 0xCAFEBABe. Possible major/minor value : 4.0−beta−b32c) JAVA HOTSPOT(TM) CLIENT VM (BUILD 1.printf()).5 new features .rgagnon./javadetails/java−0544.5 and install it. args) { System.16 Check the class version Current version of this HowTo : http://www..5./javadetails/java−0462.5.printf("Local time: %tT".0−beta" Java(TM) 2 Runtime Environment.5.5.5 Test15..0\bin\javac" −source 1.getInstance()). MIXED MODE) On Windows. Do it again but with the complete path (if the path contains spaces. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 4.com/javadetails/.. • Run it >"C:\Program Files\Java\j2sdk1.out.15 Use JDK1.out.0−BETA−B32C. Standard Edition (build 1.4. it's because the JVM can't be found through the PATH.0\bin\java" −version • Let's do our first jdk1. consider making a small donation to show your support for this Web site and its content.rgagnon.0\bin\java" Test15 Local time: 15:26:04 If you find this article useful.5 program : public class Test15 { public static void main(String . make sure to use quotes!) : "c:\program files\java\j2sdk1. type java −version The response should be something like java version "1.html • Download the JDK1. if you don't specify it you won't be able to access the new features (like System. • From a shell. java. if you have a "file not found" message.5.util.java Note the switch "−source 1..

Thus.4 0 1.length.0 v Mj.. a major and a minor version number determine the version of the class file format. Only Sun can specify what range of versions a Java virtual machine implementation conforming to a certain release level of the Java platform may support.3 0 1. If a class file has major version number M and minor version number m. it has the value 0xCAFEBABE.2 0 1.0 < 2. 0 from The Java Virtual Machine Specification magic The magic item supplies the magic number identifying the class file format. public class ClassVersionChecker { public static void main(String[] args) throws IOException { for (int i = 0. } private static void checkClassVersion(String filename) throws IOException { DataInputStream in = new DataInputStream (new FileInputStream(filename)).m. if(magic != 0xcafebabe) { System.major 45 45 46 47 48 49 50 minor Java platform version 3 1.println(filename + " is not a valid class!").out.6 import java.class ClassVersionChecker.m. " + minor).out.close(). } } > java ClassVersionChecker ClassVersionChecker. for example.1.readInt(). in. i < args. } int minor = in.class: 49 . minor_version.5 new features .Together.15 Use JDK1.5 < 2. i++) checkClassVersion(args[i]).println(filename + ": " + major + " . major_version The values of the minor_version and major_version items are the minor and major version numbers of this class file.1 0 1.5 0 1.readUnsignedShort(). A Java virtual machine implementation can support a class file format of version v if and only if v lies in some contiguous range Mi.*. we denote the version of its class file format as M. int major = in.0 3 1. class file format versions may be ordered lexicographically.io.readUnsignedShort(). 1. int magic = in. System. 4.

System.println("CLASSPATH:\n" + mx. x.com/javadetails/. // a map of names and values of all system properties.out. } catch (Exception e) { e.html The RuntimeMXBean defines several convenient methods for accessing system properties about the Java virtual machine.printStackTrace().getProperty("sun. System. System..getUptime() + " ms").equals("?") { // probably sun.5] import java.out. System./javadetails/java−0549.lang. [J2SE 1. System.println("VM start time : " + new Date(mx.println("VM up time : " + mx. } if (bits. import java.model".model isn't available // maybe not a Sun JVM? // try with the vm.html public static boolean is64BitVM() { String bits = System.println("BOOTCLASSPATH:\n" + mx.getRuntimeMXBean()..equals("64") { return true.getStartTime())).Date.arch.rgagnon.com/javadetails/.out.data.17 Get the system properties or the JVM uptime Current version of this HowTo : http://www.util.out. import java.management.getBootClassPath())./javadetails/java−0565.getSystemProperties()).name property 4. } } } 4. class JMXTest { public static void main(String args[]) { JMXTest x = new JMXTest().ManagementFactory.out.println("SYSTEM PROPERTIES:\n" + mx.rgagnon.17 Get the system properties or the JVM uptime .RuntimeMXBean. } public void doit() { try{ RuntimeMXBean mx = ManagementFactory. System.println("COMMAND LINE ARGS:\n" + mx.getInputArguments()). // the input arguments passed to the Java virtual machine // which does not include the arguments to the main method.lang.out.arch.18 Detect if running in a 64bit JVM Current version of this HowTo : http://www. "?").getClassPath()). if (bits.doit().4.data.management.

you'll need to download the SDK to get both systems.return System. What's the difference between the −client and −server systems? These two systems are different binaries. For 64−bit. sharing) The default JVM with a JIT (Just−In−Time compiler) for a "client" mode is used. In general the client system is better suited for interactive applications such as GUIs.vm. and inlining policy.5.19 Set the default JVM type Current version of this HowTo : http://www. The default setting is defined the file jvm.5.rgagnon.5.0−b64) Java HotSpot(TM) Client VM (build 1.sun.com/javadetails/.5. on Linux and Windows.getProperty("java. From the Hot Spot FAQ at http://java. On Debian GNU/Linux with Sun Java 1. Where do I get the server and client systems? Client and server systems are both downloaded with the 32−bit Solaris and Linux downloads. if you download the JRE. it's in C:\Program Files\Java\jre1.5. it's a completely separate distribution. } // probably 32bit return false.5. However. On Windows.0\lib\i386.indexOf("64") >= 0. only the server system is included. you get only the client.cfg.html If you type.heap defaults..0−sun.toLowerCase().html#compiler_types. On Solaris. Standard Edition (build 1. mixed mode. The client system is optimal for applications which need fast startup times or small footprints. Some of the other differences include the compilation policy. the 64−bit JRE is an overlay on top of the 32−bit distribution.0−b64. the file is in /etc/java−1.19 Set the default JVM type . For 32−bit Windows./javadetails/java−0566. the server system is optimal for applications where the overall performance is most important. The other available mode is "server".name") . in a Shell > java −version you get java version "1. } } 4. They are essentially two different compilers (JITs)interfacing to the same runtime system.com/docs/hotspot/HotSpotFAQ.0.0" Java(TM) 2 Runtime Environment. A content like 4.

rgagnon.html method 1a : redirect to a file // Win95 (?) javac −J−Djavac.getRuntime().20 Capture the output of JAVAC .*.com/javadetails/.txt // WinNT (or better) javac MyClass.java 21 | MORE method 2 : use JAVA to capture the output // // // // [JDK 1. compile.length > 0 ) fn = args[0]. public class JC { public static void main( String args[] ) throws IOException. while( (buf = se. String buf.1] to compile: java JC mySource. −server KNOWN −client KNOWN sets the server as the default.java".txt method 1a : redirect to stdout with a pause after each screen full // WinNT (or better) javac MyClass. capture compiler output and launch your Applet or Application directly from the editor.out.getErrorStream() ) ).java (use redirection to keep the output) java JC mySource.waitFor() + ")" ).java >output.out.io.java 2output. } } or you can always use a small text editor like Textpad where you can write with Java code (with syntax coloring). 4. 4.out./javadetails/java−0147.txt import java.20 Capture the output of JAVAC Current version of this HowTo : http://www.java >output.−client KNOWN −server KNOWN defines the client as the default. System. if( args.println( "BEGIN (" + fn + ")" ). InterruptedException { String fn = "JC.pipe..readLine()) != null ) System.output=true myClass. System.println( " : " + buf ).exec( "javac −verbose " + fn ). Process p = Runtime.println( "END (rc:" + p. BufferedReader se = new BufferedReader ( new InputStreamReader( p.

. add the following line at the end : java.io.readLine().DataInputStream(System. String aLine = in. Let's try it with this simple class : package JavaCom.21 Freeze the JVIEW window in MS VJ++ .2 must be installed on the system (for download.rgagnon.DataInputStream in = new java.in). } } NOTE: This is not really a Bean but let's keep it simple! The next step is to build a manifest file to identify the bean in the jar.txt): Name: JavaCom/JavaBeanSays Java−Bean: true NOTE: If no manifest is present all classes in the jar are treated as beans. The tool is called packager.ole package. Sun provides a similar tool but you must package everything in a jar file and use the Beans technology.txt is the directory under it... and the JVIEW window won't close until you hit ENTER.21 Freeze the JVIEW window in MS VJ++ Current version of this HowTo : http://www.22 Wrap a Java beans in a COM object Current version of this HowTo : http://www. see Java Sun Web site).io.html In your source. The JavaBeanSays class is in the directory JavaCom.2 and the JDK1.beans. Here it is (manifest.4.com/javadetails/. Or simply execute JVIEW directly in a DOS window with jview <classname> Check this How−to for a better way.com/javadetails/. the manifest. } public void setHello(String s) { _hello = s. public class JavaBeanSays { private String _hello = "Hello World!". 4. public String getHello() { return _hello ./javadetails/java−0045./javadetails/java−0148.rgagnon. From 4. written in Java. you execute it from the sun.. The Java Plug−in 1.html The previous How−to was using a Microsoft utility to enable access to Java objects from a COM−aware development tool.

The "ActiveX" name under which the beans will be seen is shown. 4.. you need to specify a valid directory name.CreateObject("JavaBeanSays.html Applets can read certain system properties by invoking System.1\ for example .getHello MsgBox strFromJava. the beans suffix must be added to this name). the wizard should list the JavaCom. An output directory is needed. press Next (in VbScript. you follow the 5 steps to create the "JavaBeans bridge for ActiveX" for the JavabeanSays component.2) or (jsdk1.ocx in it.txt). And you start the packager with bin\java.Packager A wizard is started.vbs) ' VBSCRIPT connect to a Java Bean Dim objJava Set objJava = WScript.getHello MsgBox strFromJava. press Next.setHello("Bonjour le monde!") strFromJava = objJava. _ 0.jre\lib\jaws.exe −cp jre\lib\rt. The packager assume that a subdirectory bin is present with the file beans. be careful because this directory name will be hard−coded in the generated files (REG and TLB).jar if you to proceed more rapidly. you go there.getProperty(String key) 4.ole. _ "JAVA BEAN OUTPUT" objJava. The next step is to run the packager. You can create it and then copy beans. The Bean is now registered and ready to be used as a COM object. When selected.JavaBeanSays bean. NOTE: There is a command−line interface available in the packager if you want to bypass the wizard. If the JDK is installed in c:\dev\java\jdk1.23 Know details about the JAVA at run−time Current version of this HowTo : http://www.jar.4).jar manifest. _ "JAVA BEAN OUTPUT" NOTE: Check the JAVA PLUG−IN SCRIPTING documentation (jdk1.beans. _ 0.the directory under (the one containing manifest.jar sun.com/javadetails/.rgagnon. we built the jar with : jar cfm javacom. You run it from the JDK installation directory. To test it. The first step is to specify where is located the JavaCom.jar file. try this VbScript (TestJavaBeansSays./javadetails/java−0149. document for more infos.txt javacom\JavaBeanSays.Bean") strFromJava = objJava.class NOTE: You can download my JavaCom.23 Know details about the JAVA at run−time .ocx from the JRE\bin into it or edit the REG file to specify the original JRE\bin and update the registry with the good location.2.

vendor java.name user.url os.Properties p = null. } java. long totalMemory = rt.getProperties().separator java.vendor").home user. sb.append(s + "=<" + strValue + ">"). sb.java.version java.getProperty(key) on the property you are interested in. Here a dump that can be useful in a log file: public String dump() { StringBuffer sb = new StringBuffer().home java.append("total memory=" + totalMemory). while (en.class.separator path.hasMoreElements()){ String s = (String) en.nextElement().arch file.version Java version number Java vendor−specific string Java vendor URL Operating system name Operating system architecture File separator (eg.Enumeration en = p.getProperty("java.append("\n").vendor.class. sb. long freeMemory = rt. try { p = System.getProperty(s). return "". String strValue= p.name os.util.getRuntime().append("\n").printStackTrace().separator line. ":") Line separator Java class version number But applets are prevented from reading these system properties (for security reason): java.freeMemory(). sb. "/") Path separator (eg.dir Java installation directory Java classpath User account name User home directory User's current working directory To read a system property from within an applet.23 Know details about the JAVA at run−time . } catch(Exception e) { e.append("\n").util. String s = System. Runtime rt = Runtime. sb. } // result to a string return sb. java. simply invoke System. sb.totalMemory().path user.toString().append("free memory=" + freeMemory). } 4.propertyNames().

..html class MSJVMversion { public static void main(String[] args) { String build./javadetails/java−0328.3.html This HowTo will you show how to start a class (with a main() method) without opening a DOS Shell or using a JAR file directly from Windows Explorer. Microsoft's Java environment only goes up to 1. In our situation. This not the same thing as as the JDK version.1 or higher and start the process with the JVM switch −Xrs (Reduce Signals Xtended−switch) to stop the Windows signal from killing the JVM. included with the NT resource Kit.org/doc/english/introduction. But this solution presents many problems.SystemVersionManager.26 Execute a class from Windows Explorer Current version of this HowTo : http://www.rgagnon.. System.24 Detect the Microsoft JVM version installed Current version of this HowTo : http://www.com/javadetails/.techeez. it's possible to the utility SRVANY.ms. In this case . The setup is very simple with one configuration file and your Java service can be notified when the service is stopped.24 Detect the Microsoft JVM version installed . 4. For BEA JRockit. if you kill the SVRANY.4 and there is no plan to upgrade it.com/javadetails/.rgagnon.getProperty ("BuildIncrement").25 Run JAVA as a Windows service Current version of this HowTo : http://www.com/windows_tips/service_under_nt.htm SVRANY is used to run any EXE as a windows service. If you log in and log out from a machine and a java service is running then the service may be stopped. you need to do it manually.tanukisoftware.4.println("Microsoft JVM installed is " + build). } } NOTE:The above snippet will return the Microsoft VM version.EXE with our class a parameter.out. http://www. it's the −Xnohup Also.html A solution adapted to Java.com/javadetails/.1.EXE process (stop the service) then the JAVA. 4.EXE.html ) (opensource). build=com.util. The fix is to use Java 1. is the Java Service Wrapper ( http://wrapper.EXE is not killed.rgagnon./javadetails/java−0151. 4. SVRANY will run the specified JAVA./javadetails/java−0327. For exemple.getVMVersion().

Echo "Not a java class! (" &javaclass &")" End if End If Set WSHShell = Nothing Set FSO = Nothing WScript.Type the following VBScript using a text editor and save it as WRunJava.24 Detect the Microsoft JVM version installed . Then you will have two choices from the SendTo menu. On XP.Arguments(0) If fso.Quit(0) You need a second script to launch a java class with a console (useful to see debugging traces or text−only Java program). false Else WScript. eg.Run cmdline. You need to save the script in the SendTo subdirectory located in the Windows directory On a Win98 system. Called it CRunJava. c:\documents and settings\'user name'\SendTo. one for console−based program and one for GUI−based (Windows) program.GetAbsolutePathName(javaclass) cmdline = javaclass WSHShell. cmdline Set WSHShell = WScript. select the Send To menu and you should see an entry called WRunJava.Arguments. into the SendTo folder. Right click on it. ' [WRunJava.GetExtensionName(javaclass) = "jar" Then javacompletepath = fso.exe −cp " &javapath &" " &javaclass WSHShell.GetBaseName(javaclass) cmdline = "javaw.CreateObject("WScript. NOTE The SendTo folder is hidden by default. javaclass. go to Documents and Settings folder then select the folder of a specific user." Else javaclass = WScript.Count = 0 Then WScript.CreateObject("Scripting.CreateObject("Scripting. FSO.Shell") Set FSO = WScript.Run cmdline. javaclass.vbs. false ElseIf fso.vbs] start a java class without a console Dim WSHShell.GetExtensionName(javaclass) = "class" Then javacompletepath = fso. it's C:\Windows\SendTo. If it is not visible. SO you save the scripts shown below.Arguments. on the Tools menu.vbs .GetParentFolderName(javacompletepath) javaclass = fso.FileSystemObject") If WScript.exe . On the View tab.Shell") Set FSO = WScript.Echo "no argument on the command line.vbs. click Show hidden files and folders. javacompletepath. 1. ' [CRunJava. cmdline Set WSHShell = WScript. Then in Window Explorer. 1. Simply select it and the class should be launched via javaw. FSO. javacompletepath.CreateObject("WScript. locate a class file that can be executed (with a main() method).GetAbsolutePathName(javaclass) javapath = fso. click Folder Options.FileSystemObject") If WScript.vbs] start a java class with a console Dim WSHShell.Count = 0 Then 4.

4. false ElseIf fso.WScript.exe −jar " &javaclass WSHShell.rgagnon.Run cmdline.rgagnon. 1./javadetails/java−0157. If your application is Text mode application use "java" instead of "javaw".exe −cp " &javapath &" " &javaclass WSHShell.html 4.GetParentFolderName(javacompletepath) javaclass = fso.27 Create an icon to launch java apps for Windows? .com/javadetails/.class to javaw MyApp In the properties tab panel.GetExtensionName(javaclass) = "jar" Then javacompletepath = fso.GetAbsolutePathName(javaclass) cmdline = "java. If you click on the newly created icon.exe −cp " &javapath &" " &javaclass ' close the console ' cmdline = "cmd /c java.Arguments(0) If fso.GetBaseName(javaclass) ' keep the console open cmdline = "cmd /k java." Else javaclass = WScript.class and it is located in the directory myJavaApp on drive C:.Quit(0) Note : A JAR can be made self executable (with double click). If the Microsoft JVM is used then use "wjview" (instead of "jview") to start a GUI Java application from an icon.Echo "no argument on the command line.html Let's say you have a class named myApp. your Java application will start without opening a DOS box./javadetails/java−0159. see this HowTo 4.GetExtensionName(javaclass) = "class" Then javacompletepath = fso..com/javadetails/. false Else WScript. you also havethe possibility to assign an icon to the Shortcut.28 Fix the "out of environment" error when setting a new CLASSPATH Current version of this HowTo : http://www.GetAbsolutePathName(javaclass) javapath = fso.. 1. Then create a Shortcut to the myApp. Next edit the properties of the Shortcut and change the line c:\myjavaapp\MyApp.Echo "Not a java class! (" &javaclass &")" End if End If Set WSHShell = Nothing Set FSO = Nothing 'WScript.Run cmdline.27 Create an icon to launch java apps for Windows? Current version of this HowTo : http://www.class.

You can adjust this in CONFIG. private static final String REGSTR_TOKEN = "REG_SZ". 4.COM. The performance is poor so it's a good idea to cache frequently used values.*.join().. In Windows 2000 and later REG.policy=/files/policy java −cp %MYCLASSPATH% %MYARGS% myClass • Use a BAT file.29 Query Windows registry .EXE.waitFor(). The REG utility can be used to write values in the registry (reg add /? for more infos). private static final String PERSONAL_FOLDER_CMD = REGQUERY_UTIL + "\"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\" + "Explorer\\Shell Folders\" /v Personal". public class RegQuery { private static final String REGQUERY_UTIL = "reg query ".exec(PERSONAL_FOLDER_CMD). private static final String CPU_SPEED_CMD = REGQUERY_UTIL + "\"HKLM\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\"" + " /v ~MHz".com C:\windows /p /E:4096 will set off 4 Kb for environment variables. public static String getCurrentUserPersonalFolderPath() { try { Process process = Runtime. reader.we query the registry to extract the personal folder path ("My Documents") and the processor ID and its name. import java.io. process.jar SET MYARGS = −Djava.start(). 4. Command line in DOS has a limit of 127 characters. • Use environment variable like SET MYCLASSPATH = /files/classes/lib/examples.getInputStream()).com/javadetails/.0 Resource Kit contains REG. Note : The Microsoft ® Windows NT ® Server 4. If your SHELL statement is set to COMMAND. simply add/modify the SHELL parameter for adjusting the environment size: SHELL=C:\windows\command. If you need more room to lanch the JVM then you have the following workaround.EXE is a native command. private static final String REGDWORD_TOKEN = "REG_DWORD".getRuntime(). reader./javadetails/java−0480. private static final String CPU_NAME_CMD = REGQUERY_UTIL + "\"HKLM\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\"" + " /v ProcessorNameString".29 Query Windows registry Current version of this HowTo : http://www.rgagnon.SYS.html We launch the REG utility and capture the output.security.DOS has a limit on available environment space. StreamReader reader = new StreamReader(process. In this example.

start().substring(p + REGSTR_TOKEN. if (p == −1) return null.String result = reader.waitFor().length()).substring(p + REGDWORD_TOKEN. reader.getResult(). int p = result.join().join(). String result = reader. } catch (Exception e) { return null.getInputStream()). process. reader. return Integer. private StringWriter sw.indexOf(REGSTR_TOKEN).waitFor().start().length()). } catch (Exception e) { return null. if (p == −1) return null. if (p == −1) return null.length()).indexOf(REGDWORD_TOKEN).getInputStream()).getResult(). return result. } } public static String getCPUName() { try { Process process = Runtime.parseInt(temp. convert it to DEC String temp = result.exec(CPU_NAME_CMD).getRuntime().trim(). String result = reader. StreamReader reader = new StreamReader(process. int p = result.indexOf(REGSTR_TOKEN).getRuntime(). StreamReader reader = new StreamReader(process.trim(). 4. 16) + 1)).getResult(). // CPU speed in Mhz (minus 1) in HEX notation. process.length()).exec(CPU_SPEED_CMD). } } public static String getCPUSpeed() { try { Process process = Runtime. reader.trim(). } } static class StreamReader extends Thread { private InputStream is. reader. return result.substring(p + REGSTR_TOKEN. int p = result.substring("0x".toString ((Integer. } catch (Exception e) { return null.29 Query Windows registry .

out. Written and compiled by Réal Gagnon ©1998−2007 [ home ] 4. start /w regedit /e jre.00 [HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment] "CurrentVersion"="1.rgagnon.println("Personal directory : " + getCurrentUserPersonalFolderPath()).4.html Use regedit utility to query the Windows registry.out. } } public static void main(String s[]) { System.1_02" "RuntimeLib"="C:\\Program Files\\Java\\j2re1. while ((c = is.txt "HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment" The content of jre.txt on my machine : Windows Registry Editor Version 5.write(c).com/javadetails/.is = is.30 Quickly retrieve available Java JVM on a workstation (Windows) Current version of this HowTo : http://www. consider making a small donation to show your support for this Web site and its content.out. the result is written into a file. If you find this article useful.1_02\\bin\\client\\jvm.30 Quickly retrieve available Java JVM on a workstation (Windows) . System.dll" "MicroVersion"="1" 4.4. System.read()) != −1) sw.StreamReader(InputStream is) { this. } } String getResult() { return sw.toString(). } public void run() { try { int c. sw = new StringWriter(). } } See also this HowTo and this one.println("CPU Name : " + getCPUName()).println("CPU Speed : " + getCPUSpeed() + " Mhz")./javadetails/java−0525.4] "JavaHome"="C:\\Program Files\\Java\\j2re1.. } catch (IOException e) { .5" [HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.

0\\bin\\client\\jvm.dll" [HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1. Written and compiled by Réal Gagnon ©1998−2006 [ home ] 4. As an alternative.txt | find "CurrentVersion" > reg2.5.0" "RuntimeLib"="C:\\Program Files\\Java\\jre1.dll" "MicroVersion"="0" [HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.dll" A CMD file for Windows to display the default JRE used : @echo off ::Find the current (most recent) Java version start /w regedit /e reg1.0\\bin\\client\\jvm. see this HowTo.0] "JavaHome"="C:\\Program Files\\Java\\jre1.txt "HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment" type reg1.txt if errorlevel 1 goto ERROR for /f "tokens=2 delims==" %%x in (reg2.5.31 Get the Windows "My Documents" path Current version of this HowTo : http://www.31 Get the Windows "My Documents" path . we can use a method provided by the JFileChooser class.txt if errorlevel 1 goto ERROR for /f "tokens=2 delims==" %%x in (reg2.4. 4..txt) do set JavaTemp=%%~x if errorlevel 1 goto ERROR echo Java home path (per registry) = %JavaTemp% del reg1.txt pause The above script returns the default JVM if the PATH variable does not override it! If you find this article useful.1_02\\bin\\client\\jvm.1_02] "JavaHome"="C:\\Program Files\\Java\\j2re1.txt ::Get the home directory of the most recent Java start /w regedit /e reg1.4.rgagnon.txt "HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\%Ja type reg1.0" "MicroVersion"="0" "RuntimeLib"="C:\\Program Files\\Java\\jre1.txt | find "JavaHome" > reg2.com/javadetails/.5] "JavaHome"="C:\\Program Files\\Java\\jre1.[HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.txt del reg2.5.txt del reg2. consider making a small donation to show your support for this Web site and its content.html This value is stored in the registry and there is no easy way to get it with regular Java unless you execute an external utility.4.5.1_02" "MicroVersion"="1" "RuntimeLib"="C:\\Program Files\\Java\\j2re1.txt) do set JavaTemp=%%~x if errorlevel 1 goto ERROR echo Java Version = %JavaTemp% del reg1.5./javadetails/java−0572.

getPath()).filechooser.JFileChooser. p. Obviously.32 Get a return code from a VBS ..getRuntime().File.write(vbs). } public static void main(String[] args){ // // DEMO // String result = "".close(). it's easy to do from a VBS. FileSystemView fw = fr.import javax.IsServiceRunning(\""+ serviceName +"\") Then \n" + " wscript.vbs").FileSystemView. import java. this is useful only on the Windows plateform. public class VBSUtils { private VBSUtils() { } public static boolean isServiceRunning(String serviceName) { try { File file = File. javax. 4./javadetails/java−0575. System.com/javadetails/.getFileSystemView(). Process p = Runtime.io. fw.".deleteOnExit(). String vbs = "Set sh = CreateObject(\"Shell.32 Get a return code from a VBS Current version of this HowTo : http://www.exitValue() == 1). You execute the script from Java.FileWriter. file. wait for its completion and capture the return code. } } 4.rgagnon. return (p. FileWriter fw = new java.Quit(0) \n".getDefaultDirectory()).exec("wscript " + file. public class GetMyDocuments { public static void main(String args[]) { JFileChooser fr = new JFileChooser(). } catch(Exception e){ e. However.waitFor().printStackTrace().swing.swing.html You can't detect directly if Windows service is running or not in Java.Application\") \n" + "If sh. fw.io.Quit(1) \n" + "End If \n" + "wscript.println(fw. msgBox("Check if service 'Themes' is running (should be yes)").FileWriter(file).io.createTempFile("realhowto". import java.out. } return false.

Process p = Runtime.exe /fo csv /nh").equals("")) { // keep only the process name line = line. msgBox("Check if service 'foo' is running (should be no)"). But you can download it from Web. javax.com/download/winxp. result = isServiceRunning("foo") ? "" : " NOT ". import java.htm.util. } public static void main(String[] args){ List<String> processes = listRunningProcesses(). } catch (Exception err) { err.readLine()) != null) { if (!line.substring(0.io.result = isServiceRunning("Themes") ? "" : " NOT ".trim(). for example : http://www. } } 4.swing.1 Using TASKLIST. msg.33 List currently running processes (Windows) Current version of this HowTo : http://www.JOptionPane.printStackTrace().*.rgagnon.computerhope.close()./javadetails/java−0593. we are launching TASKLIST.exec("tasklist.html 4.33.EXE and capture its output. } return processes.showConfirmDialog((java.JOptionPane.33 List currently running processes (Windows) . try { String line. msgBox("service 'Themes' is " + result + " running "). Note : TASKLIST. public class WindowsUtils { public static List<String> listRunningProcesses() { List<String> processes = new ArrayList<String>(). } } input.Component) null.EXE is not included the HOME edition of XP.EXE The Microsoft TASKLIST. } public static void msgBox(String msg) { javax.getRuntime().EXE is used to dump the list of the currently running processes.DEFAULT_OPTION). It is similar to tasklist window but for the console.indexOf("""))). BufferedReader input = new BufferedReader (new InputStreamReader(p. import java.awt. msgBox("service 'foo' is " + result + " running ").*.swing.getInputStream())).com/javadetails/. line.substring(1). "VBSUtils". From a Java program. processes.add(line. 4. while ((line = input..

"WindowsUtils".iterator().SWbemLocator\")\n" "Set service = locator.exec("cscript //NoLogo " + file. javax.swing.33.2 Using a VBS Another technique to build the required VBScript on−the−fly. java. java.FileWriter(file).JOptionPane.io. Korbel 4. } } msgBox("Running processes : " + result).FileWriter. 4.createTempFile("realhowto".getInputStream())).hasNext()) { result += it.io. java.JOptionPane. BufferedReader input = new BufferedReader (new InputStreamReader(p. if (i==10) { result += "\n". i++.2 Using a VBS . file.getPath()). String line.Shell\")\n" "Set locator = CreateObject(\"WbemScripting.io.echo process.*.getRuntime().vbs"). execute it and capture its output. Process p = Runtime.io.io.File. msg.deleteOnExit().Component) null. try { File file = File.write(vbs).BufferedReader.".".util.DEFAULT_OPTION). int i = 0.ExecQuery _\n" " (\"select name from Win32_Process\")\n" "For Each process in processes\n" "wscript. } } Thanks to M.Name \n" "Next\n" "Set WSHShell = Nothing\n".showConfirmDialog((java.close(). fw. fw. i = 0.next() +".InputStreamReader.String result = "". } public static void msgBox(String msg) { javax.CreateObject(\"WScript. // display the result Iterator<String> it = processes.33.swing. public class VBSUtils { private VBSUtils() { } public static List<String> listRunningProcesses() { List<String> processList = new ArrayList<String>(). FileWriter fw = new java. while (it. String vbs = + + + + + + + + "Set WshShell = WScript.awt.ConnectServer()\n" "Set processes = service. import import import import import java. java.

java.readLine()) != null) { processList. } } See this HowTo to check for a specific application is running or not. } public static void msgBox(String msg) { javax. Iterator<String> it = processes.add(line).listRunningProcesses().swing. public class VBSUtils { private VBSUtils() { } public static boolean isRunning(String process) { boolean found = false. } } msgBox("Running processes : " + result).JOptionPane. } input.io.awt. } return processList. java.JOptionPane.". } public static void main(String[] args){ List<String> processes = VBSUtils.34 Check if a program or process is running (Windows) Current version of this HowTo : http://www. i = 0.showConfirmDialog((java.Component) null. 4.InputStreamReader. java.iterator(). msg.io./javadetails/java−0610.io. try { 4.DEFAULT_OPTION). String result = "".hasNext()) { result += it. "VBSUtils". we adapt it to check for a specific program name. import import import import java. i++.close(). we check if the text editor TextPad.while ((line = input. if (i==10) { result += "\n". } catch(Exception e){ e.File.io.next() +".swing..printStackTrace().com/javadetails/. javax.rgagnon.BufferedReader. In this example.FileWriter.34 Check if a program or process is running (Windows) . int i = 0.exe is running. while (it.html Based on this HowTo which list the currently running processes.

4.html The JDK itself does not use the windows registry to run. line = input.write(vbs). BufferedReader input = new BufferedReader (new InputStreamReader(p.DEFAULT_OPTION).exe").readLine().getPath()).printStackTrace().vbs").com/javadetails/.deleteOnExit(). 4. if (line != null) { if (line.Shell\")\n" "Set locator = CreateObject(\"WbemScripting.rgagnon. file. msgBox("Is TextPad running ? } public static void msgBox(String msg) { javax.FileWriter(file).ExecQuery _\n" " (\"select name from Win32_Process where name='" + process +"'\")\n" "For Each process in processes\n" "wscript.awt. It is the JRE that uses the system registry to run in some situations like an Applet or a program started with the WebStart technolgy. "VBSUtils".File file = File.JOptionPane.exec("cscript //NoLogo " + file.JOptionPane. } } input. } catch(Exception e){ e. String line. fw.35 Windows registry vs. Java JDK/JRE installation .echo process.getRuntime().35 Windows registry vs.close().CreateObject(\"WScript.isRunning("TextPad. javax.getInputStream())).swing.".ConnectServer()\n" "Set processes = service.Name \n" "Next\n" "Set WSHShell = Nothing\n"./javadetails/java−0604.close(). String vbs = + + + + + + + + "Set WshShell = WScript.Component) null. msg. Process p = Runtime. FileWriter fw = new java. Java JDK/JRE installation Current version of this HowTo : http://www. fw.io..swing.createTempFile("realhowto".showConfirmDialog((java. } public static void main(String[] args){ boolean result = VBSUtils.SWbemLocator\")\n" "Set service = locator. } } " + (result ? " Yes" : "No")).equals(process)) { found = true. } return found.

0. then the javadoc tag /** *@table employee:firstname. This would happen if the user just types "java" on the commandline in some random directory.5.exe file.address:city.. the java.1 newMethod public java.rgagnon. it is safe to specify the complete path to the JRE to launch it. In this situation.html Since JDK1.36. If a method interact with 2 tables. But for the Applet/Plugin or WebStart−based programs. the registry is always used to determine the current JRE.36 Create a Taglet to document database access (Javadoc) Current version of this HowTo : http://www.exe will locate the current Java installation by looking at the registry key [HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\CurrentVersion] and then get the path of the JRE from the corresponding key [HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.String newMethod() 4.country * @return value */ public String newMethod() { return "yo".4. 4.5. Oracle) installs themself at the beginning of the PATH definition.com/javadetails/. You can run the absolute path to the java. it is possible to create a taglet to be used with javadoc to customized the generated documentation. C:/winnt/system32/java.5\JavaHome] Beware that some software (eg.36 Create a Taglet to document database access (Javadoc) .Finally. and it will be guaranteed to use jre1.0\bin\java. employee and address./javadetails/java−0473. because the system directory is always in the user's path. So for a regular Java SE program. the JRE will only use the registry if it is run from the Windows system directory (ex . so it's their Java installation that will be found first.exe" MyClass It will not use the registry. as in "C:\Program Files\Java\jre1. } will be documented as 4. This example implements a new javadoc tag to document which tables a class is dealing with.lang.exe).lastname.

Taglet. private static final String HEADER = "Table(s):".Map.country * * @author Réal Gagnon */ public class Table implements Taglet{ private static final String NAME = "table".tools. } /** * Will return true since <code>@todo</code> * can be used in method documentation. * @return true since <code>@todo</code> * can be used in method documentation and false 4.sun.java */ city country package com.address:city.util.taglet.sun. } /** * Will return true since <code>@todo</code> * can be used in constructor documentation. /** * This is a taglet to document tables and fields used by a classes * example : @table employee:lastname.*. } /** * Will return true since <code>@todo</code> * can be used in field documentation.firstname. import com.36 Create a Taglet to document database access (Javadoc) . /** * Return the name of this custom tag. */ public boolean inField() { return false. import java. * @return true since <code>@todo</code> * can be used in constructor documentation and false * otherwise.rgagnon. import com. */ public String getName() { return NAME.doclets.Returns: value Table(s): firstname lastname The "table" taglet source /* * Table. * @return true since <code>@todo</code> * can be used in field documentation and false * otherwise. */ public boolean inConstructor() { return true.javadoc.

*/ public boolean inPackage() { return true.remove(tag.put(tag. * @return false since <code>@todo</code> * is not an inline tag.getName(). } /** * Will return false since <code>@todo</code> * is not an inline tag. } /** * Register this Taglet. if (t != null) { tagletMap. } /** * Will return true since <code>@todo</code> * can be used in method documentation.getName()). tag). Taglet t = (Taglet) tagletMap. * @return true since <code>@todo</code> * can be used in type documentation and false * otherwise. * @param tagletMap the map to register this tag to.getName()).36 Create a Taglet to document database access (Javadoc) .get(tag. * @return true since <code>@todo</code> * can be used in overview documentation and false * otherwise. } 4.* otherwise. */ public boolean inOverview() { return true. } /** * Will return true since <code>@todo</code> * can be used in package documentation. } /** * Will return true since <code>@todo</code> * can be used in type documentation (classes or interfaces). */ public static void register(Map tagletMap) { Table tag = new Table(). * @return true since <code>@todo</code> * can be used in package documentation and false * otherwise. */ public boolean inMethod() { return true. } tagletMap. */ public boolean isInlineTag() { return false. */ public boolean inType() { return true.

length.").1\lib\tools. int j = tables.4.length > 1) { String fields[] = current[1]. * @param tags the array of Tags representing of this custom tag. } } Compile your taglet. output += "<TH ALIGN=\"center\" STYLE=\"border−style:solid. } output += "</TR></TABLE>". */ public String toString(Tag tag) { String output = "". Use javac compiler version 1. } return result .java 4.length == 0) { return null.split(":").4.length. i < j . n++) { output += "<TR><TD ALIGN=\"center\">" + fields[n] + "</TD></TR>". The required class files are in the lib\tools. int k = fields.1 : javac −classpath "C:\Program Files\j2sdk1.split(". i++){ // deals with the current table and its fields String current[] = tables[i]. for (int n=0. n < k .text()." + " border−width:thin\">" + current[0] + "</TH>". if (current. i++) { result += toString(tags[i]). i < tags. } } output += "</TABLE>". if (j > 0) { output = "<DT><B>" + HEADER + "</B><DD><TABLE><TR>".4. for (int i = 0.length. */ public String toString(Tag[] tags) { if (tags.jar file in the SDK. for (int i=0.").0 (or later) in the Java 2 SDK. return its string representation." + " border−width:thin\">".split("./** * Given the <code>Tag</code> representation of this custom * tag. } /** * Given an array of Tags representing this custom * tag. * @param tag the <code>Tag</code> representation of this custom tag. return its string representation. } return output. String tables [] = tag. output += "<TD><TABLE style=\"border−style:solid. } String result = "".36 Create a Taglet to document database access (Javadoc) . Assuming the SDK is installed at C:\Program Files\j2sdk1.jar" com\rgagnon\taglet\Table.

37 Generate the Javadoc "en français" .SerialData=Serial Data\: doclet.ClassUse_Subinterface=Sous−interfaces de {0} dans {1} doclet.properties in 4. if your taglet class file is defined to be in package com. then you should set tagletpath to C:\taglets.doclets.rgagnon.properties used by Javadoc to generated the labels. This example calls javadoc on package com. consider making a small donation to show your support for this Web site and its content. Translate it (or you can download my "incomplete" version here). Copy it under the name standard_fr.jar.taglet and is stored in C:\taglets\com\rgagnon\taglet\Table.standard.taglet..Since=Since\: doclet./javadetails/java−0437.Generated_Docs_Untitled=Generated Documentation (Untitled) [standard_fr.properties into the tools.properties (extract)] doclet.jar in the lib directory contains the resource bundle standard.class.jar making sure that the file is located in the right package (along standard.Warn_inline_taglet=Inline tag {0} should only be used with a {1}.Frame_Version=Frame version doclet. [standard.rgagnon.rgagnon.package1 Download this taglet here. Extract from tools. in our case for french.SerialData=Donn\u00E9e s\u00E9rialis\u00E9e\: doclet. If you find this article useful.com/javadetails/.properties files (keep the directory structure). we need a file called standard_fr.tools. you need to create the appropriate resource bundle. doclet. doclet.properties.37 Generate the Javadoc "en français" Current version of this HowTo : http://www.Since=Depuis\: doclet. To add a new language. The new file must be in the package com.sun. For example.Warn_inline_taglet=Inline tag {0} should only be used with a {1}.resources.Generated_Docs_Untitled=Documentation g\u00E9n\u00E9r\u00E9e Once everything translated.html The javadoc utility uses the regular Java mechanism to internationalize its output.Packages=Paquetages doclet. including Table taglet tags: C:\dev\Work\java\taglet>javadoc −taglet com.Window_Split_Index={0}\: {1}−Index doclet.Packages=Packages doclet. the standard. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 4.Window_Split_Index={0}\: {1}−Index doclet.Frame_Version=Version avec cadres doclet. put your standard_fr.package1.Run the javadoc tool using the −taglet and −tagletpath options.properties (extract)] doclet. The tools.properties.ClassUse_Subinterface=Subinterfaces of {0} in {1} doclet.Table −tagletpath c:\dev\work\java\taglet com.

/javadetails/java−0502. use the −locale switch on the command line javadoc −locale fr . <javadoc locale="fr" sourcefiles="c:/client/Client.html.rgagnon 4. <html><head></head><body> this is <i>com. com rgagnon HelloWorld.5..standard.0\bin\javadoc −d javadoc0 −linksource com.sun. To generate in french. consider making a small donation to show your support for this Web site and its content.html Suppose I have a package called com.38 Document a package using Javadoc . the first line of the body will be used a the package description by javadoc..java In the directory containing HelloWorld. NOTE : Make sure the −locale switch is the first one.rgagnon with one HelloWorld class.rgagnon</i> package description.rgagnon.doclets.</i>]]></bottom> </javadoc> If you find this article useful.java" destdir="javadoc/Client" author="true" version="true" use="true" private="true" windowtitle="Client"> <doctitle><![CDATA[<h1>Client</h1>]]></doctitle> <bottom><![CDATA[<i>Copyright &#169.com/javadetails/.38 Document a package using Javadoc Current version of this HowTo : http://www.. \progra~1\Java\jdk1. add a file called package. 2003 Real's Howto.java. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 4..com" target="_top">web site</a> </body></html> Now execute the javadoc utility located in [JDK]\bin directory from the root of the com. This must be a complete HTML file (with HEAD and BODY).rgagnon package.resources). Using Ant.com.rgagnon. see <a href="http://www.tools.

5. to create a package comment file.com/j2se/1.html.setVisible(true). consider making a small donation to show your support for this Web site and its content.39 Display a comment in a Javadoc . no package annotations. import java.*.0/docs/tooldocs/windows/javadoc./javadetails/java−0615. f.setSize(200.html#packagecomment If you find this article useful. the syntax is &#nnn. where nnn is the Unicode code (decimal value) of the character.* create a frame *&#47. package annotations. package comments and Javadoc tags. you have a choice of two files to place your comments: • package−info.where −d javadoc0 is used to specify the output directory and −linksource to create HTML version of the source file.sun.html − Can contain only package comments and Javadoc tags.com/javadetails/. Since JDK 1. } } and the javadoc output is : You can represent any character with a numerical identity. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 4.html Use the numerical identity to represent the / in the javadoc section to avoid any conflict with a real comment.java − Can contain a package declaration. * Frame f = new Frame() * </pre> * @param args */ public static void main(String args[]){ Frame f = new Frame(). See the result.5. and is preferred over package.rgagnon.39 Display a comment in a Javadoc Current version of this HowTo : http://www.200). See http://java.0. • package. This file is new in JDK 5. 4. f..awt. public class Example { /** * Simple Frame * <pre> * &#47.

.com</font>' 4.rgagnon.40 Display XML in a javadoc Current version of this HowTo : http://www.com/javadetails/.41 Add a copyright notice to a Javadoc Current version of this HowTo : http://www. 2008 rgagnon. −bottom '<font size="−1"><a href="http://www. : /** * To use this class use this XML * <pre> * {@code * <xml> * <parameter>foo</parameter> * <value>bar</value> * </xml> * } * </pre> */ With the previous versions.. } command./javadetails/java−0623.5.4. /** * To use this class use this XML * <pre> * < xml> * < parameter>foo< /parameter> * < value>bar< /value> * < /xml> * } * </pre> */ 4. you can use the {@code ..rgagnon.com">Reals HowTo</a> <br>&copy. With Javadoc 1.rgagnon.html Let's say you have a comment like this /** * To use this class use this XML * * <xml> * <parameter>foo</parameter> * <value>bar</value> * </xml> * */ The XML will not be visible since it will embedded in the HTML as tag and not as text. one way was to add a space after the <.html Use the −bottom parameter to the javadoc command line./javadetails/java−0626..com/javadetails/.40 Display XML in a javadoc .

com/javadetails/.42 Use a Log file . static { try { boolean append = true. public class TestLog { public static Logger logger./javadetails/java−0501.addHandler(fh).42 Use a Log file Current version of this HowTo : http://www..dtd"> <log> <record> <date>2005−02−28T21:21:09</date> <millis>1109643669250</millis> <sequence>0</sequence> <logger>TestLog</logger> 4. logger = Logger.logging.severe("my severe message"). import java. a logging functionnality is included with the JDK.setFormatter(new SimpleFormatter()). } } and the result is 2005−02−28 21:19:28 TestLog main GRAVE: my severe message 2005−02−28 21:19:28 TestLog main ATTENTION: my warning message 2005−02−28 21:19:28 TestLog main INFO: my info message if the XMLFormatter is in use then the output is <?xml version="1.log".logging package. append).info("my info message"). } } public static void main(String args[]) { logger.rgagnon. FileHandler fh = new FileHandler("TestLog.util.warning("my warning message").setFormatter(new XMLFormatter()).util.html Since 1.0" encoding="windows−1252" standalone="no"?> <!DOCTYPE log SYSTEM "logger.printStackTrace().getLogger("TestLog"). fh. //fh.io.*. logger.4. } catch (IOException e) { e. logger. import java.*.The result looks like this : 4. logger. It's the java.

import java. buf. return buf.*.io. static { try { boolean append = true. buf.append('\n'). fh.setFormatter(new Formatter() { public String format(LogRecord rec) { StringBuffer buf = new StringBuffer(1000). buf. buf.append(formatMessage(rec)).append(new java. buf.util. FileHandler fh = new FileHandler("TestLog.append(' ').printStackTrace(). } } 4.getLogger("TestLog").addHandler(fh).<level>SEVERE</level> <class>TestLog</class> <method>main</method> <thread>10</thread> <message>my severe message</message> </record> <record> <date>2005−02−28T21:21:09</date> <millis>1109643669328</millis> <sequence>1</sequence> <logger>TestLog</logger> <level>WARNING</level> <class>TestLog</class> <method>main</method> <thread>10</thread> <message>my warning message</message> </record> <record> <date>2005−02−28T21:21:09</date> <millis>1109643669328</millis> <sequence>2</sequence> <logger>TestLog</logger> <level>INFO</level> <class>TestLog</class> <method>main</method> <thread>10</thread> <message>my info message</message> </record> </log> to customize the output. } }). buf. logger = Logger. you can provide you own formatter import java.Date()). append).toString().append(' ').42 Use a Log file .append(rec.logging.*.log".getLevel()).util. } catch (IOException e) { e. logger. public class TestLog { public static Logger logger.

// 1 Mb int numLogFiles = 3./javadetails/java−0301. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 4.props TestLog To suppress the logging output to the console Logger rootLogger = Logger.ConsoleHandler You may want to take a look at another popular logging mechanism : Log4J.log".log. consider making a small donation to show your support for this Web site and its content.config. java −Djava. TestLog1.severe("my severe message").logging.getLogger("").43 Trace the execution Current version of this HowTo : http://www. } or modify the logging. [StackTrace. limit.logging.properties file located in JRE_HOME/lib (default). logger.config.getHandlers(). you specify a filename with the java.info("my info message").java] 4. Handler[] handlers = rootLogger.file=mylogging. See also this HowTo and this one If you find this article useful.removeHandler(handlers[0]). FileHandler fh = new FileHandler("TestLog%g.public static void main(String args[]) { logger. Look for the property handlers and remove the value java.properties. numLogFiles).util.html This class generate a stackTrace and then parse it according to the parameters received.43 Trace the execution .util.com/javadetails/.file system property.log and so on. To use a different properties file.util. will give TestLog0. if (handlers[0] instanceof ConsoleHandler) { rootLogger. logger.logging.warning("my warning message"). Default values are defined in JRE_HOME/lib/logging.rgagnon.. } } then the output is Mon Feb 28 21:30:54 EST 2005 SEVERE my severe message Mon Feb 28 21:30:54 EST 2005 WARNING my warning message Mon Feb 28 21:30:54 EST 2005 INFO my info message To limit the log file size and set a rolling pattern int limit = 1000000.

java] import java.nextToken() + "\n".nextToken().util.io. 0).equals("")) output = msg + "\n" . // get ride of line(s) for the Trace class if (!msg.println("Trace: " + output).nextToken() + "\n". int deep) { // // msg a message to appear in the Trace // deep = 0 complete stack // n from "n" levels // String output = "" . s=st.out. import java. } } [SimpleTrace. } public static void displayStack(int deep) { displayStack("". // to clean up the stacktrace StringTokenizer st = new StringTokenizer(stackTrace. deep−−. s=st. } } else { while (deep > 1) { if (st.*. } public static void displayStack(String msg) { displayStack(msg. } } System. System. StringWriter sw = new StringWriter().nextToken(). deep).hasMoreTokens()) { output += st.43 Trace the execution . // get ride of the first line String s=st. } public static void displayStack(String msg. 0).hasMoreTokens()){ output += st.out. 4.nextToken(). "\n"). if ( s.*.toString(). new Throwable(""). // process the stack if (deep == 0) { while (st.printStackTrace(new PrintWriter(sw)).displayStack") < 0 ) output += s + "\n". } else deep = 0. String stackTrace = sw.println("**" + deep).indexOf("StackTrace.public class StackTrace { public static void displayStack() { displayStack("".

java:20) Trace: Howto Trace all levels at MyClass.2.44 Time the execution Current version of this HowTo : http://www. Remember that line numbers are not available when a JIT is in function. in this example.java:12) at SimpleTrace. } } And the output should be Trace: Howto Trace only 1 level at MyClass. To disable it.java:21) at SimpleTrace.. See also this HowTo.currentTimeMillis(). it's the Sun's JDK 1.java:7) NOTES: The stackTrace() formatting may be different with the JVM used.44 Time the execution . } } class MyClass { MyClass() { } public void aMethod() { StackTrace. private long end. s. 1).html public class ExecutionTimer { private long start.doit().com/javadetails/.rgagnon. StackTrace. check this How−to 4.aMethod(). } 4. } public void start() { start = System.displayStack("Howto Trace all levels"). } public void doit() { MyClass s = new MyClass(). public ExecutionTimer() { reset().aMethod(SimpleTrace.aMethod(SimpleTrace.main(SimpleTrace.doit(SimpleTrace./javadetails/java−0132.1.displayStack("Howto Trace only 1 level".public class SimpleTrace { public static void main(String args[]){ SimpleTrace s = new SimpleTrace(). You may want to look at this How−to to disable the Trace mechanism in the "release" version of your classes to achieve the best performance. s.

threshold=WARN 4. With Log4J. DEBUG.} t.public void end() { end = System. INFO.start().getName()). ALL log4j.println("\n" + t. } } See this HowTo to format a duration in ms into a string as "Days . .currentTimeMillis(). logger.debug("I'm here").45 Log information efficiently (with Log4J) . } public static void main(String s[]) { // simple example ExecutionTimer t = new ExecutionTimer().out. . logger.error("omg " + e. System.html In production code. } public long duration(){ return (end−start).print(". 4. FATAL. for (int i=0. While you can set the level in your code with something like logger.. i < 80. a good practice is to only log what is necessary in the context.warning("something wrong " + e.com/javadetails/. can be OFF.45 Log information efficiently (with Log4J) Current version of this HowTo : http://www..getLogger(MyClass.duration() + " ms"). it's more flexible to do it from the Log4J properties file . } public void reset() { start = 0. Hours . i++){ System. logger.getMessage()). ERROR.class. you can have different levels of message written into your log. logger.getMessage()).WARN).getMessage()).rgagnon. t. public class MyClass { /** * Logger log4j */ static Logger logger = Logger./javadetails/java−0527. end = 0.").info(e.out... minutes and seconds".setLevel(Level..end(). WARN.

getName()) sb. The best practice is to check if the level is enabled or not. You can even remove the unwanted logging operation from the bytecode! See this HowTo. Finally it's a good idea to design a robust toString() method for your class like this one : public String toString(){ StringBuffer sb = new StringBuffer(). Consider this line : logger.toString()).) is interpreted..append("]"). logger. sb. } even if myValue is null.getSystemResource("log4j. Written and compiled by Réal Gagnon ©1998−2006 [ home ] 4.append(this. Even if you set the level at DEBUG level.com/javadetails/.You put the properties file in the classpath and then from your code URL url = ClassLoader.. ERROR. consider making a small donation to show your support for this Web site and its content.configure(url). sb. the toString() method will be called and the result concatened to a String even if the DEBUG level is disabled.append(this. this toString() method will display "null" as the value and not throw a NullPointerExeception. } This way you will not incur the cost of parameter construction if debugging is disabled for logger.debug("something wrong with the value of " + myValue.html While you can set the logging level through the configuration properties file .DEBUG).threshold=WARN 4.. DEBUG. the logger. return sb. ALL log4j. FATAL. Logging activities have a cost.append(" anotherValue=["). WARN.append(" myValue=["). logger.setLevel(Level. can be OFF.rgagnon.anotherProperty). PropertyConfigurator.myValue).isDebugEnabled()) { logger.46 Change the logging level on−the−fly (Log4J) . INFO.append("]").DEBUG).toString()).setLevel(Level. See also this HowTo and this one If you find this article useful./javadetails/java−0621.props").46 Change the logging level on−the−fly (Log4J) Current version of this HowTo : http://www.toString().append(getClass().debug("something wrong with the value of " + myValue. if (logger.debug(.

Level. However.setLevel(org.47 Use a JAR/ZIP/CAB file with an Applet . ./javadetails/java−0153..Level.setLevel(org. The browser need to be JDK1. If a JAR file is used with an Applet..equals(level)) { root. private void setLogLevel(String level) { Logger root = Logger.47 Use a JAR/ZIP/CAB file with an Applet Current version of this HowTo : http://www.INFO). setLogLevel("DEBUG").class files. simply include the JAR in the CLASSPATH : 4...It may be useful to change it on−the−fly for debugging purpose. For more infos about signing Applet for Netscape. These utilities can be freely downloaded from the Netscape Web site. . If the search fails in the JAR file. JAR supports compression. you must use Netscape's utilities ZIGbert or GUI JAR Archiver to sign it. you can specify many JARs in one ARCHIVE tag.jar" WIDTH=100 HEIGHT=100> </APPLET> In theory. To specify the use of a JAR file with an applet: <APPLET CODE=a.log4j.. } else { root. Netscape).apache.. if ("DEBUG".class ARCHIVE="abc. You need to get the Log4J "root" Logger and then change its "level".com/javadetails/.getRootLogger(). then the browser looks in the applet's base directory.DEBUG). } } 4. .rgagnon.1 compatible to handle JAR file. setLogLevel("INFO").. In an application. the browser will look first into the JAR to load all classes. images and sounds) into a single JAR file. further improving the download time.log4j.apache. But the current version of Netscape will only load the first JAR and ignore the others. which reduces the file size. Microsoft IEv4 can handle multiple JAR files. check this JAVA How−to. The applet author can digitally sign individual entries in a JAR file to authenticate their origin (using the JAVAKEY utility). to sign JAR to be used with a "real−world" browser (eg.html [JAR format] JAR (Java ARchive) is a platform−independent file format that allows you to bundle a Java applet and its requisite components (.

To create a CAB file..class" ARCHIVE="abc." ARCHIVE=abc.jar *.class According to some JAVA developers.1 jar cvf abc. To associate a CAB file with an Applet. It is possible sign a CAB file using the Authenticode mechanism. An Applet can support ZIP and CAB format by using the following HTML: <APPLET CODEBASE=".cab"> </APPLET> the cabbase parameter will be interpreted only by MSIE.cdrom. simply use the HTML ARCHIVE tag <APPLET CODE="a. check the Microsoft Web site for more infos.java −classpath c:\jdk1.0.jar HelloWorld To create a JAR file (compressed). JAR in CLASSPATH needs to be uncompressed (JDK1.1) to create a JDK1.\HelloWorld.class" WIDTH=100 HEIGHT=100> <PARAM NAME="cabbase" VALUE="abc.cab. non−MS browsers browser will simply ignore it. use the JAR utility included with JDK1.class or check for InfoZIP at http://www.zip *. To create an archive.1).class [ZIP format] JDK1.cab *. To create uncompressed JAR: jar cvfO myArchive.47 Use a JAR/ZIP/CAB file with an Applet .class 4. simply use a ZIP tool that supports the long filename format and specify the ZERO compression mode.jar a..com/pub/infozip/ To use a ZIP archive.class c.. It offers compression (like the JAR but the ZIP format is un−compressed). You can use Sun's JAR utility (included with JDK1.1.zip CODE=a.3\lib\classes. simply use the HTML : <APPLET CODE="a.zip.* to create myArchive.0. use the CABARC utility from Microsoft : CABARC n myArchive.2 introduces the ZIP "un−compressed" format.zip" WIDTH=618 HEIGHT=410> </APPLET> [CAB format] CAB (for CABINET) is used only by Microsoft Internet Explorer.class b.2 compatible ZIP file: jar cvfO myArchive.

48 Make ZIP/JAR file always accessible from applet Current version of this HowTo : http://www.awt. Try with this simple class import java.com/docs/manuals/signedobj/overview.rgagnon.html In the manifest file of a JAR.com [ home ] 4.Check the following links for more infos: http://developer. import java.netscape. public class MyClass { public static void main(String[] args) { Frame f = new Frame()./javadetails/java−0166. The class must have a main().JAR in the PLUGINS directory and restart Netscape. MSIE will use CAB and ignore the ZIP file.addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { System.event. to be able use SWING classes from Netscape.com/docs/manuals/communicator/jarman/ http://developer.exit(0). it is possible to specify the class to be used when the JVM is lauched with the JAR as parameter.. f.awt.com/javadetails/.rgagnon.*. The JAR must be signed with the Netscape Signing Tool.netscape.48 Make ZIP/JAR file always accessible from applet . Automatic method Automatic installation can be done with Netscape using the SmartUpdate mechanism. copy SWING.. Written and compiled by Réal Gagnon ©1998−2000 mailto:real@rgagnon.cab"> </APPLET> while Netscape will use the ZIP file and ignore de CAB parameter. For example.width=610 height=600 > <PARAM NAME="cabbase" VALUE="abc. } 4.html 4.com/javadetails/./javadetails/java−0154.*.html [Netscape 4] Manual method Copy the ZIP/JAR file in the PLUGINS directory and remove the reference in the ARCHIVE parameter of the APPLET tag.49 Make a JAR executable Current version of this HowTo : http://www.JAR and ROSE.

add(new Label("Hello world")). the CLASSPATH definition (as defined by the environnement variable) is overridden.jar . On Windows (NT or better).exe" −jar "%1" %* If the association is broken or you need to change the JRE used then by using the assoc/ftype utilities. for example SET PATHEXT=.jar file (if the JRE is correctly installed) or by typing java −jar myjar.. You can verify that everything is ok with the following command from a DOS Shell >assoc . Main−Class specifies the entry point with the main(String args[]) method.0 Main−Class: MyClass Class−path: .setVisible(true).jar manifest. The file association mechanism is made during the installation of the JRE. f.CMD.. It is important because when running a jar .. you include the manifest file in the JAR (MyJar. f. The Class−path is used to specify the dependency of this jar (if any). use the −D switch before the −jar switch and use the getProperty() method to get the value. Manifest−Version: 1.jar accessible via the PATH environment variable. your user account needs to be at the Admin level. You add the directories and jars separated by a space.} ).mft *. typing "MyJar" on the DOS command line will invoke "javaw −jar MyJar.EXE.jar=jarfile >ftype jarfile jarfile="C:\Program Files\Java\jre1.jar) with the MyClass class.jar If you need to pass parameters.JAR Then if you have the jar file MyJar. Next.5.jar" .0_10\bin\javaw.200). NOTE: On WinXp (or better).class by double−clicking on the MyJar. you can also make JARs run from the command−line by setting the PATHEXT environment variable. f. you can modify the association easily (use /? to display the syntax of the assoc and ftype utilities).mft) with any text editor. } } Then create this manifest file (manifest.class Then you are able to start the MyClass. jar cvfm myjar.setSize(200.BAT.48 Make ZIP/JAR file always accessible from applet . 4.

LIST file in the META−INF directory which will enable the application class loader to download the right jar files when it is searching for classes or resources./javadetails/java−0409.net.*.com/javadetails/.io. public class ExtraLoader { public static void main(String[] args) { try { URL urlA = new File("C:/xtras/xercesImpl.*.jar and Third.html Supposed we have a jar called Main. URLs are separated by one or more spaces.getName()). The application or extension class loader uses the value of this attribute to construct its internal search path.4. } } } 4. In the manifest file of the first jar (Main.50 Accessing jars from within a jar Current version of this HowTo : http://www.dom./javadetails/java−0319.jar"). This application needs Second.ChildNode".jar"). // Class c = Class.out. } catch(Exception e) { e.jar The value of the Class−Path attribute specifies the relative URLs of the extensions or libraries that this application or extension needs. true.50 Accessing jars from within a jar .forName ("org.println(c.rgagnon.html import java.51 Access a JAR outside the CLASSPATH Current version of this HowTo : http://www.com/javadetails/.toURL().jar Third.apache.. you adjust the Class−Path setting : Manifest−Version: 1. // System.. URLClassLoader ulc = new URLClassLoader(urls).xerces. 4.urlB }.jar This will build an an INDEX.0 Main−Class: MyClass Class−Path: Second. ulc).jar . import java.printStackTrace(). URL[] urls = { urlA. URL urlB = new File("C:/xtras/xmlParserAPIs.toURL().jar for the application.rgagnon.jar). You can use the −i option to speed up your application's class loading time: jar −i main.

class mydb. in.printStackTrace().52 Extract a file from a Jar .) { int nBytes = in. OutputStream out = new BufferedOutputStream(new FileOutputStream(efile)).jar manifest.close().close().getProtectionDomain().mft ExtractFromJAR. } catch (Exception e) { e. } } public static void main(String args []){ new ExtractFromJAR().util.52 Extract a file from a Jar Current version of this HowTo : http://www.\mydb. nBytes). for (. InputStream in = new BufferedInputStream(jar. File efile = new File(dest.4.read(buffer)./javadetails/java−0429.rgagnon. 0. out. } } Grab this auto−run Jar if you want to try it. To create an auto−run JAR. out.mdb").extractMyMDBFromJAR("..").io. substring(6).getEntry("mydb. byte[] buffer = new byte[2048].write(buffer.mft Manifest−Version: 1. public class ExtractFromJAR { public void extractMyMDBromJAR(String dest){ try { String home = getClass().getLocation(). JarFile jar = new JarFile(home).*. if (nBytes <= 0) break.html The following snippet extract a file (mydb.util.getInputStream(entry)). getCodeSource(). import java. entry.jar Main−Class: ExtractFromJAR Create the JAR C:\jdk141\bin\jar cvfm mydb.jar. first create a manifest.com/javadetails/.mdb 4.*.toString().getName()). } out..0 Classpath: . import java.zip.*. ZipEntry entry = jar.mdb) from a jar. import java.flush().

.out..rgagnon.html package com.class 4. getCodeSource().rgagnon.getProtectionDomain() .getCodeSource().class >java −jar Hello.jar (A tip from Fred Hommersom) Your code reads: String home = getClass().53 Determine if running from JAR .HelloClass file:/C:/DEV/WORK/JAVA/com/rgagnon/HelloClass. } System. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 4.getClass(). if (classJar.getClass()..'.class"). So I modified the code to String home = getClass().getProtectionDomain()./javadetails/java−0391.startsWith("jar:")) { System. String classJar = this. and the mydb.getPath(). I got a problem when the jar file was located in C:\Program Files\xyz due to the embedded space.replace('.53 Determine if running from JAR Current version of this HowTo : http://www.class added manifest adding: com/rgagnon/HelloClass.toString().say().out.getResource("/" + className + ".mdb file should appear in the current directory.mft com\rgagnon\HelloClass.replaceAll("%20".jar!/com/rgagnon/HelloClass.com/javadetails/.println("*** running from jar!").getLocation() .println(classJar).getName().class (in=1059) (out=601) (deflated 43%) >java com.jar manifest.jar *** running from jar! jar:file:/C:/DEV/WORK/JAVA/Hello.substring(6). " ").Run it . '/'). consider making a small donation to show your support for this Web site and its content.toString(). public class HelloClass { public static void main(String[] args) { new HelloClass(). java −jar mydb. } } The output >jar cvfm Hello. If you find this article useful. } public void say() { String className = this.rgagnon.getLocation().

")).getNextJarEntry ().1_02/lib/mail. "com.mail. classes.getName().mail. if(jarEntry == null){ break. public static List getClasseNamesInPackage (String jarName. /* output : Jar C:/j2sdk1.println ("Found " + jarEntry. JarEntry jarEntry.jar looking for com/sun/mail/handlers Found com. import java.54 Get list of classes in package (in a Jar) Current version of this HowTo : http://www.util. packageName = packageName.sun.handlers.out." .text_html.sun. try{ JarInputStream jarFile = new JarInputStream (new FileInputStream (jarName)).startsWith (packageName)) & (jarEntry. while(true) { jarEntry=jarFile..getName ().replaceAll("/". "\\.See these related HowTo's : 1 2 4.54 Get list of classes in package (in a Jar) .util.sun. } /** * */ public static void main (String[] args){ List list = PackageUtils.class 4.text_xml.out.getClasseNamesInPackage ("C:/j2sdk1.out.*.class Found com. System.getName ().4.add (jarEntry. } } } catch( Exception e){ e.jar".mail. } return classes. } if((jarEntry.1_02/lib/mail.sun.html import java.getName().endsWith (".*.4.replaceAll("/".handlers"). "/").text_plain.class Found com. if (debug) System.class")) ) { if (debug) System.")). import java.println ("Jar " + jarName + " looking for " + packageName).io. public class PackageUtils { private static boolean debug = true.printStackTrace ().println(list). "\\.mail. String packageName){ ArrayList classes = new ArrayList ().jar.com/javadetails/.handlers./javadetails/java−0513.*.handlers.replaceAll("\\.rgagnon.

handlers.html Let's say we have the following class (package is mandatory) package com.55 Add version to Jar packaging .mail.sun.mail.Hello Specification−Version: 2. com.mail.Hello Then build the executable Jar and run it.1 Implementation−Version: 1.sun.handlers.jar MANIFEST.text_xml.sun. >jar cvfm hello. public class Hello { public static void main(String[] args) { new Hello().class >java −jar hello.handlers.MF com\rgagnon\Hello.class Found com.mail. Manifest−Version: 1.rgagnon. } } First create a MANIFEST.mail.jar Hello World! Now modify the manifest to include versioning information.class.class [com. com.class.handlers.sun.handlers. .image_gif.message_rfc822.image_jpeg.rgagnon.sun.class Found com.message_rfc822.multipart_mixed.image_jpeg.text_html.com/javadetails/.handlers.sun.sun.55 Add version to Jar packaging Current version of this HowTo : http://www.mail. com .class] */ } } If you find this article useful.say("Hello World!").handlers.0 Main−Class: com.rgagnon.rgagnon./javadetails/java−0388.handlers.out.MF file : Manifest−Version: 1. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 4.println(s). 4.mail.1 Modify the class to display the version.sun..Found com. } public void say(String s) { System.0 Main−Class: com.class.class Found com. consider making a small donation to show your support for this Web site and its content.mail.

getSpecificationVersion()).getValue("Specification−Version").println("Hello Implementation Version : " + p. System.rgagnon. } public static String getJarSpecificationVersion(String jar) throws java. System.out.io. public class Hello { public static void main(String[] args) { new Hello().jar.MF com\rgagnon\Hello.say("Hello World!"). return att.1 Hello World! See also this Howto.getMainAttributes().getMainAttributes(). } } Compile and rebuild the Jar and execute > jar cvfm hello.getPackage().getValue("Implementation−Version"). return att.io.5.howto.out.IOException { JarFile jarfile = new JarFile(jar).getManifest().println("Hello Specification Version : " + p.getClass(). Manifest manifest = jarfile.out.getJarSpecificationVersion(javaMailJar)). System. Attributes att = manifest.println("Specification−Version: " + JarUtils.getJarImplementationVersion(javaMailJar)).55 Add version to Jar packaging .0/lib/mail.getManifest().*. 4.rgagnon. } public void say(String s) { System. System. This example opens a given Jar and outputs its version information.jar".IOException { JarFile jarfile = new JarFile(jar). public class JarUtils { public static String getJarImplementationVersion(String jar) throws java.1 Implementation Version : 1. } public static void main(String[] args) throws java.out.out. } Hello() { Package p = this. import java. Attributes att = manifest.println("Implementation−Version: " + JarUtils.println(s).class > java −jar hello.jar Specification Version : 2. Manifest manifest = jarfile.getImplementationVersion()).IOException{ String javaMailJar = "C:/Program Files/Java/jre1.package com. package com.io.jar MANIFEST.util.

" /> 4.cmd..5.jar howto/Hello. Type the following ant script and save it./javadetails/java−0532. The target compile is also executed since the target jar depends on it.3. package howto.class(in = 415) (out= 284) (deflated 31%) > java −cp hello. public class Hello { public static void main( String[] args ){ System.Hello Hello World • Create a build. and load it into your favorite editor.rgagnon.println( "Hello World" ).org/bindownload.%path% • Create a simple Hello class as shown below (you need have a package).%JAVA_HOME%\bin.56 Use ANT to Build a JAR with version/build number ." /> </target> <target name="buildHello" depends="compile" /> </project> Go back to the DOS shell and launch Ant with > ant compile Buildfile: build.class added manifest adding: howto/hello.1 */ } } 4. <project default="buildHello"> <target name="compile"> <javac srcdir=".3 * Implementation−Version: 1. Before using ANT. You may need to adjust the values according to your installation! set ANT_HOME=c:\ant set JAVA_HOME=C:\Progra~1\Java\jdk1.. • .com/javadetails/.0 set PATH=%ANT_HOME%\bin.out.. you must execute this file to set up the environment.cmd to set the environment • Compile your Hello class and make a jar to check if your environment is ok..xml which is the default ant build file . > javac howto/Hello.java > jar −cvf hello. <project default="buildHello"> <target name="compile"> <javac srcdir=".jar howto. } } • Execute your antenv.cgi • Unzip into the root of C: (Windows).. rename the folder to \Ant • Create a file call antenv.56 Use ANT to Build a JAR with version/build number Current version of this HowTo : http://www.xml compile: [javac] Compiling 1 source file • Go back to the editor and add the jar building command./* * output : * Specification−Version: 1.apache.html • Download ANT from http://ant.

class" manifest="MANIFEST.jar" /> </project> • Execute your Ant script : > ant jar Buildfile: build. Then a property. is 4." includes="**/*.Hello Hello World • Make your Jar auto−executable by specifying the Main class into a MANIFEST. > java −jar hello.jar" /> </project> • Now you can launch Hello with only > ant jar . Add the following lines to build. build.MF"> <attribute name="Built−By" value="${user." /> </target> <target name="jar" depends="compile"> <delete file="hello.jar jar −tvf hello..56 Use ANT to Build a JAR with version/build number .xml <project default="buildHello"> <target name="compile"> <javac srcdir=".MF"/> <manifest file="MANIFEST.name}"/> <attribute name="Main−Class" value="howto.jar BUILD SUCCESSFUL Total time: 2 seconds $ jar −tvf hello." includes="**/*.jar"/> <delete file="MANIFEST.MF" /> </target> <target name="buildHello" depends="compile.num (so you need to keep it!).number.xml compile: jar: [jar] Building jar: /Dev/hello.jar" basedir=".MF file to be included in the Jar. Ant will create (if necessary) and increment a property in a file called build.class" /> </target> <target name="buildHello" depends="compile..jar" basedir=".</target> <target name="jar" depends="compile"> <jar destfile="hello.Hello"/> </manifest> <jar destfile="hello.jar howto.MF howto/ howto/Hello.class • Try your new Jar file > java −cp Hello.jar Hello World • Add a build number with the Ant task buildnumber .jar 0 Wed May 03 17:06:32 55 Wed May 03 17:06:32 55 Wed May 03 17:06:32 335 Wed May 03 16:36:16 EST EST EST EST 2006 2006 2006 2006 META−INF/ META−INF/MANIFEST.

the entry will be Implementation−Version: 1.Hello"/> <attribute name="Implementation−Version" value="${version.num" value="1." /> </target> <target name="jar"> <delete file="hello.MF"> <attribute name="Built−By" value="${user.00−b1 • and after the next build operation. The version number is also a property.00−b2 • Modify the Hello class to read the Implementation−Version information and display it.MF"> <attribute name="Built−By" value="${user.num"/> <manifest file="MANIFEST.num"/> <manifest file="MANIFEST.00"/> <buildnumber file="build." /> </target> <target name="jar" depends="compile"> <delete file="hello.56 Use ANT to Build a JAR with version/build number .jar"/> <property name="version. package howto.jar"/> <delete file="MANIFEST.MF" /> </target> <target name="buildHello" depends="compile. <project default="buildHello"> <target name="compile"> <javac srcdir=".jar" 4.name}"/> <attribute name="Main−Class" value="howto.number}"/> </manifest> <jar destfile="hello.println( "Hello World ").MF"/> <property name="version.num" value="1. <project default="buildHello"> <target name="compile"> <javac srcdir=".jar" /> </project> • If you examine the MANIFEST.MF.number}"/> </manifest> <jar destfile="hello.out.getPackage().available in your Ant script.name}"/> <attribute name="Main−Class" value="howto.num}−b${build.jar" basedir="." includes="**/*. you now see a new entry Implementation−Version: 1.xml file. } } • Finally we add a target to cleanup and the main target to build everything to the build.00"/> <buildnumber file="build. public class Hello { public static void main( String[] args ){ System.println("version : " + Hello.out. System.class" manifest="MANIFEST.Hello"/> <attribute name="Implementation−Version" value="${version.num}−b${build. Here it is hard−coded in the script but you can read it from a file.getImplementationVersion() ).class.

num" value="1. 4.num"/> <tstamp> <format property="TODAY" pattern="yyyy−MM−dd HH:mm:ss" /> </tstamp> <manifest file="MANIFEST.cleanup" /> </project> • Build and launch the Hello class > ant buildHello .class" manifest="MANIFEST.com/javadetails/.57 Include all jars in the classpath definition .class" manifest="MANIFEST.jar"/> <property name="version." includes="**/*.57 Include all jars in the classpath definition Current version of this HowTo : http://www.basedir=".MF" /> </target> <target name="cleanup"> <delete> <fileset dir=".class"/> <fileset file="MANIFEST..00"/> <buildnumber file="build.jar Hello World version : 1./javadetails/java−0587..MF"/> </delete> </target> <target name="buildHello" depends="compile..00−b3 b3 == build #3 (if it's your third build !) Build number is great but a Built date is useful too! ." includes="**/*.jar" basedir=".html 4." includes="**/*.number}"/> <attribute name="Built−Date" value="${TODAY}"/> </manifest> <jar destfile="hello.num}−b${build.MF" /> </target> See also this Howto . > java −jar hello...MF"> <attribute name="Built−By" value="${user.rgagnon.Hello"/> <attribute name="Implementation−Version" value="${version. <target name="jar"> <delete file="hello.name}"/> <attribute name="Main−Class" value="howto.jar.

As a special convenience.%%G Echo The Classpath definition is %CLASSPATH% .cmd set CLASSPATH=%CLASSPATH%. main.JAR.jar or . @echo off setlocal ENABLEDELAYEDEXPANSION if defined CLASSPATH (set CLASSPATH=%CLASSPATH%.\lib %%G IN (*.html. a class path element containing a basename of * is considered equivalent to specifying a list of all the files in the directory with the extension .%CLASSPATH% :END buildclasspath_append. 4.sun.\lib Echo The Classpath definition is %CLASSPATH% . Here some techniques to set the classpath definition automatically. All jar files in the specified directory. java MyClass 4.Specifying all the required jar in the classpath can be a pain. then the class path element foo/* is expanded to a A. if directory foo contains a.jar ) do call buildclasspath_append.) else (set CLASSPATH=.. are included in 4.cmd %%~fsi if "%_CLASSPATH%" == "" goto END set CLASSPATH=%_CLASSPATH%. there is a new way to include jars in a given directory without explicitly to specify each one of them. even hidden ones.cmd @echo off call buildclasspath.com/javase/6/docs/technotes/tools/windows/java...JAR (a java program cannot tell the difference between the two invocations). it's simpler . a single batch file can do the job..58 Windows batch file For Windows 2000 (or better).cmd set _CLASSPATH=%CLASSPATH% set CLASSPATH=%1 for %%i in ( %1\*..jar and b. java MyClass buildclasspath. For example.jar:b. we need a set of 3 CMD files to scan a given directory and build the classpath defintion with all the jars found.jar) DO set CLASSPATH=!CLASSPATH!..cmd .%1 With XP (or better). except that the order of jar files is unspecified.58 Windows batch file .59 JDK6 According to http://java..) FOR /R .JAR.

Manifest−Version: 1. The CLASSPATH environment variable. so ensure that your editor is not set up to trim trailing spaces on saves and exits. Note : There is a bug when using this feature with JAVAW.the list.jar mailer_client. See http://java. see http://bugs. where defined.sun.jar"/> </fileset> </path> 4.do?bug_id=6510337 Note : Use quote to avoid problem during the wildcard expansion.com/docs/books/tutorial/deployment/jar/downman.jar lib/client.html Ant can be used to build your Jar and built the manifest class−path definition.0 Class−Path: customer_client. ex. javac −cp "C:\mylib\*" HelloWorld. will be similarly expanded. The line with the Class−Path: header must end with a space character and each of the lines referencing the client jar's should start and end with a space ' ' character and the manifest file as a whole must end with a blank line.sun.jar" /> </manifest> </jar> </target> It's possible (but not so simple) to do it automatically without specifying each jar one by one : <path id="build.jar The manifest file format restrictions mandated by the JDK requires the use of a space ' ' character as the line continuation character. <target name="MyJar" depends="dist.jar signon_client. lib/utils.classpath"> <fileset dir="${basedir}"/> <include name="lib/*. A classpath entry consisting simply of * expands to a list of all the jar files in the current directory. compile" description="generate jar" > <jar destfile="${dist}/${jar}"> <manifest> <attribute name="Main−Class" value="${Main_Class}"/> <attribute name="Class−Path" value=".java 4.jar the CLASSPATH definition (as defined by the environment variable) is overriden by the "class−path" defined the jar's manifest.com/bugdatabase/view_bug.60 JAR (and ANT) . Remember that when you launch an application with java −jar myjar.60 JAR (and ANT) The best solution when you have a jar is to try to include the required jars into the manifest declaration.

rgagnon.dir}/${jar.jar"/> </chainedmapper> </mapper> </pathconvert> <target depends="compile" name="buildjar"> <jar jarfile="${basedir}/${test.list}"/> </manifest> .<pathconvert property="manifest.html <path id="build−classpath"> <fileset dir="${build..classpath}"/> </manifest> </jar> </target> Latest Ant version (1. <manifest> <attribute name="Main−Class" value="com. See http://ant.TestMain"/> <attribute name="Class−Path" value="${manifest.61 Detect the browser/JVM type Current version of this HowTo : http://www./javadetails/java−0160.out.mycompany.classpath" pathsep=" "> <path refid="build.TestMain"/> <attribute name="Class−Path" value=".jar" to="lib/*.jar}"> <fileset dir="${build}" /> <manifest> <attribute name="Main−Class" value="com.61 Detect the browser/JVM type ..html One way is to instanciate a known browser−specific method and catch the Exception if not found import java.list" jarfile="${build.classpath"/> <mapper> <chainedmapper> <flattenmapper/> <globmapper from="*.jar"/> </fileset> </path> <manifestclasspath property="lib. ${lib.7) includes a task called ManifestClassPath which converts a classpath into a space−separated list of items used to set the Manifest Class−Path attribute.mycompany.. public class BrowserDetector extends Applet { public void init() { if ( isNetscape() ) System.")..apache.dir}"> <include name="*.. </jar> 4.com/javadetails/. if ( isMicrosoft() ) 4.applet.println("This browser is a Netscape Browser.file}"> <classpath refid="build−classpath" /> </manifestclasspath> <jar> .org/manual/CoreTasks/manifestclasspath.*.

WToolkit")) theJVM = "JAVA".ActiveXApplet")) theBrowser = "MICROSOFTPLUGIN.MozillaAppletContext"). else if (appletContext. } } Or by examining the string representation of the getAppletContext() method String theBrowser = "APPLICATION".startsWith( "com. } public static boolean isMicrosoft() { try { Class.")) theBrowser = "MICROSOFT". One is using Microsoft−specific classes.").plugin.navig.startsWith("com.out. return false. } catch (ClassNotFoundException e) { System.println("This browser is not a Netscape Browser.").hotjava.startsWith ( "sun. else if (appletContext. String appletContext = getAppletContext().tags.windows.applet.applet.startsWith("sunw.viewer.IExplorerAppletContext") theBrowser = "MICROSOFTPLUGINJRE1.")) theBrowser = "NETSCAPE".startsWith( "sun. For an application. else if (appletContext.out. The idea is to put all 4.forName("com.toString(). } return true.ms.ocx.WToolkit")) theJVM = "JVIEW".AppletPlugin")) theBrowser = "NETSCAPEPLUGIN". by looking at the string representation of the getDefaultToolkit() method.ms.println("This browser is not a Microsoft Browser. } return true.4.toString(). } catch (ClassNotFoundException e) { System.applet.forName("netscape.equals("APPLICATION") { if (toolkit.ms.applet.awt.startsWith("netscape.System.getDefaultToolkit(). else if (toolkit. the other is a JDK1. else if (appletContext. else if (appletContext.startsWith( "sun.win32. if (theBrowser."). our MyApplet.61 Detect the browser/JVM type . else if (appletContext.plugin.context.class exists in three versions. return false.TagAppletPanel")) theBrowser = "HOTJAVA". String toolkit = Toolkit.out.AppletViewer")) theBrowser = "APPLETVIEWER". } For example.GenericAppletContext"). } public static boolean isNetscape() { try { Class.println("This browser is a Microsoft Browser.awt.applet.plugin.startsWith( "sun. if (appletContext.1 applet and finally a version for JDK102−only browser. we detect the JVM type String theJVM = "".startsWith("sun.

indexOf(b) != −1).jar". browserOk = (navigator. we decide which archive to use.appVersion)).. if (isBrowser("Microsoft".write() method to generate the right APPLET tag instead of a the Javascript entity to be compatible with Netscape and IE. } archiveToBeUsed = "java102. click here./javadetails/java−0161. <HTML></HTML><HEAD> <SCRIPT> function isBrowser(b. > </APPLET> </BODY></HTML> NOTE: You may need to use the document.com/javadetails/. return browserOk &versionOk. 4)) { archiveToBeUsed = "ie4.62 Detect if Java is enabled from HTML .com/javadetails/.jar".html For a Javascript solution. By using a javascript entities.62 Detect if Java is enabled from HTML Current version of this HowTo : http://www. 4) { archiveToBeUsed = "n4. } else { if isBrowser("Netscape". During layout time.class" NAME="myApplet" HEIGHT=400 WIDTH=400 ALT="Oups! You don't have JAVA enabled"> <A HREF="nojava.. the javascript entity is remplaced by the right archive name.</A> </APPLET> </BODY></HTML> 4.jar". versionOk = false.appName.class" HEIGHT=100 WIDTH=400 ARCHIVE=}.63 See the Java Console Window Log (Java plugin) Current version of this HowTo : http://www. 4.rgagnon.rgagnon./javadetails/java−0533.html 4. } } </SCRIPT></HEAD><BODY> <APPLET CODE ="MyApplet.html">Oups! You don't have JAVA enabled. check this How−to <HTML><HEAD></HEAD><BODY> <APPLET CODE="MyApplet.v) { browserOk = false.the required classes in an ARCHIVE file. versionOk = (v <= parseInt(navigator.

62 Detect if Java is enabled from HTML .trace If you find this article useful.com http://www.rgagnon. it's in the folder : C:\Documents and Settings\ <username>\ Application Data\ Sun\ Java\ Deployment\ log It's a file with the extension . Written and compiled by Réal Gagnon ©1998−2006 [ home ] Written and compiled Réal Gagnon ©2007 real@rgagnon.com 4. On the Windows plateform.The Java Console Window Log is also stored on disk. consider making a small donation to show your support for this Web site and its content.

// String aLabel = new JLabel (MyResources. 5 Internationalization . // String concatenation with MessageFormat Date d = new Date().awt. java. One way is to use Properties files and the other are classes extending the ListResourceBundle base class..*.java (main program)] import import import import import javax.rgagnon.*.event. JLabel vLabel. // Object aCheckbox = (JCheckBox)MyResources.util./javadetails/java−0133.html There are two ways to include resources based on the current Locale. [International.1 java−inter 5. MessageFormat mf = new MessageFormat (MyResources.2 Load resources based upon client environment at startup Current version of this HowTo : http://www. java.rb. java. Note that if a resource is missing for the current locale then the default definition is used.*. JCheckBox aCheckbox.getObject("aCheckbox"). aButton = new JButton (mf. JButton vButton.getString("aLabel")).text.*. JTextField aTextField.format(new Object [] { d })).com/javadetails/.rb. NumberFormat nf. add(aButton).5 Internationalization 5. JButton aButton.swing. add(aLabel). You need to follow a naming standard so that the JVM retrieves the right resources bundle. add(aCheckbox).awt. public void initGUI(){ setLayout(new FlowLayout()). public class International extends JFrame implements ActionListener { JLabel aLabel.rb.getString("aButton")). java.*.

1416.validate().*. vLabel.rb. aTextField. nf = (NumberFormat) (MyResources.*. } }. vLabel. this.addActionListener(this).rb.*. frame. vLabel = new JLabel("validation message . } } [MyResources.rb.").java (default resources)] import java. vButton.out..parse(aTextField. } } } public static void main(String args[]) { System.validate(). aTextField = new JTextField(6). import javax.text. 5 Internationalization . frame.format(dn)). SwingUtilities.util. // Number input validation vButton = (JButton)MyResources.getString("numERR")).getSource() == vButton) { try { nf.getBundle("MyResources"). add(aTextField).println("Current Local : " + Locale.// Number format output double dn = 3.invalidate().getText()). this.getDefault()). Thread t = new Thread () { public void run() { International frame = new International().getString("numOK")).printStackTrace(). add(vButton).initGUI().setVisible(true).swing. add(vLabel).setText(MyResources.setText(nf. } public void actionPerformed(ActionEvent ae) { if (ae. public class MyResources extends ListResourceBundle { public static ResourceBundle rb = ResourceBundle. public Object [][] getContents() { return contents.getObject("aNumber")). } catch (ParseException pe) { pe..setText(MyResources.invokeLater(t). vLabel.invalidate().rb. vLabel. import java.getObject("vButton").400). setSize(400.

"aButton" . new JButton("Validation du nombre")}. "a Label (en)" } }. } 5 Internationalization .} static { { { { { { { }. new JCheckBox("Oui (fr)")} .util. "vButton" . "Valid!" }. "une étiquette (fr CA)" } . { "aCheckbox".date. }. public class MyResources_fr extends ListResourceBundle { public Object [][] getContents() { return contents.java (english language resources)] The classname format is [name][language ID][country code]. public class myResources_fr_CA extends ListResourceBundle { public Object [][] getContents() { return contents. "Today {0. "numOK" . "aCheckbox". public class MyResources_en extends ListResourceBundle { public Object [][] getContents() { return contents. } [MyResources_fr_CA. new JCheckBox("Yes") } .long}"}.*.swing.####")}. You can retrieve a list of language IDs and country codes at the Unicode organization Web site import java. import javax.*. } final Object[][] contents = { "myLabel" .java (french language resources)] import java. } [MyResources_fr. new DecimalFormat("0.*.java (french language (for Canada) resources)] import java. } static final Object[][] contents = { { "aLabel" . "Valide!"}. new JButton("Validate number")}. { "vButton" . "une étiquette (fr)" } . "A Label" } .java. { "numERR".util. "Invalid"} [MyResources_en. } static final Object[][] contents = { { "aLabel" . } static final Object[][] contents = { { "aLabel" .util. { "numOK" . "Invalide"} }. "aNumber" .*. "numERR" .

getString("btnQuit")).getString("r0")). JLabel today. a ListResourceBundle.FRANCE. this.swing.awt. boolean defaultDone = false. java.html This HowTo lets you select a language and change its GUI to reflect the choice.util. 5. See this How−to. If a specific resource is not in a specific Locale ListResourceBundle then the default resource is used. JButton btnQuit.US. btnQuit. The properties files must have the . java.*. } public void initText() { setTitle (rb.getBundle("ResourcesDynamic".*. to store our resources.properties extension.3 Load resources dynamically Current version of this HowTo : http://www.setText(rb.awt.setText(rb. [InternationalDynamic.rgagnon. r2./javadetails/java−0134.java (main program)] import import import import import java. localeCurrent). int localeChoosen = 0.3 Load resources dynamically . java. r0. rb = ResourceBundle.*. javax.com/javadetails/.getString("r2")). public class InternationalDynamic extends JFrame implements ActionListener { static Locale[] localesSupported = { Locale. ButtonGroup bg.This example uses ListResourceBundle classes to store the required resources.setText(rb. JRadioButton r0. public void initLocale(){ localeCurrent = localesSupported[localeChoosen].GERMANY }. Locale. Locale localeCurrent. We have a class per Locale.. Locale.*. r1.*.setLocale(localeCurrent). ResourceBundle rb.text.event. 5. r2. We are using a special class.setText(rb.getString("title")). To use a properties file instead of a class to store resources then look at this HowTo. It is possible to substitute them for Properties files without any change to the code.getString("r1")). r1.

} else { if (localeChoosen == 0) r0. add(r0). btnQuit. // default RADIO button if (!defaultDone) { String rDef = rb.setSelected(true).addActionListener(this). else r2. bg.setSelected(true).Date d = new Date().add(r1). r2 = new JRadioButton().addActionListener(this).add(r0). } public void actionPerformed(ActionEvent ae){ if (ae. // r0.format(new Object [] { d })).3 Load resources dynamically .setSelected(true).setSelected(true). else r2. } public void initGUI(){ setLayout(new FlowLayout()).getString("rDefault").setText(mf. add(r1). today. localeCurrent). bg. bg. setSize(400. // today label today = new JLabel().getSource() == btnQuit) { System. else if (localeChoosen == 1) r1.addActionListener(this).addActionListener(this). } 5. if (rDef.100). add(today). defaultDone = true. r1 = new JRadioButton(). } // QUIT button btnQuit = new JButton(). MessageFormat mf = new MessageFormat (rb. r1. setVisible(true). add(r2).equals("r1")) r1.add(r2). r2. else if (rDef.exit(0). // RADIO buttons bg = new ButtonGroup().setSelected(true).equals("r0")) r0. add(btnQuit). r0 = new JRadioButton().getString("today").setSelected(true).

long}"}.*. else if (ae. { "r1".3 Load resources dynamically . { "rDefault" .java (english language resources)] import java. "Quit"}.pack().println("Current Locale : " + Locale. { "btnQuit" . "Quit"}. { "today" . { "r1".else if (ae. }.initLocale().*. Thread t = new Thread () { public void run() { InternationalDynamic i = new InternationalDynamic().date. "r0" }. initText().java (default resources)] import java. i. " (def) {0. pack(). "Example" }. } static final Object[][] contents = { { "title". } }. "r0" }.initGUI(). { "r2" . { "r0" . i.initText(). }. } } [ResourcesDynamic. { "r2" . { "today" . "France" } .long}"}. { "rDefault" . i. public class ResourcesDynamic_en extends ListResourceBundle { public Object [][] getContents() { return contents.out. "Germany"}. SwingUtilities.invokeLater(t). } static final Object[][] contents = { { "title".getDefault()). "United States" } . "Example" }. i.date. " (en) {0. "France" } .util. "Germany"}. "United States" } . } 5. public class ResourcesDynamic extends ListResourceBundle { public Object [][] getContents() { return contents. } public static void main(String args[]) { System. { "btnQuit" .util.getSource() == r1) localeChoosen = 1. { "r0" . else if (ae. } [ResourcesDynamic_en.getSource() == r2) localeChoosen = 2.getSource() == r0) localeChoosen = 0. initLocale().

to use properties file very easily. { "r2".dd. { "today" . { "rDefault". "Quitter" }. we must recompile the class. "r1" }. "Allemagne" }. Written and compiled by Réal Gagnon ©1998−2007 [ home ] 5. the ResourceBundle will construct the filename using the same 5. }.. "Frankreich" } . } static final Object[][] contents = { { "title".date.java (french language resources)] import java. from the programmer's point of view. "Deutschland" }. The drawback is when there is a modification. dd/MM/yyyy}"}. { "r0" . The JDK provides a class.[ResourcesDynamic_fr. With a resources file. In fact.java (german language resources)] import java. { "btnQuit".date. there is no difference if the resources are stored in classes or properties files. { "rDefault".com/javadetails/. The ResourceBundle will look first for classes and if not found. " (fr) {0.yyyy}"}. { "today" . "France" } . "Vereinigte Staaten" } . }. "Etats−Unis" } . the resources were stored in classes. we simply add or modify the resource in a special file with a regular text editor.html With the previous JAVA How−to.util. public class ResourcesDynamic_de extends ListResourceBundle { public Object [][] getContents() { return contents. { "r1". "verlassen"}.*. consider making a small donation to show your support for this Web site and its content. } static final Object[][] contents = { { "title".*. it will look for properties files. { "btnQuit"./javadetails/java−0135.4 Load resources via a resources file . } If you find this article useful. "r2" }. public class ResourcesDynamic_fr extends ListResourceBundle { public Object [][] getContents() { return contents.MM. { "r1". We don't have to specify filenames. "Beispiel" }.4 Load resources via a resources file Current version of this HowTo : http://www. { "r0" .util. "Exemple" }.rgagnon. } [ResourcesDynamic_de. PropertyResourceBundle. { "r2". " (de) {0.

format(new Object [] { d })). r2. JRadioButton r0.*.getString("title")).GERMANY }.getString("r2")).setText(rb.getString("r0")). boolean defaultDone = false.swing.setText(mf. } public void initGUI(){ setLayout(new FlowLayout()).FRANCE.*. Locale.mechanism used for classes. r1.getBundle("subdir.4 Load resources via a resources file .getString("r1")). 5. r1. JLabel today. Locale. rb = ResourceBundle. localeCurrent).text. For example.awt. java. Date d = new Date()." instead of "/". The file must have the extension .awt. int localeChoosen = 0. today. r2.util.getBundle("res. public void initLocale(){ localeCurrent = localesSupported[localeChoosen]. Locale localeCurrent. public class InternationalDynamic extends JFrame implements ActionListener { static Locale[] localesSupported = { Locale. JButton btnQuit. use ".*. MessageFormat mf = new MessageFormat (rb.getString("today").getString("btnQuit")). btnQuit. The ResourceBundle try to load the properties file from the current classpath.ResourcesDynamic".*. javax.*. localeCurrent). If the properties are stored in subdirectory .event. ButtonGroup bg. java.setText(rb. ResourceBundle rb. [InternationalDynamic. java. localeCurrent).java] import import import import import java. let's say that the properties file is in a subdirectory called "subdir" (from the current directory). Then you can load the ResourcesDynamic resources file with ResourceBundle. r0.setText(rb.ResourcesDynamic".properties.setText(rb.setLocale(localeCurrent). this. // RADIO buttons bg = new ButtonGroup(). } public void initText() { setTitle (rb.US.

100).add(r2). bg. } else if (ae.setSelected(true).getSource() == r0) localeChoosen = 0. } else { if (localeChoosen == 0) r0.getSource() == r1) localeChoosen = 1. r1. add(r1).getString("rDefault"). } public static void main(String args[]) { System. r1 = new JRadioButton(). } public void actionPerformed(ActionEvent ae){ if (ae. pack().addActionListener(this). defaultDone = true. } // QUIT button btnQuit = new JButton().equals("r1")) r1. initLocale().setSelected(true). // default RADIO button if (!defaultDone) { String rDef = rb. add(btnQuit). initText().println("Current Locale : " + Locale.addActionListener(this). setSize(400. if (rDef. setVisible(true). btnQuit. else if (localeChoosen == 1) r1.setSelected(true). r2 = new JRadioButton().setSelected(true). else if (rDef. // r0.setSelected(true).getSource() == r2) localeChoosen = 2. add(today). add(r0).add(r1).getSource() == btnQuit) { System.add(r0).setSelected(true).4 Load resources via a resources file .exit(0). bg.r0 = new JRadioButton(). add(r2). r2. // today label today = new JLabel(). 5. else r2.out.getDefault()). else if (ae.equals("r0")) r0.addActionListener(this). else if (ae. else r2.addActionListener(this). bg.

initGUI().invokeLater(t).4 Load resources via a resources file .yyyy} If you find this article useful. } } [RresourcesDynamic.Thread t = new Thread () { public void run() { InternationalDynamic i = new InternationalDynamic(). i.properties] title=Beispiel r0=Vereinigte Staaten r1=Frankreich r2=Deutschland rDefault=r2 btnQuit=Verlassen today=(de) {0.pack().date. Written and compiled by Réal Gagnon ©1998−2007 [ home ] 5.date.long} [ResourcesDynamic_fr.long} [RresourcesDynamic_en. i.properties] title=Exemple r0=Etats−Unis r1=France r2=Allemagne rDefault=r1 btnQuit=Quitte today=(fr) {0.initText().MM. } }. i. consider making a small donation to show your support for this Web site and its content.properties] title=Example r0=United States r1=France r2=Germany rDefault=r0 btnQuit=Quit today=(def) {0. i.initLocale().properties] title=Example r0=United States r1=France r2=Germany rDefault=r0 btnQuit=Quit today=(en) {0. dd/MM/yyyy} [ResourcesDynamic_de. SwingUtilities.dd.date.date.

/javadetails/java−0136.applet.*. Label b = new Label(REGISTERED + " R\u00e9al's Software " + " price : 100 " + EURO). Here a quick list for accented letters : á à â é è ê î ç \u00e0 \u00e1 \u00e2 \u00e9 \u00e8 \u00ea \u00ee \u00e7 Á À Â É È Ê Î Ç \u00c0 \u00c1 \u00c2 \u00c9 \u00c8 \u00ca \u00ce \u00c7 5. public static final String REGISTERED = "\u00ae".com/javadetails/. } } Output : Java not enabled! A list of Unicode characters is available at the Unicode organization Web site. The registered symbol ® : String REGISTERED = "\u00ae". The euro−currency sign € : String EURO = "\u20ac" For example : import java.html The copyright symbol © : String COPYRIGHT = "\u00a9"".5 Display "special character" using Unicode .5 Display "special character" using Unicode Current version of this HowTo : http://www.rgagnon. public static final String EURO = "\u20ac".Applet { public static final String COPYRIGHT = "\u00a9". add(a).5. Label a = new Label(COPYRIGHT + " R\u00e9al Gagnon").awt. public void init () { setLayout(new FlowLayout()). public class TestUnicode extends java. add(b)..

*.html This example will show 2 radio buttons. 5. Create 2 properties files. button.geocities.awt. one for english messages and buttons and the other one for french. AbstractButton button.com/javadetails/.*. one for english .add(button). public class MessageBoxExample extends JPanel implements ActionListener { JButton go. ButtonGroup group.7 Localize a JOptionPane dialog Current version of this HowTo : http://www.com/Tokyo/Pagoda/1675/ for a more complete overview. java.US. add(button).6 Display chinese/japanese characters Current version of this HowTo : http://www.netscape.properties] Yes=Oui No=Non Cancel=Annuler SaveMsg=Voulez−vous sauvegarder vos donnees Then import import import import javax.event.com/software/jdk/i18n.awt./javadetails/java−0138. // default value button = new JRadioButton("English". 5.util.6 Display chinese/japanese characters .rgagnon./javadetails/java−0137. locale = Locale.addActionListener(this).. button.*..properties] Yes=Yes No=No Cancel=Cancel SaveMsg=Do you want to save your data [JOptionPane_fr. true). java. Locale locale.swing. group. Press the button to display a localized JOptionPane according to the radio button selected. String msg . public MessageBoxExample() { group = new ButtonGroup().*.com/javadetails/.html and check also http://www. one for french.html A useful link to integrate international characters set in Netscape is http://developer.rgagnon.5. [JOptionPane_en. java.setActionCommand("en").

} } public Dimension getPreferredSize(){ return new Dimension(200.add(panel. } public static void main(String s[]) { JFrame frame = new JFrame(""). } public void actionPerformed(ActionEvent e) { int result.put("OptionPane. } } 5.getContentPane().setActionCommand("fr"). frame.getString("SaveMsg"). locale).button = new JRadioButton("Francais"). UIManager. MessageBoxExample panel = new MessageBoxExample().msg). frame. if (e.addActionListener(this).noButtonText".yesButtonText".getPreferredSize()). } public void setUILanguage() { ResourceBundle rb.getActionCommand().setSize(panel. go = new JButton("Do it"). add(go). button.println(result). rb. System.exit(0).FRANCE. add(button).getSource() instanceof JRadioButton) { if (e. } else { // the button action result = JOptionPane. button. frame. rb.out.getBundle("JOptionPane". rb.setVisible(true).cancelButtonText".US. msg = rb.add(button).put("OptionPane. group.equals("en")) locale = Locale. frame.addActionListener(this).getString("No")).put("OptionPane."Center"). rb = ResourceBundle.getString("Yes")). UIManager.getString("Cancel")). setUILanguage().addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System. UIManager. 200). go.showConfirmDialog(this.US. } } ). locale = Locale. else locale = Locale.6 Display chinese/japanese characters .

value).rgagnon.getDefault().util. public class NumberUtils { public static double getDoubleValue(String value) throws ParseException { // use the default locale return NumberUtils. import java.8 Validate/Convert a number using the current Locale() .out. } public static String convertStringAsStringNumberUnLocalized(String value) throws ParseException { // use the default locale return convertStringAsStringNumberUnLocalized(Locale.text. "42.println(NumberUtils.NumberFormat.text.getInstance(new Locale("us")).8 Validate/Convert a number using the current Locale() Current version of this HowTo : http://www.println(NumberUtils.getDefault(). } public static String convertStringAsStringNumberUnLocalized (Locale loc.println(NumberUtils. /* * output * fr_CA * 42.doubleValue().24")).getDoubleValue("42.getInstance(loc).ParseException.5.24 * 42. } public static void main(String[] args) throws Exception{ System. numbers with comma as decimal separator may be permitted. System. return NumberFormat. System. } public static double getDoubleValue(Locale loc.getDoubleValue("42.com/javadetails/.parse(value). value). System.html Depending on the International setting.getDefault()).0 * 42.out.getDoubleValue(loc.24")).getDoubleValue(Locale. import java.. value).24")).24 */ } } 5.Locale.out. String value) throws ParseException { // use the default locale return NumberFormat. String value) throws ParseException { double d = NumberUtils./javadetails/java−0139.out. The NumberFormat class can handle this based on the current Locale().convertStringAsStringNumberUnLocalized (new Locale("fr").println(Locale.format(d). import java.

one for english .awt.*. java.. one for french. java. So you don't have to do anything to display the JFileChooser in the right language.util.9 Localize a JFileChooser Current version of this HowTo : http://www.java] import import import import javax.properties] Title=Real's JFileChooser lookInLabelText=Current filesOfTypeLabelText=File type upFolderToolTipText=go up [JFileChooser_fr. Locale locale.*.event./javadetails/java−0299.0.5. include Swing dialogs. one for french (these files are incomplete but should be enough to get you started). as well as messages produced by the tools provided with the JRE.*.*. [JFileChooser_en. Create 2 properties files.properties] Title=JFileChooser de R\u00e9al lookInLabelText=Courant filesOfTypeLabelText=Type de fichier upFolderToolTipText=Remonte Then [LocalizeJFileChooser.com/javadetails/.html Modern Swing release have now built−in ready−to−use translations for the JFileChooser. java. public class LocalizeJFileChooser extends JPanel implements ActionListener { JButton go. ButtonGroup group.rgagnon. These user interface elements are localized into the following languages: Sun Supported Locales This example will show 2 radio buttons.awt. AbstractButton button. The language is choosen based on the current Locale. Press the button to display a localized JFileChooser according to the radio button selected. 5. one for english. messages written by the runtime environment to the standard output and standard error streams.swing.9 Localize a JFileChooser . The user interface elements provided by the J2SE Runtime Environment 5.

fileNameLabelText FileChooser.updateButtonToolTipText=Update FileChooser.cancelButtonToolTipText=Cancel FileChooser.listViewButtonToolTipTextlist FileChooser. // default value button = new JRadioButton("English". rb.US.saveButtonToolTipText=Save FileChooser.setActionCommand("en").helpButtonText=Help FileChooser. go. UIManager.add(button).put ("FileChooser.openButtonText=Open FileChooser.setActionCommand("fr"). true).getString("upFolderToolTipText")). button. button.US. add(button).put ("FileChooser.helpButtonToolTipText=Help Almost all Swing widgets can be customize this way. } public void setUILanguage() { ResourceBundle rb. button. rb = ResourceBundle.addActionListener(this).add(button). add(button).cancelButtonText=Cancel FileChooser. locale = Locale. You can 5. z_choosertitle = rb. UIManager.addActionListener(this).getString("lookInLabelText")).getString("Title").getString("filesOfTypeLabelText")).filesOfTypeLabelText". button. UIManager.String msg .updateButtonText=Update FileChooser.saveButtonText=Save FileChooser. add(go). protected JFileChooser z_chooser.lookInLabelText". go = new JButton("Do it"). public LocalizeJFileChooser() { group = new ButtonGroup().put ("FileChooser. rb.addActionListener(this). locale).homeFolderToolTipText FileChooser.detailsViewButtonToolTipText FileChooser.9 Localize a JFileChooser . locale = Locale. /* do the same with : FileChooser.getBundle("JFileChooser".openButtonToolTipText=Open FileChooser.upFolderToolTipText". group. rb. String z_choosertitle.newFolderToolTipText FileChooser. button = new JRadioButton("Francais"). group.

frame. if (e.equals("en")) locale = Locale.language=en −Duser.10 Disable localization Current version of this HowTo : http://www. you specify on the command line the locale to be used : java −Duser. if (z_chooser. LocalizeJFileChooser panel = new LocalizeJFileChooser(). frame.region=US MyApplication 5. z_chooser.setDialogTitle(z_choosertitle). } public static void main(String s[]) { JFrame frame = new JFrame("").com/javadetails/.com/papers/plafdiff. } } 5. else locale = Locale.APPROVE_OPTION) return."Center"). } else { z_chooser = new JFileChooser().showOpenDialog(this) != JFileChooser. } } public Dimension getPreferredSize(){ return new Dimension(200. z_chooser. To bypass this configuration.getSource() instanceof JRadioButton) { if (e.US.getContentPane(). */ } public void actionPerformed(ActionEvent e) { int result. 200).getPreferredSize()). } } ).io. the JVM uses the current locale as defined by the OS. setUILanguage(). frame.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.File(".setVisible(true).FRANCE..add(panel.examine the Swing sources to get these values or check http://www.setSize(panel.getActionCommand().html By default.rgagnon./javadetails/java−0418.html for a list of them. frame.10 Disable localization .exit(0).")).gargoylesoftware.setCurrentDirectory(new java.

doclet. consider making a small donation to show your support for this Web site and its content.properties (extract)] doclet./javadetails/java−0437.resources.ClassUse_Subinterface=Sous−interfaces de {0} dans {1} doclet.properties used by Javadoc to generated the labels.11 Generate the Javadoc "en français" . NOTE : Make sure the −locale switch is the first one.sun.doclets.resources).SerialData=Serial Data\: doclet. put your standard_fr.Warn_inline_taglet=Inline tag {0} should only be used with a {1}. Translate it (or you can download my "incomplete" version here).Since=Depuis\: doclet.sun. Extract from tools. in our case for french..jar in the lib directory contains the resource bundle standard.standard.ClassUse_Subinterface=Subinterfaces of {0} in {1} doclet.jar making sure that the file is located in the right package (along standard.html The javadoc utility uses the regular Java mechanism to internationalize its output. To add a new language. doclet.properties in com.Since=Since\: doclet. we need a file called standard_fr.. you need to create the appropriate resource bundle..11 Generate the Javadoc "en français" Current version of this HowTo : http://www.properties. [standard.Warn_inline_taglet=Inline tag {0} should only be used with a {1}.properties.Window_Split_Index={0}\: {1}−Index doclet. To generate in french. use the −locale switch on the command line javadoc −locale fr .. the standard. Using Ant. The tools.doclets.Frame_Version=Frame version doclet.If you find this article useful.Packages=Paquetages doclet.com/javadetails/.Window_Split_Index={0}\: {1}−Index doclet.Generated_Docs_Untitled=Documentation g\u00E9n\u00E9r\u00E9e Once everything translated.standard. <javadoc 5.SerialData=Donn\u00E9e s\u00E9rialis\u00E9e\: doclet. The new file must be in the package com. Copy it under the name standard_fr.properties into the tools.Packages=Packages doclet.rgagnon.Frame_Version=Version avec cadres doclet.properties files (keep the directory structure).tools. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 5.tools.jar.properties (extract)] doclet.Generated_Docs_Untitled=Generated Documentation (Untitled) [standard_fr.

. i < 4 .*.CASE_INSENSITIVE_ORDER).12 Sort a String array . for(int i=0. 2003 Real's Howto.out. "Real". public class TestSort1 { String [] words = { "Réal".io. consider making a small donation to show your support for this Web site and its content.sort(myArray. Take the following example : import java.util. // w.sort(myArray).java" destdir="javadoc/Client" author="true" version="true" use="true" private="true" windowtitle="Client"> <doctitle><![CDATA[<h1>Client</h1>]]></doctitle> <bottom><![CDATA[<i>Copyright &#169.write(words[i] + " "). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 5. Case insensitive java.write("Before :\n"). "Cp850")).12 Sort a String array Current version of this HowTo : http://www.Arrays.*. String. } public void doit() { try { // to be able output french character at the console Writer w = new BufferedWriter (new OutputStreamWriter(System. public static void main(String args[]) { new TestSort1().locale="fr" sourcefiles="c:/client/Client.Arrays.</i>]]></bottom> </javadoc> If you find this article useful./javadetails/java−0343. "Rico" }. import java. Case sensitive java.html Sort utilities are now part of latest JDK versions. i++) { w. 5.util.com/javadetails/. Sort with international characters. "Raoul".util.doit().rgagnon.

12 Sort a String array . sortArray(Collator. i++) { for (int j = i + 1.getInstance(loc). Locale loc = Locale. } catch(Exception e){} } } The output is : Before : Réal Real Raoul Rico After : Raoul Real Rico Réal which is wrong since we expect to find "Réal" after "Real".length.write("\n"). To solve the problem . } } } } 5.close(). by java..} java. } w. java. replace java. words).compare(strArray[i]. i++) { w. w.write("\nAfter :\n").length == 1) return..sort(words).sort(words).arrays.FRENCH)).. public static void sortArray(Collator collator.util.length.getInstance(Locale. strArray[j] ) > 0 ) { tmp = strArray[i].FRENCH. i < strArray.write(words[i] + " "). for (int i = 0.util. w. . j < strArray. strArray[i] = strArray[j]. and the output will be : Before : Réal Real Raoul Rico After : Raoul Real Réal Rico Or you can do it the long way : .sort(words. for(int i=0.arrays.flush(). w.util.collator. String[] strArray) { String tmp. strArray[j] = tmp.text. i < 4 . j++) { if( collator. if (strArray.Arrays..

notation • To avoid having to type all the \u.Collator frCollator = java.Collator. String s2 = "famille". If you find this article useful.14 Compare accentuated letters Current version of this HowTo : http://www./javadetails/java−0492. frCollator. } // (javadoc) // Collator..com/javadetails/.5. equal to or greater than zero // depending on whether the source String is less than. // Returns an integer less than.compare() compares the source string to the target string // according to the collation rules for this Collator. // // // // // // // // (javadoc) The result of String. // here we are expecting "é" < "f" if (s1.FRANCE)./javadetails/java−0496. // or frCollator. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 5.util.println("not ok s1 > s2 ")..setStrength(java. The result is zero if the strings are equal.html class Test { public static void main(String args[]) { String s1 = "état".Locale.out.rgagnon.CANONICAL_DECOMPOSITION)..SECONDARY). // equal to or greater than the target string. // to be non case sensitive 5.text.. consider making a small donation to show your support for this Web site and its content.text. compareTo returns 0 exactly when the equals(Object) method would return true..compareTo() is a negative integer if this String object lexicographically precedes the argument string.13 Accentuated characters in Properties/ResourceBundle file .setStrength(java.com/javadetails/.text..Collator.html The rules are • Only use ISO Latin 1 characters in the Properties/ResourceBundle files • For other characters use the \u. java. use the native2ascii tool (included with the SDK). The result is a positive integer if this String object lexicographically follows the argument string.rgagnon.13 Accentuated characters in Properties/ResourceBundle file Current version of this HowTo : http://www.text. notation manually.compareTo(s2) > 0) { // s1 lexicographically follows s2 which is not true! System.Collator..getInstance(java.

since the class is in sun.Collator frCollator = java.compare(s1.15 Unaccent letters Current version of this HowTo : http://www.compareTo(s2) != 0) { System. } java. } } } NOTE: Also. 5.println("ok s1 == s2 "). Windows. Macintosh. Linux. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 5.rgagnon.com/javadetails/.println("ok s1 < s2 ").out.Locale. and are not supported. s2) < 0) { // s2 lexicographically follows s1 System.util.Normalizer class.* package./javadetails/java−0456. writing java programs that rely on sun. 1.getInstance(java.Collator.text.) and can change at any time without notice with SDK versions (1.text.Normalizer class. However. if (frCollator. etc). Technique 1 It's a simple using the sun.2. s2) == 0) { // s2 lexicographically follows s1 System. For an alternative to the sun. another possibility is to convert to uppercase/lowercase both items to be compared.text. In general. consider making a small donation to show your support for this Web site and its content.2. it is considered outside of the Java platform.SECONDARY).html The following snippet removes from a String accented letters and replace them by their regular ASCII equivalent.text. frCollator. } } } Equality class Test { public static void main(String args[]) { String s1 = "état". // here we are expecting "état" == "État" if (s1.out. you may to take a look at IBM's ICU4J project on SourceForge.text.FRANCE). can be different across OS platforms (Solaris..println("not ok s1 != s2 "). etc. String s2 = "État".setStrength(java.out.15 Unaccent letters . This can be useful before inserting data into a database to made sorting easier.1.3. If you find this article useful.2.Collator.if (frCollator.compare(s1. 1.* is risky: they are not portable.

} } A note from ajmacher: The Normalizer API changed in JDK6.text.4 import sun.â.À.O. it can now be found in java. replaceAll() and regular expressions on a String can also be used : public class Test { public static void main(String args[]) { String s = "È."").e."I").i.We are calling the normalize() with the option DECOMP (for decomposition. So we need to detect the position in the first 5.Ï. s."O").I.Ô.o } } Technique 3 While the two techniques above are ok.15 Unaccent letters .ô".a.A.Ë."a").û. return temp.replaceAll("Ô".text. s.text. s.ë.a."E").ï.e."i").É. Try : java.è. s. s. 0). see Unicode Normalization). there are a little bit slow."A").NFD). we clean up the string to keep only valid US−ASCII characters...I.E. s. java.Î.Form.î. JDK1.text.ù.replaceAll("[àâ]".replaceAll("[ÏÎ]"."U").A. // output : e a i _ @ } public static String formatString(String s) { String temp = Normalizer.out.Ê."o").replaceAll("[ïî]".e.Â.println(formatString(value))."u"). public static void main(String args[]) throws Exception{ System.replaceAll("Ô".à.normalize(s.replaceAll("[ÀÂ]".replaceAll("[èéêë]". s.replaceAll("[ÈÉÊË]". s. So if we pass à.DECOMP. the method returns a + ` .E. s s s s s s s s s s = = = = = = = = = = s.e. Then using a regular expression.Normalizer.U.Û. s.normalize(s.out.Normalizer. public class Accent { public static String value = "é à î _ @".Normalizer and its usage is slightly different (but enough to break it).println(s).replaceAll("[^\\p{ASCII}]". Normalizer.U.u. The following HowTo is faster because we using one String to contain all the possible characters to be converted and a String with the ASCII equivalent. so Technique 1 will cause compiler errors in JDK6.é. System..Normalizer. // output : E. Technique 2 As an alternative.Ù.ê.E.u.i.."e").replaceAll("[ûù]".replaceAll("[ÛÙ]".

charAt(i).a.ë.e. } else { sb.charAt(pos)).out. Hague for the missing "double acute".î.println(AsciiUtils. i++) { char c = s.e.É.Â.Ô. int pos = UNICODE. private static final String UNICODE = "\u00C0\u00E0\u00C8\u00E8\u00CC\u00EC\u00D2\u00F2\u00D9\u00F9" + "\u00C1\u00E1\u00C9\u00E9\u00CD\u00ED\u00D3\u00F3\u00DA\u00FA\u00DD\u00FD" + "\u00C2\u00E2\u00CA\u00EA\u00CE\u00EE\u00D4\u00F4\u00DB\u00FB\u0176\u0177" + "\u00C3\u00E3\u00D5\u00F5\u00D1\u00F1" + "\u00C4\u00E4\u00CB\u00EB\u00CF\u00EF\u00D6\u00F6\u00DC\u00FC\u0178\u00FF" + "\u00C5\u00E5" + "\u00C7\u00E7" + "\u0150\u0151\u0170\u0171" .a. // private constructor. Tama for the missing Ñ ! Thanks to T. can't be instanciated! private AsciiUtils() { } // remove accentued from a string and replace with ascii equivalent public static String convertNonAscii(String s) { if (s == null) return null.ù.E.e.String and then do a lookup in the second String..u.append(c).I.ç".ô.Ë. } } return sb.i. int n = s.â.e.Ê.A.A.indexOf(c).convertNonAscii(s)).Î.À. if (pos > −1){ sb. 5.ï.ê.append(PLAIN_ASCII.U.à.o. System.u.E.Ù.E. i < n.è.I.Û. for (int i = 0.toString().O. // output : // The result : E. public class AsciiUtils { private static final String PLAIN_ASCII = "AaEeIiOoUu" // grave + "AaEeIiOoUuYy" // acute + "AaEeIiOoUuYy" // circumflex + "AaOoNn" // tilde + "AaEeIiOoUuYy" // umlaut + "Aa" // ring + "Cc" // cedilla + "OoUu" // double acute .Ï. } public static void main(String args[]) { String s = "The result : È.û.15 Unaccent letters .U.é.c } } Thanks to MV Bastos for the "tilde" bug fix Thanks to L. StringBuffer sb = new StringBuffer().length().i.

encoding=Cp850 MyApp Alternate technique import java.com/javadetails/.flush(). you must specified a different encoding when printing to a DOS console.write(javaString). java −Dfile.*. } catch (UnsupportedEncodingException error) { System. public class test { public static void main(String[] args) { PrintStream ps = null. import java.io. // Unicode for "é" try { ps = new PrintStream(System. } ps.5. Then you will be able to use regular System. "Cp850")).16 Output french characters to the console . w. w.err. } } Note : List of supported encodings here 5. public class DosString { public static void main(String args[]){ String javaString = "caractères français : à é \u00e9".println(error).rgagnon./javadetails/java−0046. This is done via the OutputStreamWriter class.out.16 Output french characters to the console Current version of this HowTo : http://www. System. } } } An alternative is to start the JVM and pass on the command line the default file encoding to be used. true.close().html Since Java string are Unicode encoded.exit(0).out. "Cp850"). // Unicode for "é" try { // output to the console Writer w = new BufferedWriter (new OutputStreamWriter(System.println().println(javaString). w. } catch (Exception e) { e..printStackTrace().out. String javaString = "caractères français : à é \u00e9".io.*.

ByteArrayOutputStream()).*.nio. // jdk1.rgagnon.out.OutputStreamWriter( new java.println(System.io. // jdk1.18 Convert OEM (DOS) file to Ansi (Windows) Current version of this HowTo : http://www.5.io.17 Get the default character set of the JVM Current version of this HowTo : http://www./javadetails/java−0505.println(java.name()). consider making a small donation to show your support for this Web site and its content. import java.rgagnon.io.out. This can be useful when migrating data from a legacy database (ex.. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 5. System.length != 2) { System.17 Get the default character set of the JVM . public class OemToAnsi { public static void main(String args[]) throws Exception{ if (args. } } Output example (winXP) >java Hello Cp1252 Cp1252 windows−1252 See also java encoding table for the encoding sets supported. Clipper.4 System.out. mySQL.getEncoding() ).println( " note : codepage input Cp850 codepage output Cp1252" )./javadetails/java−0524.getProperty("file. dBase) to newer DBMS (ex.com/javadetails/.encoding")). If you find this article useful.out.Charset.out. Sybase).println( "Usage : java OemToAnsi inputdosfile outputansifile" ).5 System.html We are using an InputStreamReader which convert the specified input encoding to Unicode and an OutputStreamWriter which from Unicode to the specified output encoding.html public class Hello { public static void main(String args[]) throws Exception{ // not crossplateform safe System.println( new java.com/javadetails/. 5.defaultCharset()..charset.

out. byte bytearray [] = test. java.newDecoder(). java.decode(ByteBuffer. w.CharsetDecoder. BufferedReader r = new BufferedReader(new InputStreamReader(fis. } w. java.nio. } // input FileInputStream fis = new FileInputStream(args[0]). // output FileOutputStream fos = new FileOutputStream(args[1]). it contains an accented letter String test = "Réal". } catch(CharacterCodingException e) { System.Charset. consider making a small donation to show your support for this Web site and its content. } } See also this related HowTo If you find this article useful.nio.System.close().nio.com/javadetails/.19 Detect non−ASCII character in a String Current version of this HowTo : http://www.println("Test string : " + test). "Cp1252")).ByteBuffer.. System.html import import import import import java. r. // this String is OK //String test = "Real".nio. "Cp850")). CharsetDecoder d = Charset.19 Detect non−ASCII character in a String . String oemString = "". public class TestAscii { public static void main (String args[]) throws Exception { // this String throws an Exception./javadetails/java−0536.flush().close().out.write(oemString). Writer w = new BufferedWriter(new OutputStreamWriter(fos.CharacterCodingException.wrap(bytearray)).readLine()) != null) { w. while ( (oemString= r.charset. Written and compiled by Réal Gagnon ©1998−2006 [ home ] 5.rgagnon. System.charset.forName("US−ASCII").println("only regular ASCII characters please!").charset.exit(0).exit(1).toString().CharBuffer.nio. try { CharBuffer r = d. java. r.getBytes(). // interrupt the processing 5.

println("Ok.19 Detect non−ASCII character in a String .throw new Exception(e). } } Another way is to use a regular expression. it's ASCII only!").com http://www. see this Javascript HowTo for a hint! Written and compiled Réal Gagnon ©2007 real@rgagnon.com 5. } System.out.rgagnon.

setOut(aPrintStream). RedirectedFrame(boolean logFile) { this. addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { dispose(). boolean logFile. setTitle("Error message"). off . add("Center" . aTextArea.2 Redirect output(stdout/stderr) to a frame Current version of this HowTo : http://www./javadetails/java−0028.1 java−io 6.*. System.*.io.com/javadetails/. import java. import java. } } ). } class FilteredStream extends FilterOutputStream { public FilteredStream(OutputStream aStream) { super(aStream).append(aString).logFile = logFile. len). int len) throws IOException { String aString = new String(b ..6 IO 6.html [JDK1.*. aTextArea. if (logFile) { 6 IO .awt. PrintStream aPrintStream = new PrintStream( new FilteredStream( new ByteArrayOutputStream())). aTextArea). } public void write(byte b[]. int off.1] import java. public class RedirectedFrame extends Frame { TextArea aTextArea = new TextArea(). } public void write(byte b[]) throws IOException { String aString = new String(b).rgagnon. setSize(500. displayLog(). System.awt. setLayout(new BorderLayout()).300).setErr(aPrintStream).event.append(aString).

width) / 2. setLocation((dim. e.forName("unknown").3 Redirect printStackTrace() to a String Current version of this HowTo : http://www. public class TestStack2String { public static void main(String s[]){ try { // force an exception for demonstration purpose Class.height) / 2).write(aString).height − abounds./javadetails/java−0029.log".printStackTrace(pw).html import java. e. aWriter. } catch (Exception e) { // for applet.println(stack2string(e)).out.rgagnon. 6. } } } Check also this simple Swing solution. } public static void main(String s[]){ try { // force an exception for demonstration purpose Class. setVisible(true). (dim.3 Redirect printStackTrace() to a String .forName("unknown"). Rectangle abounds = getBounds(). return "−−−−−−\r\n" + sw. true). PrintWriter pw = new PrintWriter(sw). // or this could be changed to: // throw new Exception().toString() + "−−−−−−\r\n".io.width − abounds. Dimension dd = getSize(). } catch (Exception e) { System.printStackTrace(). } 6.newInstance().newInstance().*. } } } public void displayLog() { Dimension dim = getToolkit().FileWriter aWriter = new FileWriter("error..getScreenSize(). aWriter. } } public static String stack2string(Exception e) { try { StringWriter sw = new StringWriter(). always RedirectedFrame(false) RedirectedFrame r = new RedirectedFrame(true).close(). requestFocus().com/javadetails/.

w. w.exit(0). w.rgagnon. // Unicode for "é" try { ps = new PrintStream(System.*./javadetails/java−0046. java −Dfile. } catch (Exception e) { e. you must specified a different encoding when printing to a DOS console.println(javaString). This is done via the OutputStreamWriter class. 6.close().html Since Java string are Unicode encoded.com/javadetails/.4 Output french characters to the console . "Cp850")).io.println(). String javaString = "caractères français : à é \u00e9".out.out. public class test { public static void main(String[] args) { PrintStream ps = null.*.flush(). "Cp850"). System. } ps.write(javaString). } } } An alternative is to start the JVM and pass on the command line the default file encoding to be used. } } } 6.io.4 Output french characters to the console Current version of this HowTo : http://www.encoding=Cp850 MyApp Alternate technique import java. true. // Unicode for "é" try { // output to the console Writer w = new BufferedWriter (new OutputStreamWriter(System. import java. Then you will be able to use regular System.printStackTrace(). public class DosString { public static void main(String args[]){ String javaString = "caractères français : à é \u00e9".println(error).out.catch(Exception e2) { return "bad stack2string".. } catch (UnsupportedEncodingException error) { System.err.

println (ANSI_HOME + ANSI_WHITEONBLUE + "Hello world" + ANSI_NORMAL).out. System.out.}catch(Exception e){} System.out. you need something like this in the CONFIG. System.print (ANSI_BOLD + "Press a key.EXE does not support ANSI escape sequences. i++) System.com/javadetails/.SYS. System.println(ANSI_CLS).println (ANSI_AT55 + ANSI_REVERSEON + "Hello world" + ANSI_NORMAL).out. see this HowTo) is to use brute force. String ANSI_HOME = "\u001b[H". The Good news is that you can use COMMAND.out. this can be done with the driver ANSI.SYS : device=c:\windows\command\ansi.5 Clear the console and control attributes Current version of this HowTo : http://www.5 Clear the console and control attributes .read().10H". String ANSI_NORMAL = "\u001b[0m".SYS's Escape Sequences.44m". String ANSI_AT55 = "\u001b[10.} } Note : List of supported encodings here 6. i<25. To use ANSI./javadetails/java−0047. String ANSI_WHITEONBLUE = "\u001b[37. System. For example. String ANSI_REVERSEON = "\u001b[7m".SYS is loaded via the CONFIG.println().SYS file. for (int i=0.println(ANSI_CLS).NT file: dosonly device=c:\winnt\system32\ansi.html On Win9x.. String ANSI_BOLD = "\u001b[1m".rgagnon. add the following lines in the CONFIG..sys But the bad news is that you are restricted this way to run only DOS−based application so it won't work for Java stuff!!! So the only solution left for NT (unless you write some JNI functions." + ANSI_NORMAL). NT's CMD.COM instead.in.out. on Win9x installation.sys Then you send the appropriate escape codes to the console public class AnsiConsole { public static void main(String args[]) { String ANSI_CLS = "\u001b[2J". try {System.. } } NOTE: Check this "old" text file to have an overview of ANSI. 6.

*.getText().write(0x0D).setDialog(JobAttributes. "PrintJob". For example. // the printer to be used PrintJob myJob = getToolkit()./javadetails/java−0051. theJobAttribs. theJobAttribs.rgagnon.getGraphics().printStackTrace(). } myJob. if (myJob != null) { Graphics g = myJob. on a Windows machine : import java./javadetails/java−0350.rgagnon..NONE).write("Hello world").io.html A quick and simple way to output some text to a printer is to print to OS logical device attached a printer. public class SimplePrinting { public static void main(String[] args) { try { FileWriter out = new FileWriter("lpt1").end().6 Print text to a printer easily Current version of this HowTo : http://www. theJobAttribs. out.. s). thePageAttribs).dispose(). g.html JobAttributes theJobAttribs = new JobAttributes().close(). out.7 Print without a Dialog Current version of this HowTo : http://www.getPrintJob(this. } catch (IOException e) { e. g.com/javadetails/. if (g != null) { String s = myArea.If you find this article useful.com/javadetails/. PageAttributes thePageAttribs = new PageAttributes(). } } } 6.DialogType.setPrinter("HP DeskJet 610C"). // what you like to print printText(myJob.6 Print text to a printer easily . // CR out. consider making a small donation to show your support for this Web site and its content. } 6. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 6.

DataInputStream in = new java. String aLine = in.io. try { System. } } } Second method JDK1.out. try { aLine = input.8 Simple input from the keyboard .2 java.nextToken(). } catch (Exception e) { e.InputInt("<prompt>") for an integer.println("Hi " + Input. System. BufferedReader input = new BufferedReader(new InputStreamReader(System. public class TestReadLine { public static void main (String args[]) { StreamTokenizer Input=new StreamTokenizer(System. try { i = Integer.out.printStackTrace().printStackTrace().io.*.6.parseInt(input.sval + "!"). System.com/javadetails/.print(" Your first name : ").printStackTrace(). use EasyInput.1 In you program. } catch (Exception e) { e. Third method JDK1. int i =0.readLine()). } public static String inputStr(String s) { String aLine = "".print(s)./javadetails/java−0053.readLine().print(s). } return aLine.in)). } return i.in).out.. public class EasyInput { public static int inputInt(String s) { BufferedReader input = new BufferedReader(new InputStreamReader(System.io.0.rgagnon.8 Simple input from the keyboard Current version of this HowTo : http://www.out. } catch (Exception e) { e.in)).in).inputStr("<prompt>") to input a String or EasyInput. } 6. System.DataInputStream(System. Input.readLine().html First method import java.

System. BufferedOutputStream bos = new BufferedOutputStream( fos ). portname. "start".com/javadetails/. Then to write.com". if( p.println("Error executing command: " + cmd ).exit( −1 ).out. public class SerialTest { public static void main( String args[]) { Runtime rt = Runtime.close(). int m = inputInt("Month: ").com // c:\\windows\\command\\mode. } } } 6.5 provides the Scanner class to do this. fos. (Win)Initialization is done via the MODE. } catch( Exception e ) { e.html This is for JAVA application only (JDK1. } byte data[] = "Writing a byte stream out of a serial port. "baud=9600".waitFor() != 0 ) { System. try { p = rt. String portname = "com1:".write( data. You can use the same technique to print to the printer port (in this case the local name would be "LPTx:").9 Initialize and write to a serial port .exe". "stop=1". String you = inputStr("Your name: ").9 Initialize and write to a serial port Current version of this HowTo : http://www. 0. "/c". simply open a stream using the OS logical name attached to the serial port.rgagnon.exec( cmd ).getBytes().public static void main(String s[]) { while(true) { int y = inputInt(" Year: ")./javadetails/java−0062.println(you + " " + y + m + d). "data=8".getRuntime().COM utility. "c:\\winnt\\system32\\mode..". 6.out.1). // for Win95 : c:\\windows\\command. System.length ). fos. data. Process p = null. int d = inputInt(" Day: "). FileOutputStream fos = new FileOutputStream( portname ).com String cmd[] = { "c:\\winnt\\system32\\cmd.printStackTrace(). "parity=n". } } } NOTE: JDK 1. }. "/min". see this HowTo.

if (name == null || name.filechooser. // Unix style PrintStream nps = new PrintStream(new FileOutputStream("/dev/null")).io.10 Redirect to a NULL device . If you find this article useful.trim()./javadetails/java−0455.rgagnon. System.getSystemDisplayName(dir).html This will retrieve the hard disk volume label : import java.. } int index = name. System. File dir = new File(path).rgagnon. if (name == null) { return null.setOut(nps).com/javadetails/.out. } 6.setOut(new java.. } name = name.substring(0. import javax. System.lastIndexOf(" ("). //Windows style PrintStream nps = new PrintStream(new FileOutputStream("NUL:")).html This can be useful if you want to suppress all output. index). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 6./javadetails/java−0453.length() < 1) { return null.*.setErr(nps)..10 Redirect to a NULL device Current version of this HowTo : http://www. public class VolumeLabel { private VolumeLabel() { } public static void main(String[] args) { System.io.setOut(nps).println("\"" + get(args[0]) + "\"").6.setErr(nps). if (index > 0) { name = name. } public static String get(String path) { FileSystemView view = FileSystemView. consider making a small donation to show your support for this Web site and its content. System.swing.getFileSystemView().io.11 Get the volume label Current version of this HowTo : http://www. System.com/javadetails/. //One−liner style : subclass OutputStream to override the write method . String name = view.*.OutputStream() { public void write(int b){}})).PrintStream(new java..

Scanner sc = new Scanner(input). One easy way on the Windows plateform is to call a VBS script. The resulting tokens may then be converted into values of different types using the various next methods.html Java provides no way to interact with a cd drive./javadetails/java−0574.rgagnon. 6. consider making a small donation to show your support for this Web site and its content.13 Open or close a CD/DVD drive Current version of this HowTo : http://www.5) . which by default matches whitespace. System. class TestScanner { public static void main(String args[]) { String input = "10:11:12".5) Current version of this HowTo : http://www.out.com/javadetails/.hasNextInt()) { int i = sc.println(i).. } } } If you find this article useful.nextInt().util.useDelimiter(":"). import java.html A Scanner breaks its input into tokens using a delimiter pattern.com/javadetails/.return name. } } The output Running from c:\temp >java VolumeLabel c: "temp" >java VolumeLabel c:\ "HARDDISK1" If you find this article useful./javadetails/java−0491.*. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 6. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 6.12 Easy keyboard input (JDK1.rgagnon. consider making a small donation to show your support for this Web site and its content.. while (sc.12 Easy keyboard input (JDK1.

JOptionPane. FileWriter fw = new FileWriter(file).io. Runtime.DEFAULT_OPTION).close().File. // Thread. } catch(Exception e){ e.12 Easy keyboard input (JDK1.io. javax.getRuntime().vbs").write(vbs).Eject".Component) null.DEFAULT_OPTION).JOptionPane. // thanks to TrueJavaProgammer for the waitFor() tip! // Runtime. FileWriter fw = new java.getPath()).In this HowTo. This technique is useful to do something that a regular Java can't do because it's too specific to OS where the Java is running. javax. "CDUtils".close().getRuntime(). fw.Eject \n " + "cd.exec("wscript " + file. we are creating a temporary vbs file and execute it.Component) null. javax.waitFor().FileWriter.showConfirmDialog((java. The vbs file is created in the "temporary" folder and is deleted by the JVM at the end.awt.deleteOnExit().waitFor().sleep(2000). fw.printStackTrace().printStackTrace().getPath()).". "Press OK to open CD".swing. import java.OCX\") \n" + "Set cd = wmp. fw. // Thread. "CDUtils".write(vbs).getByDriveSpecifier(\"" + drive + "\") \n" + "cd.io.5) .waitFor(). // to close a CD. file.swing.cdromCollection.vbs"). } } public static void close(String drive) { try { File file = File. import java.exec("wscript " + file.FileWriter(file). public class CDUtils { private CDUtils() { } public static void open(String drive) { try { File file = File. 6. fw.cdromCollection.getByDriveSpecifier(\"" + drive + "\") \n" + "cd. Runtime.getPath()). String vbs = "Set wmp = CreateObject(\"WMPlayer.getRuntime().deleteOnExit(). CDUtils.showConfirmDialog((java.sleep(2000).createTempFile("realhowto".getPath()).OCX\") \n" + "Set cd = wmp.JOptionPane.getRuntime().open("D:\\"). file.JOptionPane. we need eject two times! String vbs = "Set wmp = CreateObject(\"WMPlayer.awt.swing.exec("wscript " + file.swing.createTempFile("realhowto". "Press OK to close CD".". // thanks to TrueJavaProgammer for the waitFor() tip! // Runtime.Eject ". } catch(Exception e){ e. } } public static void main(String[] args){ javax.exec("wscript "+ file.

CDUtils.14 Get faster console output (System..out.print("abcdefghijk "). java.out..args) throws Exception { BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new 6.println() replacement) Current version of this HowTo : http://www. } } The result is >java Test >NUL Loop time: 7000 Now.FileDescriptor.com/javadetails/..io. i++) { System. By default.out. rewrite this program to use a 512−bytes buffer and specify the ASCII as character−encoding to be used. } } NOTE : Windows Media Player version 7 or later is required 6. the overall execution time will be better.print(String.io.BufferedWriter.valueOf(i))..io. Each line is flushed right away.FileOutputStream.OutputStreamWriter.println() is not well suited to handle many repetitive outputs in a batch mode.close("D:\\").println() replacement) . java.out.14 Get faster console output (System.rgagnon. import import import import java.println() then it is possible to get a good performance boost by using an alternative to do the console output. Because of its small buffer size. java. System.out. If your output is mainly ASCII−based then by removing the Unicode−related activities. public class Test { public static void main(String.out.OutputStreamWriter. Consider this program : import import import import java./javadetails/java−0603.err.FileDescriptor.html If your program is doing a lot printing to the console using System.io. System. } System.println("Loop time: " + (System. System. System.out. java.io.print() is only line−buffered and does a lot work related to Unicode handling.currentTimeMillis() − start)). for (int i = 0..args) throws Exception { long start = System. public class Test { public static void main(String.BufferedWriter.FileOutputStream.io.currentTimeMillis(). java.io. i < 1000000.out.io.print('\n'). java.

readLine()) != null) { System.html Be sure to read this Javaworld article. } input. out.write(String.write('\n').16 Using Runtime.println("Loop time: " + (System. i < 1000000.rgagnon. System. Process p = Runtime.flush().exec() This example will capture the output (from stdio) of an external program.15 Execute an external program Current version of this HowTo : http://www.exec() method..println(line).valueOf(i)). "ASCII")./javadetails/java−0014.close(). It describes the various pitfalls related to the Runtime.FileOutputStream(java. } catch (Exception err) { err. while ((line = input.write("abcdefghijk "). 6.out). 6.io.exec (System. } } The result is >java Test >NUL Loop time: 672 Note that your result will vary depending on your machine/java version but the performance gain should in the same magnitude.currentTimeMillis(). 512). out.printStackTrace().currentTimeMillis() − start)). } } } 6. } out. BufferedReader input = new BufferedReader (new InputStreamReader(p. public class CmdExec { public static void main(String argv[]) { try { String line. for (int i = 0.com/javadetails/. i++) { out.err.FileDescriptor.com /A").io.*.getenv("windir") +"\\system32\\"+"tree.15 Execute an external program .getInputStream())). import java.out. long start = System.getRuntime().

// launch EXE and grab stdin/stdout and stderr Process process = Runtime. stderr = process. stdin. InputStream stderr = null. 6. stdout = process.readLine ()) != null) { //System.flush(). stdin. p.println(p. stdin.flush().The next example. line = "param3" + "\n".write(line.waitFor(). String line.write(line. while ((line = brCleanUp. stdin = process.write(line. System.exe").println ("[Stdout] " + line).17 Launch a Windows CMD (or BAT) file and retrieve the errorlevel or exitcode . } brCleanUp.getBytes() ). launch CMD.getBytes() ).close().io. while ((line = brCleanUp. } catch (Exception err) { err.out.readLine ()) != null) { //System.17 Launch a Windows CMD (or BAT) file and retrieve the errorlevel or exitcode // win xp import java.getRuntime ().println ("[Stderr] " + line). stdin.exitValue()).getBytes() ). line = "param2" + "\n". } brCleanUp.getRuntime(). stdin.getInputStream ().printStackTrace().getOutputStream ().close(). InputStream stdout = null.close().EXE. grab stdin/stdout and push to stdin command to be interpreted by the shell.exec("test.out.out. stdin. OutputStream stdin = null.flush(). // "write" the parms into stdin line = "param1" + "\n".cmd"). public class CmdExec { public static void main(String argv[]) { try { String line.getErrorStream (). // clean up if any output in stdout BufferedReader brCleanUp = new BufferedReader (new InputStreamReader (stdout)). Process p = Runtime. stdin. // clean up if any output in stderr brCleanUp = new BufferedReader (new InputStreamReader (stderr)). } 6.*.exec ("/folder/exec.

System.environment().readLine()) != null) { System.*.getenv("temp") ). Map<String.add(System.start(). Runtime. InputStream is = process. String line. command. BufferedReader br = new BufferedReader(isr). 6.directory(new File(System.com").getenv("windir") +"\\system32\\"+"tree.getInputStream(). public class CmdProcessBuilder { public static void main(String args[]) throws InterruptedException.cmd (set the errorlevel manually) @echo hello world @exit 42 test. "ls > hello"}. import java.cmd (set the errorlevel 1 (problem detected) @java −garbage test.18 Launch a Unix script . } } 6.IOException { List<String> command = new ArrayList<String>().add("/A").out.exec(cmd). It's possible to set a starting directory. ProcessBuilder builder = new ProcessBuilder(command).cmd (set the errorlevel 0 (execution Ok) @java −version 6.io.println(line).5. InputStreamReader isr = new InputStreamReader(is). String> environ = builder.out.util. final Process process = builder.18 Launch a Unix script String[] cmd = {"/bin/sh".getRuntime().getenv("temp"))).*.println("Program terminated!"). builder. the ProcessBuilder class provides more controls overs the process to be started.out. import java.} } test. } System. "−c".19 Using the ProcessBuilder Since 1. command.println("Directory : " + System. while ((line = br.

rnaui.").doc // to start Word if the doc extension is associated with it.22 PDF (Mac only) public class ShowPDF { public static void main (String[] args) throws Exception{ Process p = Runtime.20 Windows rundll32 utility Windows File association Any program using the Windows file association mechanism can be started with the rundll32 utility.DLL. rasdial "connection name" rasdial "connection name" /d to drop rasdial /? for more options 6.RnaDial MyConnection").println("Done.waitFor().exec("open /Documents/mypdf.getAbsolutePath()).println("Done.out.out.getRuntime(). Use rasdial. System.dll. } } 6.exe instead. See also this one to open the default browser.6). You still need to press ENTER to CONNECT. See also this HowTo about the new Desktop API.getRuntime() .exec ("rundll32 SHELL32.java] public class Dialup { public static void main(String[] args) throws Exception { Process p = Runtime.getRuntime() . The following example start a Dial−up connection on the Win plateform : [Dialup. On NT and W2K. // "file" is the filename of the data file // ex.pdf"). p.waitFor(). there is an option in the Connection properties to connect automatically.getRuntime(). p. Runtime. myresume.FileProtocolHandler c:/pdf/mypdf.dll is not available. } } The "MyConnection" is the DUN and it's case sensitive.exec("rundll32.ShellExec_RunDLL " + file. } 6.dll.21 PDF (Windows only) public class ShowPDF { public static void main(String[] args) throws Exception { Process p = Runtime.exec("rundll32 url. the recommended solution (but you need JDK1.").20 Windows rundll32 utility . System.pdf").6.exe rnaui.

exe\""). String[] commands = {"cmd".exec("cscript myscript.} More runddl32 examples 6.exec(commands).vbs").vbs").getRuntime().exec(cmd). // WinNT Runtime.IOException. } } If you need to pass arguments.getRuntime().exec("start myscript. 6.25 HTML Help (Windows only) Runtime. class StartExcel { public static void main(String args[]) throws IOException 6.getRuntime().exe".exec("wscript myscript. String fileName = "c:\\Applications\\My Documents\\test.getRuntime().exec( "\"c:/program files/windows/notepad. it's safer to a String array especially if they contain spaces. you need to put the path in quotes if the path contains spaces.vbs"). "−o=This is an option" }. "\"DummyTitle\"". String[] cmd = { "myProgram.getRuntime().vbs").26 Start Excel import java.24 VBSCRIPT // Win9x Runtime.io. Runtime. or // with a visible console Runtime.exec("hh.exec("cmd /c start myscript.fileName}.getRuntime(). "/c". 6. public class Test { public static void main(String[] args) throws Exception { Process p = Runtime.getRuntime().getRuntime(). // with no visible console Runtime.23 Path to executable with spaces in them . "start".waitFor(). 6. If using the start command and the path of the file to be started contains a space then you must specified a title to the start command.exe myhelpfile.doc".chm"). p.23 Path to executable with spaces in them You can include a path for the program to be executed. On the Win plateform. Runtime.

27 Start a Windows application under another account . create a new DWORD value named HideRunAsVerb and assign it a value of 1 to disable Run as. The command runas /savecred /user:administrator regedit. "/c". Typing "runas /?" from the command prompt gets you all the options. There are many switches that can enhance the behaviour of RUNAS. "\"DummyTitle\"".exe prompts for the password. It's a feature. RUNAS doesn't work when used from a Windows service.EXE". /SaveCred option allows you to save a password for that account and then reuse it later.getRuntime().exec(commands). } } To load a worksheet import java. Runtime. This can be a huge security risk so be careful using it! RUNAS capability can be disabled by editing the Registry or by disabling the RUNAS or Secondary Logon Services. String commands [] = new String [] { "CMD. "/C". "RUNAS /profile /savecred /user:" + "administrator" + " " + "regedit. For example. One potential problem is that when /SaveCred saves the credentials it saves it for whenever RUNAS invokes that user account.io.fileName}.exec(commands).getRuntime(). Next time you use the same command. "start". class StartExcel { public static void main(String args[]) throws IOException { String fileName = "c:\\temp\\xls\\test2. } } It's important to pass a dummy title to the Windows start command where there is a possibility that the filename contains a space.IOException. and then Regedit runs. The appropriate registry key is HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explorer. Runtime.getRuntime().exe"). there is no password prompt. 6. 6.{ Runtime.exe" }.27 Start a Windows application under another account You use the RUNAS command from the command line to start an application under another account (not available with XP Home edition).xls".exec("cmd /c start excel. String[] commands = {"cmd".

isDesktopSupported()) { Desktop desktop = Desktop.awt.. Runtime.*.getenv("programfiles").Action action : Desktop.println("action " + action + " supported? " + desktop. static String FILE_SEPARATOR = System.values()) { System.getProperty("file. the localized name is shown. First it's a good idea to check if the Desktop operations are supported on the running plateform. if (Desktop.exe"}.awt. .rgagnon.6. public static void main(String[] args) throws Exception { String[] commands = {"cmd.Action. for (Desktop.getDesktop(). We simply extract to environnment variable called %programfiles% and build the complete path from there.separator"). } } 6.out.28 Windows : execute something in Program Files We want to execute the textpad editor located in C:\Program Files\TextPad 4 but without hard coding the path since it can be different for a localized version of Windows.exec(commands).getRuntime().28 Windows : execute something in Program Files .5] public class Exec { static String WIN_PROGRAMFILES = System./javadetails/java−0579.29 Launch the application associated with a file extension Current version of this HowTo : http://www. System folders were localized on disk like C:\Program Files −> C:\Archivos de programa on the Windows with the Spanish localization. Since Vista.exe". [JDK1.com/blogs/carlosq/archive/2007/02/12/windows−vista−junctions−points−mui−and−localized−f 6. import java. "/c"..6 The java. WIN_PROGRAMFILES + FILE_SEPARATOR + "textpad 4" + FILE_SEPARATOR + "textpad.isSupported(action)). } } NOTE : Prior Vista.Desktop class uses your host operating system's file associations to launch applications associated with specific file types.com/javadetails/.html JDK1. System Folders always exists with the english name BUT when viewed through Explorer. See http://msmvps..

getDesktop(). } // default mail client // use the mailto: protocol as the URI // ex : mailto:elvis@heaven.getDesktop(). launching the user−default browser to show a specified URI • MAIL.html See also this HowTo and this one. } public static void print(File document) throws IOException { Desktop dt = Desktop. dt.println("Hello from Program2").com/javase/6/docs/api/java/awt/Desktop. } } To call the above application from another 6. launching the user−default mail client with an optional mailto URI. • EDIT.The possible actions are • BROWSE.out.sun.. it is more appropriate to instanciate and called the main method of the other application./javadetails/java−0394. 6.com/javadetails/.html While you can exec("java myaotherapp"). take this simple application : public class Program2 { public static void main(String arg[]) { System.30 Launch an application from another application . } See the javadoc at http://java.browse(document). } // default browser public static void browse(URI document) throws IOException { Desktop dt = Desktop.30 Launch an application from another application Current version of this HowTo : http://www.getDesktop().getDesktop(). • PRINT.open(document). launching a registered application to open a specified file.com?SUBJECT=Love me tender&BODY=love me sweet public static void mail(URI document) throws IOException { Desktop dt = Desktop.mail(document). For example. then // application associated to a file extension public static void open(File document) throws IOException { Desktop dt = Desktop. • OPEN. dt. dt.print(document).rgagnon. launching a registered application to print a specified file. dt. launching a registered application to edit a specified file.

out.out.println("Hello from Program1a").printStackTrace(). "world" }.start(). new Thread(){ public void run() { Program2.out.println("Hello from Program1a"). t1.} } } Launch many programs using Thread and use join() to wait for the completion. // Class params[] = new Class[] { args.join().out.println("Hello from Program2"). params). The dynamic version is little more tricky.println("Hello from Program2").} }. Thread t1 = new Thread(){ public void run() { Program2. System.out.start().30 Launch an application from another application . } } [Program1a.public class Program1a { public static void main(String arg[]) { System.getClass() }).out.main(new String[]{}). t1.println("Hello from Program1b"). invoke(null.out. new Program1b(). [Program2. System. } } The above example is used when the class is hard−coded.} }.execute("Program2"). try { Class. System. getDeclaredMethod("main".java] public class Program2 { public static void main(String arg[]) { System.java] public class Program1a { public static void main(String arg[]) throws Exception{ System.println("Hello from Program2"). } catch(Exception e){ e.println("Hello from Program2"). } public void execute(String name) { Class params[] = {String[]. System. // if you need parameters // String[] args = new String[] { "Hello". public class Program1b { public static void main(String arg[]) { System.out.class}. } } 6.println("Hello from Program1a"). new Object[] {new String[] {}}).forName(name).main(new String[]{}).

[urlList. we initialize a Listbox from a file containing some URLs.html|JAVA http://www.awt.400). java.com/javadetails/java−0002. java.rgagnon.The output : C:\>java Program1a Hello from Program1a Hello from Program2 Hello from Program2 Hello from Program2 Hello from Program2 Hello from Program1a 6. initLbx(). the default browser is started with the selected HTML page as parameter.com/javadetails/java−0005.*. This example is Windows oriented since I have used the start command which supports the file association.java] import import import import import java.com/javadetails/java−0001. } } class AFrame extends Frame implements ActionListener { List lbx. When we double click an item.event.rgagnon.31 Start the default browser from an application . setSize(400. lbx = new List().rgagnon.htmL|JAVA How−to How−to How−to How−to How−to 1 2 3 4 5 [StartBrowser.com/javadetails/java−0003. String url[] = new String[50].txt] http://www.rgagnon.com/javadetails/java−0004. java.html|JAVA http://www.31 Start the default browser from an application Current version of this HowTo : http://www.io. // action on listbox double click lbx.*.addActionListener(this). add(lbx).rgagnon. java. // to close the Frame addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { 6.net../javadetails/java−0071.html|JAVA http://www.*.rgagnon. public AFrame() { // dispaly setup setTitle("URL selection"). public class StartBrowser { public static void main(String s[]) { AFrame f = new AFrame().applet.com/javadetails/.*.*.awt.html In this snippet.html|JAVA http://www.

printStackTrace().getRuntime().getRuntime(). try { String aLine = "". } } } Another way on Windows platform to start the default browser is . } catch (Exception e) { e. } } ).awt.nextToken()). while(null != (aLine = in. "|").com/howto.exe /c " + cmdLine.util. you need to start the // command interpreter // String cmdLine = "cmd.util. try { Process p = Runtime.ht%6D JDK1. // on NT. lbx. in JDK1. You may have difficulty to open a URL ending with .dll.rgagnon.exec ("rundll32 url.dll.StringTokenizer st = new java.2 } } catch(Exception e) { e.htm.readLine())) { java. // start the default browser (Win95 platform) // on listbox double click String cmdLine = "start " + theUrl.exit(0).exe because start is not // an external command but internal. like rundll32 url.6 has java.open(File) 6. url[i++] = st.FileProtocolHandler " + theUrl).getSelectedIndex()].Desktop.nextToken().StringTokenizer(aLine.exec(cmdLine).txt")).dll. } public void actionPerformed (ActionEvent ae) { String theUrl = url[lbx.System. All you need is to replace the last m with %6D.printStackTrace().htm for rundll32 url. BufferedReader in = new BufferedReader(new FileReader("urlList.add(st.FileProtocolHandler http://www.31 Start the default browser from an application . setVisible(true).FileProtocolHandler http://www.rgagnon. // lbx. Runtime.com/howto. } } public void initLbx() { int i = 0.nextToken()). you need to start cmd.addItem(st.

com/javase/6/docs/api/java/awt/Desktop.printStackTrace().html JDIC provides the equivalent API for 1. // we assume that the .getCanonicalPath(). } See also this HowTo. e.dev.").html A Shortcut is stored in a file with the extension lnk. public static void main(String args[]) throws Exception{ 6.getMessage().printStackTrace().html In this example. } 6.4 and later.xox file type.ERROR_MESSAGE).lnk").com/javadetails/.32 Execute a Windows Shortcut (. } catch (MalformedURLException e1) { e1. See https://jdic.rgagnon.showMessageDialog (null. public class Head { static final int MAX_LINES = 10.lnk is in the current directory String currentDir = new File(".sun. import java. try { Runtime.lnk) ."Oups".xox will be defined and associated with a java program (display the first 10 lines of selected .com").exec ("cmd /c start " + currentDir + "/viewLog./javadetails/java−0571. } catch (DesktopException e2) { e2.33 Create a file association with a Java program Current version of this HowTo : http://www. a file with the extension .rgagnon. } catch (Exception e){ JOptionPane.browse(new URL("http://www.*. First the java program to be associated with the ./javadetails/java−0592.See http://java.io.32 Execute a Windows Shortcut (.lnk) Current version of this HowTo : http://www.. 6.net try { Desktop. JOptionPane.java.com/javadetails/.rgagnon.xox file).getRuntime()..

>set pathext=.String line = null..0\bin\java −cp c:\dev\work Head %1 Now.JS. two commands are used to define a file association.WSF. you define the environment variable PATHEXT to include the .BAT.. int i = 0 . FileInputStream fin = new FileInputStream(args[0]). >ftype Xoxfile=C:\Program Files\Java\jre1.out.xox file type. and a string to be used to execute it.5. The ftype command sets up an association between a file type name.XOX. to type only the name of . a Dos shell is opened.out.0\bin\java −cp c:\dev\work Head %1 Xoxfile=C:\Program Files\Java\jre1..print("*** Press any key.class plus the parameter (the selected . } BufferedReader input = new BufferedReader(new InputStreamReader(System..readLine()) != null) { System. while ( (line = myInput. In this example.EXE..5.xox=Xoxfile .xox extension. To make the file association works from a command line. if you double−click on a file with . i++..... we specify the Java JVM to be used. 6. input.xox file). the Head class is launched with the clicked filename as a parameter and the first 10 line are displayed.xox extension.. BufferedReader myInput = new BufferedReader (new InputStreamReader(fin)).VBS. if (i == MAX_LINES) break.VBE.%pathext% PATHEXT=.xox=Xoxfile Then we specify which program is used to handle the Xoxfile type of file. assoc and ftype. See also this HowTo.CMD. You need to execute these commands from an account with Administrator privilege. The assoc command sets up an association between a file name extension and a file type. from a Dos shell. First we define the ..COM.println(line).")..xox. >assoc .in)). the classpath to load the Head. To know more about these commands.32 Execute a Windows Shortcut (. System.JSE. type assoc /? or ftype /? .lnk) .xox file and the associated program will be launched with that file as a parameter. } } With Windows.WSH then you will be able.readLine().

java.getInputStream())).printStackTrace().io.createTempFile("realhowto".exec("cscript //NoLogo " + file. String line.BufferedReader. Since we need the output. java. msgBox("Get the path of Acrobat reader from the registry"). BufferedReader input = new BufferedReader (new InputStreamReader(p. 6.rgagnon.".io. } public static void main(String[] args){ // // DEMO // String result = "".readLine()) != null) { result += line.InputStreamReader.6. fw.io. while ((line = input.exe\\")./javadetails/java−0576.io. public class VBSUtils { private VBSUtils() { } public static String readWindowRegistry(String key) { String result = "".Echo _ \n" + "WSHShell.34 Capture the output from a VBS Current version of this HowTo : http://www.trim().RegRead(\"" + key + "\") \n" + "Set WSHShell = Nothing \n". java. we capture this output.close(). try { File file = File. result = readWindowRegistry ("HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\AcroRd32. The VBS prints the result and from Java.FileWriter(file).io.vbs"). we must use the VBS interpreter for the console mode (CSCRIPT. String vbs = "Dim WSHShell \n" + "Set WSHShell = WScript. } return result. file. FileWriter fw = new java.close(). } input.getPath()).CreateObject(\"WScript. } catch(Exception e){ e. fw.write(vbs).html This HowTo query the Windows Registry for a specific key.Shell\") \n" + "WScript.getRuntime().FileWriter. import import import import java..EXE).deleteOnExit(). Process p = Runtime.com/javadetails/.File.34 Capture the output from a VBS .

file. } public static void main(String[] args){ // // DEMO // String result = "".getPath()). import java. public class VBSUtils { private VBSUtils() { } public static boolean isServiceRunning(String serviceName) { try { File file = File.Application\") \n" + "If sh.close().File.msgBox("Acrobat Reader is located in " + result). You execute the script from Java.JOptionPane. p.io.io. "VBSUtils".io.".com/javadetails/.FileWriter(file).FileWriter.exitValue() == 1).getRuntime(). this is useful only on the Windows plateform.awt. } } 6.createTempFile("realhowto". } return false.showConfirmDialog((java.35 Get a return code from a VBS . msgBox("service 'Themes' is " + result + " running ").write(vbs).JOptionPane. 6.swing.swing.Quit(0) \n".Component) null. fw. it's easy to do from a VBS./javadetails/java−0575. FileWriter fw = new java.html You can't detect directly if Windows service is running or not in Java.35 Get a return code from a VBS Current version of this HowTo : http://www. wait for its completion and capture the return code.rgagnon. fw. Obviously. Process p = Runtime. } catch(Exception e){ e.IsServiceRunning(\""+ serviceName +"\") Then \n" + " wscript.Quit(1) \n" + "End If \n" + "wscript.DEFAULT_OPTION).printStackTrace().vbs"). However.waitFor(). String vbs = "Set sh = CreateObject(\"Shell. result = isServiceRunning("Themes") ? "" : " NOT ". msgBox("Check if service 'Themes' is running (should be yes)").deleteOnExit(). javax. } public static void msgBox(String msg) { javax. msg. import java.exec("wscript " + file.. return (p.

flush().cmd").Component) null.swing.getErrorStream (). // clean up if any output in stdout 6.awt.io. msg. InputStream stdout = null. javax.36 Execute a CMD file stored in a JAR . stdin = process. msgBox("service 'foo' is " + result + " running "). a CMD file is stored a JAR file.doit().DEFAULT_OPTION). In this How−to. try { // that our CMD file in our JAR InputStream is = getClass(). launch a Windows CMD Shell and write the content to the stdin without any temporary file. scrnsave.showConfirmDialog((java. The Java code extracts the file as a ressource. the CMD included is used to trigger the default Windows screen saver. OutputStream stdin = null.scr /s import java./javadetails/java−0600. public class StartScreenSaver { public static void main(String args[]) throws IOException { new StartScreenSaver()..JOptionPane.openStream().swing.readLine()) != null) { line += "\n".getBytes() ). InputStream stderr = null.close().getOutputStream (). // launch CMD and grab stdin/stdout and stderr Process process = Runtime.write(line. stdin. BufferedReader brCmdLine = new BufferedReader(new InputStreamReader(is)). } public static void msgBox(String msg) { javax.JOptionPane. "VBSUtils".36 Execute a CMD file stored in a JAR Current version of this HowTo : http://www.html In this example. stdin.*. } stdin.exec ("cmd").getResource("/screensaver. } } 6.getInputStream (). stderr = process. // "write" the CMD file into stdin while ((line = brCmdLine.com/javadetails/.msgBox("Check if service 'foo' is running (should be no)"). } public void doit() throws IOException{ String line.rgagnon.getRuntime (). stdout = process. result = isServiceRunning("foo") ? "" : " NOT ".

} brCleanUp.length.. while ((line = brCleanUp.out.BufferedReader brCleanUp = new BufferedReader (new InputStreamReader (stdout)).printStackTrace().readLine ()) != null) { //System.println ("[Stdout] " + line).readLine()) != null) { System. 6. i < args. while ((line = brCleanUp.close(). while ((thisLine = myInput. give the filename to be displayed.close(). i++) { try { FileInputStream fin = new FileInputStream(args[i]). } } } Get the JAR here.println(thisLine). } } catch (Exception e) { e.printStackTrace(). } } } } 6. for (int i=0.readLine ()) != null) { //System.1+ BufferedReader myInput = new BufferedReader (new InputStreamReader(fin)).io.37 Read the content of a file Current version of this HowTo : http://www.out.out. import java.close(). } catch (IOException e) { e. On the command line. } finally { stdout. // JDK1.*.close(). public class Cat { public static void main (String args[]) { String thisLine. // clean up if any output in stderr brCleanUp = new BufferedReader (new InputStreamReader (stderr)). stderr.html This following example is for an application.com/javadetails/.println ("[Stderr] " + line).37 Read the content of a file .rgagnon. } brCleanUp./javadetails/java−0052.

applet.io. import java.37 Read the content of a file .*.printStackTrace().*.*. public void init() { myChoice = new java. } br.*. while(null != (anItem = in.readLine())) { myChoice. add(myChoice).awt. java.txt"). public class MyApplet extends Applet { public void init() { readFile("mydatafile. java.out. public class ReadDataInChoice extends Applet { Choice myChoice.awt.openStream())).readLine())) { System. } catch(Exception e) { e. BufferedReader in = new BufferedReader(new InputStreamReader(source. } catch(Exception e) { e.With an Applet. } public void readFile(String f) { try { String anItem = "". } } } The next Applet reads a data file and inserts the data in a Choice component.*.close(). BufferedReader br = new BufferedReader (new InputStreamReader(source. java.*. } public void readFile(String f) { try { String aLine = "". URL source = new URL(getCodeBase(). readFile("dataforchoice.add(anItem). we can only open file on the same server that the Applet is coming from.Choice().printStackTrace(). import java.net.println(aLine). import java. while(null != (aLine = br. URL source = new URL(getCodeBase(). } } } 6.*.io. f).openStream())).txt").close().net. } in.applet. import import import import java. f).

6.txt] item item item item item ITEM 1 2 3 4 5 6 Try it here. The following method read a data file and return the content as a String.. try { is = FileUtils.html import java. String line.append(lineSep). BufferedReader br = new BufferedReader(new FileReader(filename)).separator").add(line). private static String readFile(String filename) throws IOException { String lineSep = System. while ((nextLine = br.rgagnon.*. StringBuffer sb = new StringBuffer(). } return sb.[dataforchoice. public class FileUtils{ public static List<String> readTextFromJar(String s) { InputStream is = null. 6.class.com/javadetails/.printStackTrace(). import java.readLine()) != null) { sb.toString().38 Read a text file from a jar . We use a StringBuffer to optimize string concatenation operations. // // note: // BufferedReader strips the EOL character // so we add a new one! // sb.getResourceAsStream(s). String nextLine = "". BufferedReader br = null./javadetails/java−0077. br = new BufferedReader(new InputStreamReader(is)).io.getProperty("line. } See this HowTo to read a File which is inside a JAR.38 Read a text file from a jar Current version of this HowTo : http://www.*.append(nextLine).util.readLine())) { list. } } catch (Exception e) { e. while (null != (line = br. ArrayList<String> list = new ArrayList<String>().

while(it. datafile1. } catch (IOException e) { e.txt] datafile2 datafile2 datafile2 datafile2 datafile2 line line line line line 1 2 3 4 5 Create the jar with >"C:\Program Files\Java\jdk1.hasNext()) { System.class datafile.txt").readTextFromJar("/test/datafile2.txt test/datafile. } public static void main(String args[]) throws IOException{ List<String> list = FileUtils.next()).txt").println(it.txt in the same directory as FileUtils.38 Read a text file from a jar .jar FileUtils. it = list. } list = FileUtils.readTextFromJar("/datafile1. } } return list.jar FileUtils The output should be like : 6.next()).close().out.5. Iterator<String> it = list.} finally { try { if (br != null) br.hasNext()) { System.iterator().println(it.txt in a subdirectory called test [datafile1.0\bin\jar" −cf MyJar.class (in the root) and datafile2. } } } Create 2 datafiles.out.txt] datafile1 datafile1 datafile1 datafile1 datafile1 line line line line line 1 2 3 4 5 [/test/datafile2. while(it.printStackTrace().close().iterator(). if (is != null) is.txt Try it : C> java −cp MyJar.

txt The html <HTML><HEAD></HEAD><BODY> <APPLET CODE=ReadFromJar. BufferedReader br = new BufferedReader (new InputStreamReader(is)).txt test/datafile2.readLine()) != null) { System. } } } Create the JAR >"C:\Program Files\Java\jdk1.class datafile1.applet. try { InputStream is = getClass(). readTextFromJar("test/datafile2.getResourceAsStream(s).txt").txt"). it's the same technique import java.*. } } catch (Exception e) { e.class width=1 height=1 archive=MyJarApplet.5.printStackTrace().io. while ((thisLine = br.out. public class ReadFromJar extends Applet{ public void init(){ readTextFromJar("datafile1.38 Read a text file from a jar . } public void readTextFromJar(String s) { String thisLine.0\bin\jar" −cf MyJarApplet.println(thisLine).datafile1 datafile1 datafile1 datafile1 datafile1 datafile2 datafile2 datafile2 datafile2 datafile2 line line line line line line line line line line 1 2 3 4 5 1 2 3 4 5 Get the JAR here With an Applet.*.jar ReadFromJar.jar> </APPLET> See java console for output</BODY></HTML> Try it here 6. import java.

substring(6).util..zip. import java.flush(). getCodeSource().getInputStream(entry)). byte[] buffer = new byte[2048].jar Main−Class: ExtractFromJAR Create the JAR C:\jdk141\bin\jar cvfm mydb.) { int nBytes = in.mdb").mdb 6. File efile = new File(dest. } } public static void main(String args []){ new ExtractFromJAR().*.39 Extract a file from a Jar Current version of this HowTo : http://www.").read(buffer).jar manifest.getProtectionDomain(). nBytes).util.0 Classpath: .mft ExtractFromJAR.*.close().mdb) from a jar. public class ExtractFromJAR { public void extractMyMDBromJAR(String dest){ try { String home = getClass().39 Extract a file from a Jar .html The following snippet extract a file (mydb. } catch (Exception e) { e. import java.*. import java.close(). 0.io. ZipEntry entry = jar.jar.rgagnon.getEntry("mydb. JarFile jar = new JarFile(home).getName()). if (nBytes <= 0) break..write(buffer. entry. in. InputStream in = new BufferedInputStream(jar. out.class mydb.toString(). out. To create an auto−run JAR.6. } out./javadetails/java−0429.getLocation(). } } Grab this auto−run Jar if you want to try it. for (.extractMyMDBFromJAR(".com/javadetails/. first create a manifest.\mydb.mft Manifest−Version: 1. OutputStream out = new BufferedOutputStream(new FileOutputStream(efile)).printStackTrace().

getPath().Run it .40 Read a data file with floats Current version of this HowTo : http://www. and the mydb.StringTokenizer st = new java.rgagnon.nextToken()).FileNotFoundException. String delimiter) throws Exception { java.html [ReadingFloat.BufferedInputStream(in). I got a problem when the jar file was located in C:\Program Files\xyz due to the embedded space. consider making a small donation to show your support for this Web site and its content.toString(). java −jar mydb.io.util. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 6.io.java] public class ReadingFloat { public static float[] readFile(String file.util. If you find this article useful. So I modified the code to String home = getClass().BufferedInputStream s = new java.URL(url).40 Read a data file with floats .replaceAll("%20".substring(6).mdb file should appear in the current directory.hasMoreElements()) values[j++] = Float..io. java.BufferedReader myInput = new java.floatValue().net.NumberFormatException { String thisLine. String delimiter) throws Exception { return(readValues(new java.io. } public static float[] readValues(java.getProtectionDomain() . java. int j = 0.getLocation().IOException. return(readValues(addr.URL addr = new java. delimiter). java.StringTokenizer(thisLine. while(st. delimiter)). 6. delimiter)).InputStream in.valueOf(st.InputStreamReader(s)). getCodeSource().lang.readLine()) != null) { // scan it line by line java. java.io.getCodeSource(). } public static float[] readURL(String url.getLocation() ..getProtectionDomain().FileInputStream(file). " ").net.io. while ((thisLine = myInput. float[] values = new float[10].io.BufferedReader (new java./javadetails/java−0078.jar (A tip from Fred Hommersom) Your code reads: String home = getClass().io.com/javadetails/..io.openStream(). String delimiter) throws java.

41 Write to the end of a file .2] import java.3 2.6.2. public class appendtext { public static void main(String args[]){ try { PrintStream out = new PrintStream(new AppendFileStream("myfile")). out.6 2.6 1.print("A new line of text"). i++ ) { System.dat] 1.dat] 1.2345 2.1.length.3.html [JDK1.78 2. for(int i = 0./javadetails/java−0054. "..2.78.").0.3 1.out. } System.} return(values).*. } } catch (Exception e) { e.println(e. } catch(Exception e) { System.dat". } } } 6.com/javadetails/.printStackTrace().1.dat". i++ ) { System.3.toString()). out.2 2.78 1.out.2. i lt. } } } [floatwithdelimitercolon.2345 [floatwithdelimiterspace.2345 2. " ").41 Write to the end of a file Current version of this HowTo : http://www.out.demo().2.close().println(results[i]).println().2.2 1.length.1. } public void demo() { try { // we assume 10 floats (max)to be read float results [] = readFile("floatwithdelimitercolon. results.6. for(int i = 0.rgagnon.out.println(results[i]).2345 6. } public static void main(String arg[]) { new ReadingFloat().1. results = readFile("floatwithdelimiterspace. i < results.io.78.2.

} public void close() throws IOException { fd.int len) throws IOException { fd.off.dat"). } public void write(byte[] b) throws IOException { fd. This done via the InputStreamReader class for input and OutputStreamWriter for output. } public void write(byte[] b. To pass information to outside world.len). } public void write(int b) throws IOException { fd.write(b. } } [JDK1.*./javadetails/java−0058.write(JavaString).awt. // Unicode for "é" try { // output : Unicode to Cp850 (MS−DOS Latin−1) FileOutputStream fos = new FileOutputStream("out.write(b). Writer w = new BufferedWriter(new OutputStreamWriter(fos.42 Write "real" ascii file .write(b).42 Write "real" ascii file Current version of this HowTo : http://www. fd.com/javadetails/. For example. it may be necessary to use different encoding.length()).io.*. 6.class AppendFileStream extends OutputStream { RandomAccessFile fd..seek(fd.1] FileOutputStream fos = new FileOutputStream("myfile". public class DosString { public static void main(String args[]){ String javaString = "é \u00e9". public AppendFileStream(String file) throws IOException { fd = new RandomAccessFile(file.rgagnon.html Java uses Unicode character encoding internally. "Cp850")). w. DOS application may use MS ISO−Latin 1(or Codepage 850) to represent french characters like é or à.close(). import java. Before writting to a file or in a database record it is necessary to change the default String encoding. InputStreamReader converts from the specified input encoding to Unicode while the OutputStreamWriter converts from Unicode to the specified output encoding. true). to open in Append mode 6. import java."rw").int off.

} } public static void main(String args[]) throws Exception{ FileUtils.setSize(100.close().com/javadetails/. f. the default encoding is used. FileOutputStream fos = new FileOutputStream(out).printStackTrace(). } } [JDK1.43 Copy a file Current version of this HowTo : http://www.43 Copy a file . int i = 0. if (fos != null) fos.io.4 using the java. } } catch (Exception e) { throw e.close(). // input`: Cp850 to Unicode FileInputStream fis = new FileInputStream("out. w. try { byte[] buf = new byte[1024].write(buf.read(buf)) != −1) { fos. 6. File out) throws Exception { FileInputStream fis = new FileInputStream(in). i). } } } NOTE: When the character encoding is not specified.w. Frame f = new Frame().4)] import java. "Cp850"))../javadetails/java−0064.copyFile(new File(args[0]).*. r. String dosString = r.100).encoding").nio package (faster)] 6. You can find out the current default encoding by looking at file.getProperty("file.readLine(). public class FileUtils{ public static void copyFile(File in.new File(args[1])).html [Old technique (pre JDK1. f. BufferedReader r = new BufferedReader(new InputStreamReader(fis. 0.setVisible(true).encoding property with System.close(). .flush().rgagnon.dat"). while ((i = fis. } catch (Exception e) { e.close().add(new Label(dosString)). } finally { if (fis != null) fis. f.

if (outChannel != null) outChannel.io.nio.transferTo(0. } .IOException: Insufficient system resources exist to complete the requested service is thrown. an Exception in thread "main" java.IOException: Input/output error ref : http://bugs. } } NOTE: In win2000 . try { inChannel.jspa?threadID=4396950 The workaround is to copy in a loop 64Mb each time until there is no more data.copyFile(new File(args[0]). outChannel).io. For a discussion about this see : http://forum. outChannel).do?bug_id=4643189 On the Windows plateform. long size = inChannel.size(). 6.*.getChannel().43 Copy a file .size()..1 .com/thread. } } public static void main(String args[]) throws IOException{ FileUtils.IOException: The parameter is incorrect" In solaris8 . Replace . Bytes transfered to Target channel are 2^31−1 even if the source channel file is greater than 2^31−1 In LinuxRH7.*.io. long position = 0. FileChannel outChannel = new FileOutputStream(out). try { inChannel. 64Mb − 32Kb) int maxCount = (64 * 1024 * 1024) − (32 * 1024).. try { // magic number for Windows.import java.size(). by .io.sun. File out) throws IOException { FileChannel inChannel = new FileInputStream(in). public class FileUtils{ public static void copyFile(File in. import java.close().java.close(). you can't copy a file bigger than 64Mb..sun. } finally { if (inChannel != null) inChannel. inChannel. the transferTo() does not transfer files > than 2^31−1 bytes. } catch (IOException e) { throw e..com/bugdatabase/view_bug.getChannel()..transferTo(0.new File(args[1])). inChannel..channels. it gives an error of java. it throws an exception of "java.

txt". true).println(currentTime + " " + msg).out. aWriter. try { write("LOG file : " + filename). stack2string(e)).separator")). } public static void write(String file.getProperty("line.println(stack2string(e)).mm.println(stack2string(e)).44 Use a "log file" Current version of this HowTo : http://www.df.*. } .format(now).. aWriter.text.html /** * Utilities log */ import java. new File(filename). 6. maxCount.delete(). String msg) { try { Date now = new Date(). import java.dd private SimpleLog() { } public static void setLogFilename(String filename) { logFile = filename. 6.*.util../javadetails/java−0063.com/javadetails/. private final static DateFormat df = new SimpleDateFormat ("yyyy. outChannel).transferTo(position. aWriter.rgagnon.while (position < size) { position += inChannel. String currentTime = SimpleLog. msg). System. import java. } } public static void write(String msg) { write(logFile..out.close().out.44 Use a "log file" . } public static void write(Exception e) { write(logFile. public class SimpleLog { private static String logFile = "/msglog. } catch (Exception e) { System. } hh:mm:ss ").write(currentTime + " " + msg + System.io. } catch (Exception e) { System.*. FileWriter aWriter = new FileWriter(file.flush().

String extension ) { ExtensionFilter filter = new ExtensionFilter(extension).} private static String stack2string(Exception e) { try { StringWriter sw = new StringWriter(). } public boolean accept(File dir.extension = extension. public class FileUtils{ public static void main(String args[]) throws Exception { FileUtils. File dir = new File(directory). 6. } } and then import java.printStackTrace(pw).*. ".write("i am here").io. } public static void deleteFiles( String directory. } catch(Exception e2) { return "bad stack2string".deleteFiles("c:/test/". PrintWriter pw = new PrintWriter(sw). public ExtensionFilter( String extension ) { this. String name) { return (name. e.com/javadetails/. String[] list = dir. return "−−−−−−\r\n" + sw.45 Delete files with a certain extension . See also this HowTo and this one 6. } } } and then to use it SimpleLog.toString() + "−−−−−−\r\n"./javadetails/java−0072.45 Delete files with a certain extension Current version of this HowTo : http://www.*.endsWith(extension)).list(filter). public class ExtensionFilter implements FilenameFilter { private String extension..io.gif").html Define a special FilenameFilter : import java.rgagnon. File file.

print(file + " deleted : " + file. // input FileInputStream fis = new FileInputStream(inFile). public class JInsert { public static void main(String args[]){ try { JInsert j = new JInsert().tmp").parseInt(args[1]).length == 0) return.delete()). you need to supply 3 arguments : the filename.length.46 Insert a line in a file .insertStringInFile (new File(args[0]). of course you need more error checking. // output FileOutputStream fos = new FileOutputStream(outFile). i < list. } catch (Exception e) { e. 6. In this example. for (int i = 0.*. BufferedReader in = new BufferedReader (new InputStreamReader(fis)).out. Then we erase the original file and rename the temporary file to the original name. a line number and the string to be inserted at the line number specified.rgagnon. } } } } 6. System. j. list[i]).out". i++) { //file = new File(directory + list[i]). } } public void insertStringInFile (File inFile.46 Insert a line in a file Current version of this HowTo : http://www.1] import java.com/javadetails/..io.printStackTrace().if (list.out 9 "HELLO WORLD" will insert the string "HELLO WORLD" at line number 9 in the file "test./javadetails/java−0073. String lineToBeInserted) throws Exception { // temp file File outFile = new File("$$$$$$$$.Integer. [JDK1. file = new File(directory.. args[2]). int lineno. java JInsert test..html The only way to insert a line in a text file is to read the original file and write the content in a temporary file with the new line inserted.

} out.io.rgagnon. byte[] b = new byte[in. } } 6. All we need is an input or output stream. 6. the methods needed to serialize the object are already done.com/javadetails/.Vector.length.rgagnon.47 Read a file into a variable in one shot . String result = new String (b.out. String thisLine = ""./javadetails/java−0074.println(result). public class ReadFullyIntoVar { public static void main(String argv[]){ try { FileInputStream file = new FileInputStream (argv[0]).PrintWriter out = new PrintWriter(fos). We want to save the state of the Queue in a file./javadetails/java−0075.flush(). import java. while ((thisLine = in.close().available ()].html import java.close()..com/javadetails/.. in.util.readFully (b). inFile.printStackTrace().readLine()) != null) { if(i == lineno) out. out.renameTo(inFile). } } } 6. 0. i++. int i =1. b. in.*.class.html Suppose we have a class called Queue. First the Queue class import java.println(thisLine). out. outFile. } catch (Exception e) { e.close (). Since our Queue extends the Vector class.48 Serialize an object to a file Current version of this HowTo : http://www.*. DataInputStream in = new DataInputStream (file).delete(). /* */ System. "Cp850").47 Read a file into a variable in one shot Current version of this HowTo : http://www. in.println(lineToBeInserted).io.

out.put("element 3"). theQueue = new Queue(). oos. theQueue. theQueue = (Queue) ois. return firstElement(). } } To serialize (save the Queue state to a file) : public static void main(String args[]) { Queue theQueue.dat").put("element 2"). theQueue.out. first in first out */ Queue() { super(). ObjectOutputStream oos = new ObjectOutputStream(fout).writeObject(theQueue).dat").close(). return o.public class Queue extends Vector { /* ** FIFO. // unserialize the Queue System. } Object get() { if (isEmpty()) return null. System. } catch (Exception e) { e.println("serializing theQueue"). theQueue. theQueue = new Queue(). try { FileOutputStream fout = new FileOutputStream("thequeue.toString()). try { FileInputStream fin = new FileInputStream("thequeue.println(theQueue. // serialize the Queue System.put("element 4"). } void put(Object o) { addElement(o).printStackTrace(). } } To unserialize (to load a previously saved Queue) : public static void main(String args[]) { Queue theQueue. theQueue.readObject().47 Read a file into a variable in one shot .println("unserializing theQueue"). } Object peek() { if (isEmpty()) return null.out. removeElement(o).put("element 1"). oos. ObjectInputStream ois = new ObjectInputStream(fin). 6. Object o = firstElement().

but the return value is system dependent and should only be used to compare with other values returned by last modified..rgagnon.out.println(theQueue.io.rgagnon.ois. String s2 = "file2.close().dat".html import java..1] application only System.html [JDK1. 6. } System. String s1 = "file1.com/javadetails/. File f2 = new File(s2). } 6./javadetails/java−0068.lastModified()) System.out. } catch (Exception e) { e.50 Get the "last modified" date from a file Current version of this HowTo : http://www.*..49 Redirect stdout to a file . It should not be interpreted as an absolute time.49 Redirect stdout to a file Current version of this HowTo : http://www.exists()? " is found " : " is missing ")). You may want to look at this How−to to redirect exception output to a Frame.toString()).out.DAT")))).com/javadetails/. 6./javadetails/java−0061.lastModified() < f2.setOut( new PrintStream( new BufferedOutputStream( new FileOutputStream("OUTPUT. System.println((s1 + " IS OLDER THAN " + S2).51 Check if a file exists Current version of this HowTo : http://www./javadetails/java−0070.rgagnon.println (f + (f.com/javadetails/. } } 6.dat". File f1 = new File(s1).printStackTrace(). if (f1. public class FileTest { public static void main(String args[]) { File f = new File(args[0]).html Simply use the lastModified() method from a file object.

getName() +" have change !" ).out.timeStamp = timeStamp. import java.util. this. } import java./javadetails/java−0490.timeStamp = file.com/javadetails/.rgagnon. import java.println( "File "+ file.txt") ) { protected void onChange( File file ) { // here we code the action on a change System.*. we check the current lastModifed value of a given file and compare it with the value stored in the Map.io.timeStamp != timeStamp ) { this.. // repeat the check every second timer. } } protected abstract void onChange( File file ).*. a thread is launched where we keep the Files in a Map.*. if( this. 1000 ).lastModified().io.util.*.lastModified(). } public final void run() { long timeStamp = file. public abstract class FileWatcher extends TimerTask { private long timeStamp. public FileWatcher( File file ) { this. a thread is launched to check the lastModified value and compare it with the previous value.52 Detect file modification Current version of this HowTo : http://www.52 Detect file modification .schedule( task . onChange(file). } } For a directory. Timer timer = new Timer(). 6. } }. private File file. import java.6.file = file. Also a special check is made to detect if a File is deleted. new Date().html For a single file. class FileWatcherTest { public static void main(String args[]) { // monitor a single file TimerTask task = new FileWatcher( new File("c:/temp/text.

i < filesArray. private DirFilterWatcher dfw. } } protected abstract void onChange( File file.length.lastModified())). "modify"). dir. new Long(filesArray[i].util.listFiles(dfw).lastModified()){ // modified file dir.longValue() != filesArray[i]. public abstract class DirWatcher extends TimerTask { private String path. public DirWatcher(String path) { this(path.next(). filesArray = new File(path).io.hasNext()) { File deletedFile = (File)it.listFiles(dfw). "delete"). i++) { Long current = (Long)dir.put(filesArray[i].lastModified())). // scan the files and check for modification/addition for(int i = 0. "").clone()). } } public final void run() { HashSet checkedFiles = new HashSet().remove(deletedFile). ref. new Long(filesArray[i].removeAll((Set)checkedFiles).52 Detect file modification .*.add(filesArray[i]). onChange(filesArray[i]. dfw = new DirFilterWatcher(filter).put(filesArray[i]. } public DirWatcher(String path. filesArray = new File(path). Iterator it = ref. while (it. onChange(deletedFile. } } // now check for deleted files Set ref = ((HashMap)dir.get(filesArray[i]). public DirFilterWatcher() { 6. // transfer to the hashmap be used a reference and keep the // lastModfied value for(int i = 0. onChange(filesArray[i]. private HashMap dir = new HashMap(). String filter) { this. private File filesArray [].import java. new Long(filesArray[i].lastModified())). i <filesArray.keySet(). checkedFiles.put(filesArray[i]. if (current == null) { // new file dir. } else if (current.*. i++) { dir. String action ).length. "add").path = path. import java.iterator(). } class DirFilterWatcher implements FileFilter { private String filter.

endsWith(filter)).53 File/directory polling to detect change ./javadetails/java−0617.html 6. new Date(). like JBoss' JMX console.io. String action ) { // here we code the action on a change System. 1000 ). import java. timer. 6.out.getName() +" action: " + action ).rgagnon.equals(filter)) { return true.filter = filter.net/ A general purpose Java component to enable polling on directories and aysnchronously notify client code of incoming files.sourceforge.println ( "File "+ file.sourceforge. } }.*.getName()..53 File/directory polling to detect change Current version of this HowTo : http://www. 6.com/javadetails/. } public boolean accept(File file) { if ("".54 jpoller (directory poller) http://jpoller. } } import java. "txt" ) { protected void onChange( File file.filter = "". It's instrumented via JMX and controllable (also) via a JMX agent. } return (file. } } See also this related howto and this one too.this. class DirWatcherTest { public static void main(String args[]) { TimerTask task = new DirWatcher("c:/temp".schedule( task .net/ 6. Timer timer = new Timer().util.*.55 JNotify http://jnotify. } public DirFilterWatcher(String filter) { this.

html Java 7 is supposed to provides a mechanism to get notificaton on file change without polling (JSR 203).58 Java 7 http://www.com/lejava/articles/more_new_io. try { System.").println ("Parent dir : " + dir2. } catch(Exception e) { 6. 6. One example provides notification of file system changes using the mechanism provided by the OS. the package NativeCall is used to call the Windows API to get notification about modification in given folder.println ("Current dir : " + dir1. JNotify works on both Windows (Windows 2000. FileMonitor.59 The simple (and naive!) approach Detect file modification Using Threads and file lookup at regular interval...JNotify is a java library that allow java application to listen to file system events. File dir2 = new File (". 6. 6.14 and above). 6. Vista) and Linux with INotify support (Kernel 2.out.java Javaworld article about JNA 6.File.").56 Java Native Access (JNA) https://jna.out.html import java.com/javadetails/.rgagnon.java.57 Call native methods in a DLL from Java (NativeCall) http://johannburkard.artima.de/blog/programming/java/Call−native−methods−in−a−DLL−from−Java−without−JNI.dev.net/ The goal of the JNA project is to let you access native code from Java while avoiding C and the Java Native Interface. XP.ht In this blog entry.56 Java Native Access (JNA) . public class CurrentDir { public static void main (String args[]) { File dir1 = new File (".io.getCanonicalPath()).6./javadetails/java−0076.getCanonicalPath()). System.60 Get the current directory Current version of this HowTo : http://www.

URI.io. URISyntaxException{ URL u = getClass(). import import import import import java.com/javadetails/.html First you create a class that implements java.println(f.io. 6.printStackTrace()./javadetails/java−0055.IOException.e.. } public void getRoot() throws IOException. java.com/javadetails/./javadetails/java−0581.FilenameFilter and then code the accept() method. File f = new File(u. java. then call File.61 Get the "root" of an application Current version of this HowTo : http://www.URISyntaxException.62 Get the content of a directory with a Filter Current version of this HowTo : http://www.getRoot(). DummyApp C:\Applications\dev Running from a jar C:\Applications\dev\HowTo>jar cf DummyApp.File.net.getParent()). java.* C:\Applications\dev\HowTo>java −cp DummyApp. public class DummyApp { public static void main(String args[]) throws Exception{ DummyApp s = new DummyApp(). System.rgagnon. we mean the starting directory.jar DummyApp C:\Applications\dev\HowTo See these related HowTo's : 1 2 6.net..net.URL.61 Get the "root" of an application .getLocation().toURI()). s. } } Running from a regular class C:\Applications\dev\HowTo>java −cp .out.getCodeSource().io. The returned array of strings has all the names that passed through the accept()filter.rgagnon.list() with the filter as a parameter.html By root. java. } } } 6.jar DummyApp.getProtectionDomain().

list(nf).util.io.import java. } Filter nf = new Filter (args[0]).FilenameFilter. String[] strs = dir." + extList. i++) { System.asList(extensions). "pdf" }). import import import import import java. } public static void main (String args[]) { if (args. i < strs. while (extList.File. String name) { return name. * // GenericFileFilter xmlandpdf = new GenericFileFilter (new String [] { "xml". java Filter java").io.add(". * String[] strs = dir. * File dir = new File (". java.toLowerCase().err. java.trim()).util." + ext. i < strs.out.toLowerCase(). public GenericFileFilter(String ext) { exts.iterator().FilenameFilter. // current directory File dir = new File (". public class Filter implements FilenameFilter { protected String pattern. /** * <CODE> * GenericFileFilter xml = new GenericFileFilter ("xml"). } public boolean accept (File dir.61 Get the "root" of an application .length != 1) { System.toLowerCase().length.trim()). } 6. } } } ex.Iterator.io. for (int i = 0.hasNext()) { exts.length. Here a version to support multiple filters.TreeSet.list(xml).io.Arrays. java. java. * for (int i = 0.println ("usage: java Filter <pattern list> return. } public GenericFileFilter(String[] extensions) { Iterator<String> extList = Arrays.println (strs[i]).next(). public Filter (String str) { pattern = str."). import java.File.util.endsWith(pattern.").add(".toLowerCase()). i++) { * // strs[i] * } * </CODE> */ public class GenericFileFilter implements FilenameFilter { private TreeSet<String> exts = new TreeSet<String>() .

com/javadetails/.iterator().asList(_result).matches(". import java.html import java.*. import java. return.endsWith(extList.length.*. i++) { System.length < 1) { System.hasNext()) { if (name. _result[].io. String[] strs = dir. } Filter nf = new Filter().FilenameFilter.println ("usage: java Filter <directory> ex. for (int i = 0. while (extList.rgagnon. public class DirUtils { public static List recurseDir(String dir) { String result.exts. name). } } return false. import java.util. return Arrays. java Filter c:\\temp"). String name) { return Pattern.err.(jpg|jpeg|gif|png|bmp)"./javadetails/java−0056.util.remove("").jpg" } public static void main (String args[]) { if (args.63 Get the content of a directory with subdirectories Current version of this HowTo : http://www.io.next())) { return true.regex. import java.list(nf). } public boolean accept(File dir. _result = result. i < strs. } } If multiple extensions are to be checked then a regular expression can be used. // current directory File dir = new File (args[0]). public class Filter implements FilenameFilter { public boolean accept (File dir.File.toLowerCase()..63 Get the content of a directory with subdirectories .split("\\|"). result = recurseInDirFrom(dir).println (strs[i]).*\\.out. String name) { final Iterator<String> extList = exts. } } } 6. } 6.*.io. // if only one extension to check : "\\.

com/javadetails/.println("Usage :"). c:\zip\wolf\ok\kf_box.exe.out. c:\zip\mp3\hh_install.separatorChar + list[i]). c:\zip\Water.println(" java DirUtils c:\temp").c:\zip\mp3\BonkEnc−1. c:\zip\xpAntiSpy. c:\zip\o k\htmldoc−1. c:\zip\ok.c:\zip\Shockwave_Insta ller_Full. c:\zip\AutoIt. String list[].isDirectory()) { list = file. not Applet! File td = new File("NewDirName"). c:\zip\groups2.exe.mkDir(). c:\zip\mp3\TWMP3en coder.exe.exe./javadetails/java−0057.exe.println(DirUtils. c:\zip\mp3. result. c:\zip\RealOneP layerV2GOLD.exe.println("recursive Dirs from " + arg[0]). i++) result = result + "|" + recurseInDirFrom(dirItem + File.zip. c:\zip\cc32d48. i < list.64 Make a directory Current version of this HowTo : http://www. td.exe.rgagnon. c:\zip\ok\CmdHerePowertoySetup. c:\zip\ok\j2sdk−1_4_1_02−windows−i58 6.exe.out.zip. c:\zip\wolf\sp_off lag_levels_1−4_final.zip] */ } } 6.list(). } else { System. for (int i = 0.exe.exe. } /* output: C:\Applications>java DirUtils c:\zip recursive Dir from c:\zip [c:\zip. System. c:\zip\wolf\ok. c:\zip\ok\jsref13.23. c:\zip\winamp50_full.exe..recurseDir(arg[0])). c:\zip\mp3\T PlayerSetup.23−winfree. } public static void main(String arg[]) { if (arg. c:\zip\RESTorefile2514.length.zip. c:\zip\quickmail−2_1. c:\zip\CODE_UPLOAD 148812122001. 6.exe. result = dirItem.out.length > 0) { System.zip.private static String recurseInDirFrom(String dirItem) { File file. } return result. c:\ zip\mass20.EXE. c:\zip\ok\T weakUiPowertoySetup. c:\zi p\mp3\cdex_150b10_enu.exe. System.zip.zip.c:\zip\w olf.exe. file = new File(dirItem).64 Make a directory . c:\zip\httrack−3.txt.zip.out.8.html For application only.0−beta1. c:\zip\mp3\Tunchy1017full. c:\zip\ok\jdk141−hh.exe.exe.zip. if (file.

length.close(). 0.write(buf./javadetails/java−0461..com/javadetails/. } else { files[i].delete() ). fos.html Use the following recursive method.isDirectory()) { deleteDirectory(files[i]).com/javadetails/. i<files.write(buf.66 Delete a non−empty directory Current version of this HowTo : http://www.parseLong(args[0]). class DeleteDir { public static void main(String args[]) { deleteDirectory(new File(args[0])). import java.rgagnon. import java. consider making a small donation to show your support for this Web site and its content.rgagnon.listFiles(). i < m.. for(int i=0.65 Create a fixed−length file Current version of this HowTo : http://www.FileOutputStream.exists() ) { File[] files = path. buf. public class CreateAFile { public static void main(String[] args) throws IOException { byte[] buf = new byte[8192]. } 6.IOException. (int)(n % buf. } } If you find this article useful.dat // import java.65 Create a fixed−length file ./javadetails/java−0483.File.length)). long m = n / buf. FileOutputStream fos = new FileOutputStream(args[1]).io.html // // usage : java CreateAFile 2048 twokbytes. } static public boolean deleteDirectory(File path) { if( path. long n = Long. i++) { if(files[i].delete(). } fos. } } } return( path. for (long i = 0.io.io. 0.6.length. i++) { fos. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 6.length).

consider making a small donation to show your support for this Web site and its content./javadetails/java−0484. The location of the directory used to hold temporary files is defined by the property java. File temp = File.howto").67 Create a temporary file ..deleteOnExit(). To create the new file. If the suffix is too long then it too will be truncated. 6.File.createTempFile("real". On some plateform. the prefix and the suffix may first be adjusted to fit the limitations of the underlying platform. The suffix argument may be null.tmpdir=C:\mydir myClass or .io.io.com/javadetails/.') then the period and the first three characters following it will always be preserved.rgagnon. using the given prefix ("real") and suffix (".io. on Windows.67 Create a temporary file Current version of this HowTo : http://www. temp. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 6.endsWith("/") || tempdir. (Javadoc) The prefix argument must be at least three characters long. The default value can be changed with the command line used to launch the JVM : java −Djava.tmp" will be used.. five or more internally−generated characters. String tempdir = System.separator"). the temporary directory returned by java.getProperty("java.tmpdir"). .} If you find this article useful. Once these adjustments have been made the name of the new file will be generated by concatenating the prefix. Creates an empty file in the default temporary−file directory. you can set the environment variable TMP to a different value.io..io.endsWith("\\")) ) tempdir = tempdir + System.tmpdir do not include a trailing slash.getProperty("file.html import java. meaningful string such as "hjb" or "mail". but if it begins with a period character ('. if ( !(tempdir. If the prefix is too long then it will be truncated. That is.howto"). and the suffix.tmpdir. the temporary file will be deleted when the virtual machine terminates.". It is recommended that the prefix be a short. Win NT Win XP Solaris Linux −−> −−> −−> −−> C:\TEMP\ C:\TEMP /var/tmp/ /var/tmp It's not a bad idea to check if there is a trailing slash or not. Plus. but its first three characters will always be preserved. Deletion will be attempted only for normal termination of the virtual machine. in which case the suffix ".

com/javadetails/. System.68 Get the default character set of the JVM Current version of this HowTo : http://www.println( new java.html import java. // jdk1.Charset.io.defaultCharset().ByteArrayOutputStream()).com/javadetails/.charset. consider making a small donation to show your support for this Web site and its content.exe").0/Reader/acrord32. System.out. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 6.69 Parse a pathname Current version of this HowTo : http://www.getParent()). } } Output example (winXP) >java Hello Cp1252 Cp1252 windows−1252 See also java encoding table for the encoding sets supported.. consider making a small donation to show your support for this Web site and its content.io. public class ParsePathname { public ParsePathname() { } public static void main(String[] args) throws Exception { File f = new File ("c:/program files/adobe/Acrobat 5.getProperty("file.getName()).rgagnon.out.name()). If you find this article useful.out.out.io./javadetails/java−0505. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 6.5 System.encoding")).println(System. 6.4 System.OutputStreamWriter( new java.html public class Hello { public static void main(String args[]) throws Exception{ // not crossplateform safe System.68 Get the default character set of the JVM .nio.rgagnon.println("ext : " + getFileExtension(f. // jdk1./javadetails/java−0514. System.println("file : " + f.File..println("dir : " + f.getName())).If you find this article useful.getEncoding() ).println(java.out.out.

This HowTo is only about OpenSource (and free) solutions.io.rgagnon. import java.70 Handle Excel files . if (i > 0 & i < f.com/javadetails/. Example : output an Excel file from a Servlet import java.').html There are many solutions to read or write Excel spreadsheets from Java. } } If you find this article useful. See this HowTo for an example.out. 6.OutputStream.io. and modify Excel spreadsheets dynamically.. System.exe ext : exe url : file:/c:/program files/adobe/Acrobat 5.71 JDBC−ODBC Excel driver This solution lets you access your Excel worksheet with SQL SELECT statement.length() − 1) { ext = f.0/Reader/acrord32.exe */ } public static String getFileExtension(String f) { String ext = "". One nice thing about JExcelApi is that it has no dependencies on any third party libraries. 6./javadetails/java−0516. write.0/Reader/acrord32.toURI()). int i = f. The required ODBC driver is included in a regular Windows installation and the JDBC−ODBC bridge is used to access the Excel DSN. } return ext.lastIndexOf('. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 6.println("url : " + f.70 Handle Excel files Current version of this HowTo : http://www.toLowerCase(). Any operating system which can run a Java virtual machine can both process and deliver Excel spreadsheets.System.toURL()). consider making a small donation to show your support for this Web site and its content.out.IOException.72 JExcel Java Excel API is a java API enabling developers to read.println("uri : " + f.0\Reader file : acrord32. /* output : dir : c:\program files\adobe\Acrobat 5. 6.exe uri : file:/c:/program%20files/adobe/Acrobat%205.substring(i+1).

getOutputStream()).WritableSheet. read and write XLS spreadsheets..write. wb. "attachment. POI has a dependencies with other JARs (commons. "Hello World")).close().createRow((short)0). 0).xls"). Since it's Jakarta project. HttpServletResponse response) throws ServletException. jxl.log4j.).servlet. modify. s.Label.http. WritableSheet s = w.. POI is your Java Excel solution as well as your Java Word solution. jxl. HSSFSheet sheet = wb. } catch (Exception e){ throw new ServletException("Exception in Excel Sample Servlet".addCell(new Label(0. FileOutputStream fileOut = new FileOutputStream("workbook. javax.servlet. } finally{ if (out != null) out.73 POI .xls").sourceforge.HttpServletRequest. filename=sampleName.73 POI The POI project consists of APIs for manipulating various file formats based upon Microsoft's OLE 2 Compound Document format using pure Java. jxl.servlet.HttpServletResponse. 0. row.setContentType("application/vnd.Workbook.write. HSSF is the POI Project's pure Java implementation of the Excel '97(−2002) file format and it provides a way to read spreadsheets create. try { response.import import import import import import import import javax.createSheet("new sheet").etc.HttpServlet.createSheet("Demo". w. HSSFRow row = sheet.createCell((short)0).write. public class Sample extends HttpServlet { public void doGet (HttpServletRequest request. WritableWorkbook w = Workbook. javax. } } } See http://jexcelapi.setHeader ("Content−Disposition". IOException { OutputStream out = null. Example : create an Excel file HSSFWorkbook wb = new HSSFWorkbook().WritableWorkbook.close(). jxl. response.net/ 6.write().createWorkbook(response.ServletException.setCellValue("HelloWorld"). 6. w. e).http.write(fileOut). javax.servlet.http.ms−excel").

See http://xlsql.transformXLS(templateFileName.sourceforge.00% 4500 See http://jxls. With jXLS. It is based on Jakarta POI. Map beans = new HashMap(). staff. 0.net/ 6.net/ 6. staff. 35. The name was originally an acronym for "Poor Obfuscation Implementation" (ref: Wikipedia). 28. XLSTransformer transformer = new XLSTransformer(). destFileName).30)).org/poi/ 6. xlSQL includes its own "zero−admin" mySQL database.name} Age Payment Bonus ${employee. all you need is to create XLS template file with all required formatting.apache. Example : The XLS Template Employees Name ${employee. 0.sourceforge.put("employee".15)). Documents can be read and written with SQL as if they were tables in a database. 3000.fileOut. beans. You can export XLS to XML or SQL INSERT statements. formulas etc using specific notation to indicate placement of data and then write a couple lines of code to invoke jXLS engine passing XLS template and the exported data as parameters. See http://jakarta.bonus} $[SUM(@employee. 1500.74 JXLS jXLS is a project that allows creation of extremely complex Excel reports just in several lines of code.74 JXLS .add(new Employee("Derek". gives the result Employees Name Age Derek 35 Else 28 Payment Bonus 3000 30.payment} ${employee.age} ${employee.00% 1500 15. beans. staff). transformer.payment@)] with the code Collection staff = new HashSet().add(new Employee("Elsa". The documentation is minimal at this time.close().75 xlSQL xlSQL is a JDBC Driver for Excel and CSV data sources.

.println("Version="+excel.Worksheets().Value( new Date(file.out.ga2.76 JCOM . for(int i=0.Item(1).Item(3.println("Value="+excel.Item(7.Value("can read").Value( file. String[] filenames = path.io.Item(2. System.Value( file.*. jp. xlRange.i+2). xlRange. // display any information System.ga2.File.i+2).ne. The documentation is minimal (in Japanese!).jcom.6.isFile()?"Yes":"No" ).Value()).Value( file. xlRange. ExcelRange xlRange = xlSheet.println("Caption="+excel.no_ji.Value("size" ).i+2).util.Item(2.out.Cells().Value( file.Item(4.Item(6.jcom. xlRange. ExcelWorksheets xlSheets = xlBook.1).Item(4. xlRange.1). Example : import import import import jp.Caption()). i<filenames.lastModified()) ). xlRange. i++) { File file = new File(filenames[i]). System.1).so_net."). // if already started. xlRange..println ("set infomation of files in current directory to cell . java.out.Version()). ExcelWorksheet xlSheet = xlSheets.Value("last modified time").. xlRange.Item(7.UserName()).Workbooks().1).1).println("EXCEL startup.out.Item(6. File path = new File(".out. calculate sum of filesize: "+expression). 6.no_ji. } String expression = "=Sum(B2:B"+(filenames.length. System.println ("embed equation.Value("is file").*..Visible(true).1).Item(1.canWrite()?"Yes":"No" ).out.println("UserName="+excel.i+2).Item(5.excel8.Value("filename" ). ExcelWorkbook xlBook = xlBooks.Value("can write")./"). System. System. xlRange.Item(5.list().76 JCOM JCOM is a Java to COM bridge library.Date.Value( file.i+2).i+2). // create new book // enumurate all files System.ne.Value("is directory"). excel.Value( (int)file.getName() ).isDirectory()?"Yes":"No" ). xlRange.println(file). java.canRead()?"Yes":"No" ).length() ). ExcelWorkbooks xlBooks = excel.length+1)+")". open new window ExcelApplication excel = new ExcelApplication(rm). With JCOM you can call a COM object from Java as if it were a Java object without having to deal with the internals of JNI. try { System.").1). xlRange.out.i+2). xlRange. class TestExcel { public static void main(String[] args) throws Exception { ReleaseManager rm = new ReleaseManager().Item(1. xlRange.Item(3.Add().so_net. xlRange.out.

gif.Value("sum").length+2).. xlRange.out.println("print out. // // // // // comment out."Sheet1"). // xlSheet.filenames.getType()).out.xls"). .false).xlRange.AutoFit(). } finally { rm.com/estore/product_detail..png. String sheetname){ System. // fit columns // comment out.. // read images from sheet 1 −− . // System. This open source effort is the result of over 6 years of development into it.. excel.getImages().77 OpenXLS Java Spreadsheet SDK .println("Begin parsing: " + workingdir + finpath)..jsp?product_group_id=228 Example (extract 3 images from a workbook. void doit(String finpath.t<extracted.filenames. if print out.Columns().out. (My Documents)\\testExcel.Formula(expression).getName()+". System.println("thank you .println ("save to file.").. xlBook. try{ sheet = tbo.t++) { System. 6.getType()).Item(2.Item(1. if no path.net/projects/jcom See also this HowTo for an alternative package to access a COM package from Java. if book save to file.Close(false. FileOutputStream outimg = new FileOutputStream (workingdir + extracted[t].77 OpenXLS Java Spreadsheet SDK OpenXLS claims that it has the best compatibility with complex Excel files and able to handle any kind of Excel file out there without corrupting it.getWorkSheet(sheetname)." +extracted[t]. save to(My Documents) System.")." +extracted[t].printStackTrace().out. // extract and output images for(int t=0.xls").extentech. create a new workbook with them) : doit("testImages.SaveAs("testExcel.jpg ImageHandle[] extracted = sheet.println("Successfully extracted: " + workingdir + "testImageOut_" + extracted[t].xls".length+2).release(). xlRange. } catch(Exception e) { e. See http://www. WorkBookHandle tbo = new WorkBookHandle(workingdir + finpath).getName()+".Quit().PrintOut(). xlBook. .out.length. 6. . // output default printer. } } } See http://sourceforge.null.

CellHandle a1 = sheet. System.round((float)((x * (Math. jpgy. sheet = tbo. bbout.io. a jpg. } testWrite(tbo. ImageHandle jpgy = new ImageHandle(fin. // set picture size and location in sheet giffy. BufferedOutputStream bbout = new BufferedOutputStream(fos). ix = Math. } tbo = new WorkBookHandle().insertImage(jpgy). "A1").setY(200). 6. bbout. // add to sheet ImageHandle giffy = new ImageHandle(fin.File(fout).setX(100 + ix). } catch(Exception e){ System.io. fos.io.extracted[t].x++) { fin = new FileInputStream(workingdir + "testImages.write(b.File f = new java.println("IOException in Tester. sheet.insertImage(pngy).random()*10)))). } // get png image input stream fin = new FileInputStream(workingdir + "testImages.add ("New workbook with 3 images: a gif.random()*10)))). workingdir + "testImagesOut. pngy. } catch (java.xls".77 OpenXLS Java Spreadsheet SDK .println("testImages failed: " + e.println("Successfully read: " + newbook).write(outimg).insertImage(giffy).getWorkSheet("Sheet1").err.0). and a png". outimg.flush(). 400.setY(100 + ix). sheet. // set just the x/y coords of picture pngy.flush().gif").setName("heart" + x).close(). } public void testWrite(WorkBookHandle b. 100.setBounds(100. WorkBookHandle newbook = new WorkBookHandle (workingdir + "testImagesOut. sheet).setName("giffy"). // set the random x/y coords of picture int ix = Math. 200).IOException e){ System. sheet.close().out. // add to sheet for(int x=0. "+e). outimg. // get gif image input stream FileInputStream fin = new FileInputStream (workingdir + "testImages. jpgy.getBytes()). sheet). String fout){ try{ java.round((float)((x * (Math. giffy.x<100.png").xls").jpg"). // add to sheet ImageHandle pngy = new ImageHandle(fin.err.setX(10). jpgy. FileOutputStream fos = new FileOutputStream(f).toString()). sheet).

6. Supported transformations : flat−XML.} } See also this HowTo for a way to create a simple XLS without any additional library. 6.org/utils/CSV.com/javadetails/.sourceforge. http://supercsv. FlatPack provides a sorting mechanism for your flat files.net/projects/csvfile 6.84 CSVFile A simple set of Java classes used to handle CSV http://sourceforge.util CSV Utils CSVPrinter/CSVParser/ExcelCSVPrinter/ExcelCSVParser http://ostermiller.Ostermiller. All kinds of CSV files can be handled. etc.com/java_csv.78 Handle CSV file Current version of this HowTo : http://www.net/ 6.net/ 6. XML−flat. and XML−XML http://servingxml. http://www.85 FlatPack Flat file parser that handles CSV.csvreader. fixed length and custom delimiters. Excel formatted.78 Handle CSV file .sourceforge.83 csvreader Library for reading and writing CSV and plain delimited text files.rgagnon.html 6.82 Super CSV This CSV reader/writer makes it easy to read/write objects/maps/string lists with automatic type conversion and constraint checking./javadetails/java−0591.80 opencsv A simple csv parser library for Java http://opencsv.net/ 6.php 6. text qualified.sourceforge.. Export a DataSet to a fixed length or delimited format.79 com.81 ServingXML Framework for flat/XML data transformations.html 6. flat−flat.

com/javadetails/.http://flatpack.out.pdf")).getInstance(document. From a server.com/iText/ [ITEXT] . document.86 Create an Excel file Current version of this HowTo : http://www.PdfWriter.com/javadetails/. import com.pdf. iText can deal with RTF and HTML file too..FileOutputStream. Document document = new Document().lowagie./javadetails/java−0523.xls with this content <TABLE> <th><h4>Just testing</h4> <TR><TD width="20">1</TD><TD width="30">2</TD><TD width="40">3</TD></TR> <TR><TD>4</TD><TD>4</TD><TD>6</TD></TR> <TR><TD>7</TD><TD>8</TD><TD>9</TD></TR> <TR><TD>=SUM(A3:A5)</TD><TD>=SUM(B3:B5)</TD><TD>=SUM(C3:C5)</TD></TR> </TABLE> Now you can double click on the saved file to load it into Excel and the translation will be done.lowagie. try { PdfWriter.lowagie. an easy way to import data into Excel is to create an HTML file and embed the date into a TABLE tag.html While you can use specialized packages to create native Excel file.86 Create an Excel file . create a file named test.rgagnon.net/ 6. import com.text.text. This trick works with OpenOffice too.sourceforge. public class HelloWorld { public static void main(String[] args) { System.rgagnon. • Create a PDF import java.87 Create or process a PDF file Current version of this HowTo : http://www.*.html A nice OpenSource is http://www. See also this HowTo 6. Nicely documented with many examples.open().IOException. You give to the file the XLS extension and Excel will do the translation for you! With a text editor or from a program. new FileOutputStream("HelloWorld. remember to send the appropriate MIME TYPE : application/excel to the client.. import java.io.io.println("Hello World"). 6./javadetails/java−0586.

io.EMBEDDED). import java. } catch (DocumentException de) { System. BaseFont bf = BaseFont. 32). // adding content to each page int i = 0.PdfReader.err.PdfStamper. BaseFont.A4).lowagie.pdf"). over.WINANSI. over. com.text.pdf.showTextAligned (Element.FileOutputStream.text.lowagie.println(ioe.setMoreInfo(moreInfo).setAbsolutePosition(200.pdf")).showText("page " + i). over. // watermark under the existing page under = stamp. } // adding an extra page stamp.getNumberOfPages().lowagie. img.lowagie.text. under.close().PageSize. "DUPLICATE". "Bruno Lowagie").text. com.insertPage(1.out. } catch (IOException ioe) { System.ALIGN_LEFT.err. new FileOutputStream("watermark_pagenumbers. public class AddWatermarkPageNumbers { public static void main(String[] args) { System. PageSize.text. int n = reader. over.document.put("Author".text. } } • Add a watermark to an existing document. moreInfo. over. 18).getInstance("watermark. Image img = Image.setFontAndSize(bf. 45). com.beginText().setFontAndSize(bf. import java. com. while (i < n) { i++.getUnderContent(i). PdfContentByte over. over.pdf. 230.Image.lowagie.jpg"). try { PdfReader reader = new PdfReader("ChapterSection. // create a stamper that will copy the document to a new file PdfStamper stamp = new PdfStamper(reader.getMessage()).println("Add watermarks and pagenumbers").util.pdf. 30).getOverContent(i).text. com. // text over the existing page over = stamp. com. BaseFont.getMessage()).Element. stamp.add(new Paragraph("Hello World")). 430. import import import import import import import com.BaseFont.setTextMatrix(30. over. 400). PdfContentByte under.lowagie.println(de.pdf.HashMap. } document.86 Create an Excel file . // adding some metadata HashMap moreInfo = new HashMap().PdfContentByte. 6.endText().addImage(img).lowagie.HELVETICA.createFont (BaseFont.

html 6. 0.*. import java. 0).getUnderContent(1). "DUPLICATE OF AN EXISTING PDF DOCUMENT". itext−2. } } } See also this HowTo 6.lowagie. import com.addTemplate (stamp. 0. over.com/javadetails/.txt c:\temp\text. 0. over. 0). download at http://www. Document output = null. For the simple need. System.setFontAndSize(bf.rgagnon.out.showTextAligned(Element. 6. 600.pdf. 30.lowagie.io.pdf").endText().out.lowagie. 3). under. over.text.lowagie.88 Create a PDF . // closing PdfStamper will generate the new PDF file stamp. java TextFileToPDF c:\temp\text.over = stamp. 1.88 Create a PDF Current version of this HowTo : http://www.println("input : " + args[0]).printStackTrace().jar. over. public class TextFileToPDF { /* ex.*.println("Convert text file to pdf"). import com.89 iText http://www. } catch (Exception de) { de. only 1 jar is required (ex.close(). 1.beginText(). you pass on the command line a filename (plain text file − args[0]) to convert to a PDF file (args[1]).out.pdf */ public static void main (String [] args){ BufferedReader input = null.getOverContent(1).1.html) In this example.println("output : " + args[1]). System.. System. 18).getImportedPage(reader2. under = stamp.3.com/iText/download.com/iText/ iText is a very simple to use package to create and manipulate PDF file./javadetails/java−0618.ALIGN_LEFT. // adding a page from another document PdfReader reader2 = new PdfReader("SimpleAnnotations1.*.text.

setAlignment(Element. 40). 40. new FileOutputStream (args[1])). System.close().close().aspx?p=420686 6. } System.out. output.90 Convert OEM (DOS) file to Ansi (Windows) Current version of this HowTo : http://www. System.rgagnon. input.println("Done.readLine())) { System.out. output = new Document(PageSize..addTitle(args[0]). output.").getInstance(output. p. Sybase). mySQL.PageSize for a complete list of page−size constants. output.io.length != 2) { System. } catch (Exception e) { e.com/javadetails/.add(p).exit(0). dBase) to newer DBMS (ex.informit.out. // letter 8.printStackTrace(). import java.lowagie.ALIGN_JUSTIFIED). String line = "".println( "Usage : java OemToAnsi inputdosfile outputansifile" 6.*. public class OemToAnsi { public static void main(String args[]) throws Exception{ if (args.text.try { // text file to convert to pdf as args[0] input = new BufferedReader (new FileReader(args[0])). output.90 Convert OEM (DOS) file to Ansi (Windows) .open(). while(null != (line = input./javadetails/java−0524.println(line). output. Paragraph p = new Paragraph(line).addAuthor("RealHowTo"). // pdf file as args[1] PdfWriter. } } } See also this HowTo A good introduction to iText : http://www.exit(1).5x11 // see com. Clipper.html We are using an InputStreamReader which convert the specified input encoding to Unicode and an OutputStreamWriter which from Unicode to the specified output encoding.addSubject(args[0]). 40. output. 40.com/articles/printerfriendly. This can be useful when migrating data from a legacy database (ex.LETTER.

html You close them in the finally clause using a special method.out. BufferedInputStream in2 = null. } 6.println( " note : codepage input Cp850 ). Written and compiled by Réal Gagnon ©1998−2006 [ home ] 6./javadetails/java−0539. codepage output Cp1252" } // input FileInputStream fis = new FileInputStream(args[0]). } while ( result && i != −1 ). public static boolean compareFile(File file1. in2 = new BufferedInputStream(new FileInputStream(file2)). int i. result = (i == in2. return result.rgagnon.read(). Writer w = new BufferedWriter(new OutputStreamWriter(fos. boolean result = true.exit(1).close().91 Close a stream in a try/catch block . try { in1 = new BufferedInputStream(new FileInputStream(file1)). File file2) { BufferedInputStream in1 = null.readLine()) != null) { w.com/javadetails/. "Cp1252")). consider making a small donation to show your support for this Web site and its content. r.close().91 Close a stream in a try/catch block Current version of this HowTo : http://www. } w. System. // output FileOutputStream fos = new FileOutputStream(args[1]).exit(0). System. "Cp850")). } } See also this related HowTo If you find this article useful. BufferedReader r = new BufferedReader(new InputStreamReader(fis.printStackTrace().write(oemString).read()).). do { i = in1. } catch (FileNotFoundException ex) { ex.. String oemString = "".flush(). while ( (oemString= r. w. System.

String currentExtension = getFileExtension(source).92 Rename a file extension Current version of this HowTo : http://www.html public static boolean renameFileExtension (String source. if (i > 0 && i < f.93 Remove HTML tags from a file to extract only the TEXT Current version of this HowTo : http://www.renameTo(new File(target)).html 6. } return ext.catch (IOException ex) { ex.rgagnon. } finally { close(in1).replaceAll(". } catch ( IOException ioe ) { ioe. String newExtension) { String target.equals("")){ target = source + "./javadetails/java−0541.rgagnon.printStackTrace(). } private static void close( InputStream is ) { if ( is != null ) { try { is.length() − 1) { ext = f. } public static String getFileExtension(String f) { String ext = "".." + newExtension. if (currentExtension.substring(i + 1).printStackTrace().').lastIndexOf('.com/javadetails/./javadetails/java−0424.close(). } } } 6. } 6.toLowerCase(). } return new File(source).92 Rename a file extension . } else { target = source. close(in2).com/javadetails/. } return false. newExtension)." + currentExtension. int i = f..

*.html.parse(in. System.html."").append(text).toString(). } catch (Exception e) { e. import javax. ParserDelegator delegator = new ParserDelegator(). } public String getText() { return s.replaceAll("\\<. the HTMLEditorKit is used with a JEditorPane text component but it can be also used directly to extract text from an HTML page.ParserCallback { StringBuffer s.*?>".*.swing.HTMLEditorKit In most cases.parser. import java. while ( (line=br.text.swing.swing.io.text.*.out. } } } However if any Javascript is present. public Html2Text() {} public void parse(Reader in) throws IOException { s = new StringBuffer(). the script will be seen as text. 6.94 Using regular expression . String line. Boolean.println(nohtml). Also you may need to add some logic during the reading to take into account only what is inside the <BODY> tag.95 Using javax. BufferedReader br = new BufferedReader (new FileReader ("java−new.*.html")). int pos) { s. } public void handleText(char[] text.append(line).94 Using regular expression A special regular expression is used to strip out anything between a < and > . import javax.TRUE). this.text.printStackTrace(). } String nohtml = sb. import java.6.io.toString(). } 6.html. // the third parameter is TRUE to ignore charset directive delegator.readLine()) != null) { sb. public class Html2TextWithRegExp { private Html2TextWithRegExp() {} public static void main (String[] args) { try { StringBuilder sb = new StringBuilder(). public class Html2Text extends HTMLEditorKit.

html").getContentType(f)). System.out.parse(in).rgagnon.sun. in.mime.gif is image/gif" } } The built−in mime−type list is very limited but a mechanism is available to add very easily more Mime Types/extensions.. The MimetypesFileTypeMap looks in various places in the user's system for MIME types file entries.96 Get the Mime Type from a File . import javax. 3. The file or resources named META−INF/mime. } catch (Exception e) { e.com/javadetails/.jar. The MimetypesFileMap class is used to map a File to a Mime Type.public static void main (String[] args) { try { // the HTML to convert FileReader in = new FileReader("java−new.io.1 Using javax.jar is required.types.types.com/products/javabeans/glasgow/jaf. When requests are made to search for MIME types in the MimetypesFileTypeMap. it can be downloaded from http://java.println(parser. Html2Text parser = new Html2Text(). 2. The file <java.html 6.gif").println("Mime Type of " + f. // expected output : // "Mime Type of gumby. Mime types supported are defined in a ressource file inside the activation.printStackTrace(). it searches MIME types files in the following order: 1.getName() + " is " + new MimetypesFileTypeMap().getText()).activation. parser.home>/lib/mime. System.96 Get the Mime Type from a File Current version of this HowTo : http://www. The file .96. } } } 6.types in the user's home directory. 4.activation.MimetypesFileTypeMap activation.MimetypesFileTypeMap.html. 6. class GetMimeType { public static void main(String args[]) { File f = new File("gumby.close()./javadetails/java−0487. Programmatically added entries to the MimetypesFileTypeMap instance.out. import java.File.

URL u = new URL(fileUrl).URL Warning : this method is very slow!.out. // snippet for mime−util lib // http://sourceforge.getMimeType()) . The mapping between the extension and the mime−type is defined in the file [jre_home]\lib\content−types.net/projects/jmimemagic/ Magic parser = new Magic() .96. // snippet for JMimeMagic lib // http://sourceforge. // getMagicMatch accepts Files or byte[]. uc = u.println(match.net.getContentType(). The result is very fast because only the extension is used to guess the nature of a given file.default (usually found only in the activation. The file or resource named META−INF/mimetypes.openConnection().TXT")). System. A more robust solution is possible with the JMimeMagic library.URL . return type.3 Using JMimeMagic Checking the file extension is not a very strong way to determine the file type.net. MalformedURLException { String type = null. type = uc. public class FileUtils{ public static String getMimeType(String fileUrl) throws java.*.properties import java. This tool can detect using the file extension or the magic header technique.4 Using mime−util Another tool is mime−util. // output : text/plain } } 6. URLConnection uc = null. Thanks to Jean−Marc Autexier and sygsix for the tip! 6.IOException. JMimeMagic is a Java library (LGLP licence) that retrieves file and stream mime types by checking magic headers. } public static void main(String args[]) throws Exception { System. 6.gif")).io.jar file).2 Using java.2 Using java.5.96.out.getMimeType("file://c:/temp/test.96. // which is nice if you want to test streams MagicMatch match = parser.net.net/projects/mime−util 6.getMagicMatch(new File("gumby. Like the above method a match is done with the extension.println(FileUtils.96. This method is interesting when you need to deal with incoming files with the filenames normalized.

util.96. websites.*.. if(mimeType == null) mimeType = UNKNOWN_MIME_TYPE. and DROID can be configured to automatically download updated signature files from the PRONOM website via web services. a set of APIs has been developed and a number of implementations is provided.rgagnon. http://aperture. java.. String mimeType = MimeUtil.96. websites and mail boxes. It can be invoked from two interfaces./javadetails/java−0606. 6.sourceforge.wiki.97 Sort a directory listing Current version of this HowTo : http://www. DROID uses internal and external signatures to identify and report the specific file format versions of digital files.5 Using Droid DROID (Digital Record Object Identification) is a software tool to perform automated batch identification of file formats.util. .com/javadetails/.util. The nice thing about mime−util is that there is no dependency (with others Apache packages) so it is very lightweight.5 Using Droid . mail boxes • MIME type identification • Full−text and metadata extraction of various file formats • Opening of crawled resources For each of these parts. These signatures are stored in an XML signature file.Date.Comparator.96. http://droid.net/Overview 6. New and updated signatures are regularly added to PRONOM.Arrays. a Java Swing GUI or a command line interface. java.6 Aperture framework Aperture is an open source library and framework for crawling and indexing information sources such as file systems. generated from information recorded in the PRONOM technical registry. The Aperture code consists of a number of related but independently usable parts: • Crawling of information sources: file systems.php/Introduction 6. import import import import java. java.net/wiki/index.public static final String UNKNOWN_MIME_TYPE="application/x−unknown−mime−type".io..html This HowTo sorts a directory listing in ascending or descending order. 6.getMagicMimeType(file).sourceforge.

println("*********").dirListByDescendingDate (new File("C:/Applications/folder")). Arrays.getName() + " " + new Date(file.sort( files. for (File file : files) { System.lastModified())).isDirectory()) { return null.lastModified()). return files. } System. final Object o2) { return new Long(((File)o2).println(file.listFiles(). } }).out. } @SuppressWarnings("unchecked") public static File[] dirListByDescendingDate(File folder) { if (!folder. } File files[] = folder.lastModified()).out.public class FileUtils{ public static void main(String args[]) throws Exception { File files[] = FileUtils.lastModified())). } }). } } Take a look at this HowTo to filter by a date interval. } File files[] = folder.lastModified())). final Object o2) { return new Long(((File)o1).isDirectory()) { return null.println(file.compareTo (new Long(((File) o2). for (File file : files) { System.sort( files.out.getName() + " " + new Date(file.98 Filter a directory listing by date . files = FileUtils.compareTo (new Long(((File) o1).dirListByAscendingDate (new File("C:/Applications/folder")).98 Filter a directory listing by date Current version of this HowTo : 6. return files. new Comparator() { public int compare(final Object o1.lastModified())). } } @SuppressWarnings("unchecked") public static File[] dirListByAscendingDate(File folder) { if (!folder. new Comparator() { public int compare(final Object o1. Arrays. 6.listFiles().

format(d). File folder = new File("C:/temp").html This HowTo filters a directory listing based on a date interval.html Use the numerical identity to represent the / in the javadoc section to avoid any conflict with a real comment. "2004−12−31"). 6..io. String dateEnd.Date. } } Then import java.rgagnon.File. import java.*.format(new Date(f.dateEnd = dateEnd. return ((dateStart.com/javadetails/.*. import java. String dateEnd) { this. import java. import java.SimpleDateFormat. SimpleDateFormat sdf.99 Display a comment in a Javadoc .lastModified()))). FileFilterDateIntervalUtils filter = new FileFilterDateIntervalUtils("2004−01−01".compareTo(current) < 0 && (dateEnd. 6./javadetails/java−0615. public class Test { public static void main(String[] args) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy−MM−dd"). for (File f : files) { System.dateStart = dateStart. String current = sdf.out.99 Display a comment in a Javadoc Current version of this HowTo : http://www.com/javadetails/. sdf = new SimpleDateFormat("yyyy−MM−dd"). public class FileFilterDateIntervalUtils implements FilenameFilter { String dateStart..println(f.text.util. } } } Take a look at this HowTo to sort the filenames in ascending/descending order. name). String name) { Date d = new Date(new File(dir.rgagnon./javadetails/java−0607. File files[] = folder.compareTo(current) >= 0))). public FileFilterDateIntervalUtils(String dateStart. } public boolean accept(File dir.text. import java.listFiles(filter).io.getName() + " " + sdf.util. this.*.http://www.lastModified()).

zip ** */ import java.rgagnon. for(int i = 0.setVisible(true). ZipOutputStream zout = new ZipOutputStream(System.* create a frame *&#47.putNextEntry(e). the syntax is &#nnn.0.*. public class Example { /** * Simple Frame * <pre> * &#47. f.out). i < args. } } and the javadoc output is : You can represent any character with a numerical identity. 6.len).length. } public static void print(ZipEntry e){ PrintStream err = System.'/')).separatorChar.2 > file.close(). class Zip { public static void main(String args[]) throws IOException { byte b[] = new byte[512]. where nnn is the Unicode code (decimal value) of the character./javadetails/java−0065. print(e).1 file.write(b.zip.100 Create a compressed (ZIP) file . int len=0. zout. ZipEntry e = new ZipEntry(args[i].replace(File. * Frame f = new Frame() * </pre> * @param args */ public static void main(String args[]){ Frame f = new Frame().100 Create a compressed (ZIP) file Current version of this HowTo : http://www. while((len=in. f.io. } zout.com/javadetails/. i ++) { InputStream in = new FileInputStream(args[i]).err.closeEntry(). } zout.import java.read(b)) != −1) { zout.awt..setSize(200.html /* ** a simple ZIP tool ** ** ex.*.*. import java.200). 6. java Zip file.util.

DEFLATED) { long size = e. Expand the contents of the old ZIP.getMethod() == ZipEntry. } } } NOTE: There no way to directly add or modify an entry to a ZIP file after its creation.format(d) + " "). err. } } else { err. if (e./javadetails/java−0066.*. 6. ZipInputStream zin = new ZipInputStream(in).print(e. java ViewZip file.err. err. long ratio = ((size−csize)*100) / size.println(" (deflated 0%)"). if (size > 0) { long csize = e.println("Size\t Date Time Method Ratio Name"). To do so.. } else { err. 6.print(df. import java. import java.err.io.println(" (deflated " + ratio + "%)"). System.getNextEntry())!= null) { zin. } zin.err.println(" (stored 0%)").dd Date d = new Date(e. if (e. err.print("added " + e. System. import java. create the new ZIP.101 Display compressed (ZIP) file content Current version of this HowTo : http://www.101 Display compressed (ZIP) file content . print(e).getTime()).DEFLATED) { hh:mm:ss").html /* ** a simple viewZIP tool ** ** ex.mm.zip ** */ import java.util.getSize(). while((e=zin.util. } public static void print(ZipEntry e) { PrintStream err = System. ZipEntry e.rgagnon.err.getSize() + "\t").*.*.println("−−−−\t −−−− −−−− −−−−−− −−−−− −−−−"). add the original contents plus the new files and delete the old ZIP when done.text. DateFormat df = new SimpleDateFormat ("yyyy.zip. rename the old ZIP to a temporary filename.close(). class ViewZip { public static void main(String args[]) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(args[0])).com/javadetails/.*.getMethod() == ZipEntry.getName()).getCompressedSize().closeEntry().

args[1]). break.. ZipEntry e. long ratio = ((size−csize)*100) / size. } } else { err.print(" 0% ").html /* ** a simple unZIP tool ** ** ex.zip.util.getName()).getName(). if (size > 0) { long csize = e.write(' ').*.println(e.equals(args[1])) { unzip(zin.io.close().*. import java.*. to unzip file 1 from file.err.zip to unzip file.102 Expand the compressed (ZIP) file Current version of this HowTo : http://www.println(" (stored } err. java UnZip file. } public static void unzip(ZipInputStream zin. if (ratio < 10) { err.com/javadetails/. import java. } else { err. } err. String s) throws IOException { 6. while((e=zin. } } unzip(zin.getCompressedSize().getNextEntry())!= null) { if (args.length > 1) { if (e.getName()). } zin.text. import java. } } 0 %").zip class UnZip { public static void main(String args[]) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(args[0])). long size = e.util.rgagnon. 6.*.zip ** */ import java. ZipInputStream zin = new ZipInputStream(in)./javadetails/java−0067.print(ratio + "% ").print("deflated "). e.zip file1 ** java UnZip file.getSize().102 Expand the compressed (ZIP) file .

1. public static void sound(int hz.out.*.print("\007"). 6.close().3 public class Tone { public static float SAMPLE_RATE = 8000f. Any sample rate beyound that will not work.System. //jdk1.com/javadetails/. } } The buzzer on the motherboard is used.rgagnon.out./javadetails/java−0499.103 Emit a beep Current version of this HowTo : http://www.beep(). byte [] b = new byte[512]. See also this How−to..getDefaultToolkit(). 6. System.rgagnon.read(b))!= −1 ) { out.104 Emit a Tone Current version of this HowTo : http://www. FileOutputStream out = new FileOutputStream(s).write(b. If no sound file is selected then the beep() will be a silence. while ( (len=zin.html import javax.103 Emit a beep . use the beep method in the Toolkit import java. public class Beep { public static void main(String args[]) { Toolkit. } } 6./javadetails/java−0001.html There are three ways to emit a beep in Java.com/javadetails/.sampled.out. • Starting with JDK 1. } } (Windows) The sound used is determined from the setting found in Control Panel/Sounds and Devices/Sounds/Sound Scheme/"Default Beep". AU files need to be created at a sample rate of 8000.flush()..awt. } out. int msecs) throws LineUnavailableException { byte[] buf = new byte[1].println("unzipping " + s).len).*. int len = 0. • Print the ASCII Bell character to the console public class TestBeep { public static main(String args[]) { // ASCII bell System.0.sound. • Use an AU audio file For Java.

try{ AudioStream as = new AudioStream(new FileInputStream("aSound.2. } } } If you find this article useful. .100).player.105 Play an audio file from an application Current version of this HowTo : http://www.105 Play an audio file from an application . buf[0] = (byte)(Math.sin(angle) * 110..sound(100. i<msecs*8. in a regular Java application) with java.2. import sun. So it may be possible to use it without an Applet (i. sdl. sdl.true.100). sdl.sound(1000.PI. } public static void main(String[] args) { try { Tone..sun.. SourceDataLine sdl = AudioSystem.com/javadetails/.*.com/docs/books/tutorial/sound/playing. sdl.au")).0 * Math..Applet.8. Tone.start(). } sdl. .out.AudioFormat af = new AudioFormat(SAMPLE_RATE. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 6.printStackTrace().getAudioClip(URLofMySound).open(af).start(as). see http://java. } catch (LineUnavailableException lue) { System. Note: Since JDK1.html With Applet. getAudioClip() is now a static method. 6. AudioPlayer p=AudioPlayer./javadetails/java−0006.1000).audio package. Another way is to use the undocumented sun. p. Tone.1).close().write(buf. i++) { double angle = i / (SAMPLE_RATE / hz) * 2.drain(). for (int i=0.sound(5000..1.html.audio.0).rgagnon. } catch(IOException err){ err.false).applet. the getAudioClip method() from the Applet package is used to play sound file. sdl.stop(). Java can play WAV directly.println(lue). Starting with JDK1.0. consider making a small donation to show your support for this Web site and its content.getSourceDataLine(af).e.

import sun.*.start(as). } } Since JDK1. AudioPlayer.} To play a sound from a JAR file (the .com 6. Written and compiled Réal Gagnon ©2007 real@rgagnon.player.105 Play an audio file from an application .3. see this HowTo. you have also the javax.*.class.net. public class AppAudio { public static void main(String args[]) throws Throwable { InputStream in = AppAudio.audio.com http://www.io. import java.sleep(5000).rgagnon.AU file in the JAR must be accessible via the CLASSPATH of course!) : import java. Thread.sound package.getResourceAsStream(args[0]). AudioStream as = new AudioStream(in).*.

printStackTrace(). import java.1 java−jdbc 7. } finally { try { if (theConn != null) theConn.com/javadetails/.getString("objet")). import java.getConnection().7 JDBC 7. Statement stmt. public static void main (String args[]) { try { // connection to an ACCESS MDB theConn = MyConnection. } rs.2 Connect to a database via JDBC−ODBC Current version of this HowTo : http://www.close().forName 7 JDBC .html You have to keep in mind that the bridge JDBC−ODBC is only useful in an Application. sql = "select objet from Email".next()) { System.rgagnon.executeQuery(sql).close().URL.net. } catch (Exception e) { } } } } class MyConnection { public static Connection getConnection() throws Exception { Driver d = (Driver)Class. String sql./javadetails/java−0107. stmt = theConn. you can't use it with JAVA Applet because ODBC requires some DLL on the client machine (forbidden for security reason). class JDBCapp { static Connection theConn.sql.close()..createStatement().*.out.println(rs. } catch (Exception e) { e. while (rs. stmt. ResultSet rs. rs = stmt.

rgagnon.printStackTrace().close(). Connection c = DriverManager.("sun.newInstance().out.executeQuery().3 SELECT data from a table . String sql.createStatement().out./javadetails/java−0108.println(rs. 7.mdb)}. */ } } 7. prepstmt. rs = prepstmt. return c.prepareStatement ("select custName.jdbc. Connection c = DriverManager. else System. if (found) System..getConnection(URL. CustAddr from tCust where custId = ?"). stmt = theConn.JdbcOdbcDriver"). "user".odbc.getConnection( "jdbc:odbc:Driver={Microsoft Access Driver (*.com/javadetails/.DBQ=c:/tech97. sql = "select custName from tCust where custName = " += "'" + name + "'". id). prepstmt = theConn. "pwd"). try { PreparedStatement prepstmt.html Note:the MyConnection class was used to connect to the DB With a Prepared Statement (only 1 row) String id = cust_id.executeQuery(). prepstmt. /* To use an already defined ODBC Datasource : String URL = "jdbc:odbc:myDSN".getText().getString(1)).getText().println("Customer " + id + " not found!"). try { Statement stmt.3 SELECT data from a table Current version of this HowTo : http://www. } With a Statement (many rows) String name = cust_name. ResultSet rs.next(). rs = stmt.mdb" ). found = rs.setString(1. } catch (Exception e) { e. boolean found = false. ResultSet rs.

length(). Even." "('" + custAddr + "')". Thanks to Lawrence Angrave for the warning. i < source.com/javadetails/.println(rs. Even. if(source.commit(). stmt = theConn.html Note:the MyConnection class was used to connect to the DB Statement stmt. String sql.close(). String concatentation of this form can only be used if you first validate the fields to include only alphanumeric characters..charAt(i)).close().while (rs. i++){ sb. stmt. custName.createStatement(). } You need to be aware to the snippet above contains a SQL Injection vulnerability.charAt(i)=='\'') sb. custAddr) " "VALUES " "('" + custId + "'.getString("custName")).append(source. 7.append('\'') } return sb.rgagnon. public static String convertString(String source) { StringBuffer sb = new StringBuffer(). theConn. You can use the following function to "prepare" your string.executeUpdate(sql).next()) { System./javadetails/java−0109. You need to be aware to the snippet above contains a SQL Injection vulnerability. This is especially when you in a Web application environnement.dbConn. 7. for(int i = 0. } rs.4 INSERT data into a table .4 INSERT data into a table Current version of this HowTo : http://www. rows = stmt. then it is generally considered bad practice when prepared statements solve this problem more cleanly. Before inserting data containing quotes. String concatentation of this form can only be used if you first validate the fields to include only alphanumeric characters. int rows. } catch (Exception e) { e.out.close(). This is especially when you in a Web application environnement.printStackTrace(). Thanks to Lawrence Angrave for the warning. then it is generally considered bad practice when prepared statements solve this problem more cleanly.toString()." "('" + custName + "'. sql = + + + + + "INSERT INTO tCust " "(custId. stmt. you may need to double them (so "Real's HowTo" −> "Real''s HowTo").

rgagnon. rows = stmt. } 7.html Note:the MyConnection class was used to connect to the DB PreparedStatement prepstmt. may generate a SQL Exception even if the "\" is escaped for Java because you need to escape it again for the database. At the end. prepstmt.out.println(sql).} Or you can use a PreparedStatement to insert data containing QUOTES PreparedStatement stmt = null. theConn. cust_id.close().executeUpdate().printStackTrace(). prepstmt. stmt.commit(). System. stmt.executeUpdate("INSERT INTO mytable VALUES('\\\\')"). int rows. } catch (Exception e) { e. stmt. "Name with \" are permitted!"). 7. you need to use "\\\\" to INSERT a simple "\"."Smith").5 MODIFY data in a table . prepstmt. stmt. stmt = theConn. } catch (Exception e){ e.setString(1.printStackTrace().prepareStatement ("UPDATE tCust SET custName = ? "+ " WHERE custId = ?"). String sql.com/javadetails/.commit(). prepstmt./javadetails/java−0110.5 MODIFY data in a table Current version of this HowTo : http://www.setString(1.executeUpdate().close(). } The character "\" can be difficult to use in an INSERT statement since "\" is considered as an escape character in Java (and probably by the database also).. try { prepstmt = theConn.executeUpdate("INSERT INTO mytable VALUES('\\')"). theConn.setString(2. try { sql = "INSERT INTO tCust" + "(custName) " + "VALUES " + "(?)".prepareStatement(sql).getText()).

.rgagnon./javadetails/java−0111.cust_id.out. } while (rs.printStackTrace(). if (found) System. prepstmt..next()) { do { System.close().next().getText()).rgagnon. // execute the query and then found = rs. } catch (Exception e) { e. if (rs.com/javadetails/. ..6 DELETE data in a table Current version of this HowTo : http://www.println("Record found").executeUpdate()..println("RECORD NOT FOUND"). theConn.out.next()).html boolean found. } else { System.prepareStatement ("DELETE FROM tCust "+ " WHERE custId = ?").println("Record found").commit().setString(1.html Note:the MyConnection class was used to connect to the DB PreparedStatement prepstmt.. A nicer way to do the same would be ResultSet rs.7. prepstmt. } 7.com/javadetails/. try { prepstmt = theConn. .out.out. else System../javadetails/java−0116.println("Record not found").6 DELETE data in a table . prepstmt. } 7.7 Test for an empty ResultSet Current version of this HowTo : http://www. ResultSet rs.

8 Store and retrieve an object from a table .bais.executeUpdate().7.printStackTrace(). // bind our byte array to the emp column pstmt.prepareStatement ("INSERT INTO EMPLOYEE (emp) VALUES(?)"). j.dbConn. public static void main (String args[]) { JDBCapp j = new JDBCapp().selectFromEmp().8 Store and retrieve an object from a table Current version of this HowTo : http://www. try { ByteArrayOutputStream baos = new ByteArrayOutputStream().."Real Gagnon". 98000).executeQuery("SELECT emp FROM Employe").close(). pstmt. ResultSet rs = stmt.rgagnon.dbConn. import java.sql. // serialize the employee object into a byte array byte[] employeeAsBytes = baos. "username". import java. } catch(Exception e) { e. theConn.connect("your_db_profile". j.insertIntoEmp().html Assume that we have a table called "Employee". "password").createStatement().connectToDB().dbConn. with only one field called "emp" and "long binary" or "blob" as data type. ObjectOutputStream oos = new ObjectOutputStream(baos). pstmt. theConn. import java.setBinaryStream(1.length).URL. // loop through the result set while (rs.writeObject(employee). oos. The object "Employee" will be serialized into the table "Employee" ( ideally the table "Employee" should have an index key. something like emp_id. class JDBCapp { static MyConnection theConn.next()) { 7.com/javadetails/.net. ByteArrayInputStream bais = new ByteArrayInputStream(employeeAsBytes). try { Statement stmt = theConn. } } public void selectFromEmp() { boolean found. j.io./javadetails/java−0117. } public void connectToDB() { theConn = new MyConnection(). } public void insertIntoEmp() { Employee employee = new Employee(42. but for the example there is none).commit(). PreparedStatement pstmt = theConn.*.*.toByteArray(). We want to insert an instance of the class "Employee" into the table "Employee". employeeAsBytes.

// or Blob aBlob = rs. String URL = "jdbc:odbc:" + db. ObjectInputStream ois = new ObjectInputStream(baip).printStackTrace().JdbcOdbcDriver").getObject(1).getBytes(0. String user.close().out.odbc. } } } class Employee implements Serializable { int ID. // display the result for demonstration System.newInstance(). ByteArrayInputStream baip = new ByteArrayInputStream(st). } stmt.name). public Employee(int ID. void connect(String db. String passw) { try { Driver d = (Driver)Class.forName ("sun. } catch (Exception e) { e. String name. // byte[] st = aBlob.getConnection(URL. this. } } } 7. this. double salary) { this. } catch (Exception e) { e.printStackTrace().// fetch the serialized object to a byte array byte[] st = (byte[])rs.length()).getBlob(1). // re−create the object Employee emp = (Employee)ois.close(). String name.printStackTrace().getBytes(1).jdbc. } catch(Exception e) { e. } } class MyConnection { Connection dbConn = null.readObject(). (int) aBlob.name = name.ID = ID. user. passw).8 Store and retrieve an object from a table . double salary.salary = salary. // or byte[] st = rs.close(). } } void disconnect() { try { dbConn. rs. dbConn = DriverManager.println(emp.

InputStream stream = rset. ps./javadetails/java−0119.read().11 Connect to an Oracle database with JDBC Current version of this HowTo : http://www.9 Retrieve an Image Current version of this HowTo : http://www.prepareStatement("insert into images values (?./javadetails/java−0112.length()). } myImage = Toolkit.file.getBinaryStream(column).createImage(output.read(). SQLException { Class.setBinaryStream(2. All you need is to include the required jar in the classpath.write((char)a1). FileInputStream fis = new FileInputStream(file).getDefaultToolkit().jdbc. // // or 7.rgagnon. // we assume that the type is LONGVARBINARY Image myImage = null.?)").html Oracle Corporation has released a free 100% JAVA driver.html // column is column index in ResultSet containing the image.close(). output.fis.*.com/javadetails/.rgagnon.com/javadetails/.OracleDriver").getName()).rgagnon. fis. try { int a1 = stream.toByteArray()). 7. } catch(Exception e){} 7. PreparedStatement ps = conn. import java.10 Insert an Image Current version of this HowTo : http://www. It is available at their Web site.setString(1.(int)file.gif").9 Retrieve an Image .executeUpdate().driver. ps.7.sql.. ps. ByteArrayOutputStream output = new ByteArrayOutputStream(). a1 = stream.forName("oracle.close()./javadetails/java−0118..com/javadetails/. ps..close(). while (a1 >= 0) { output. public class TestDBOracle { public static void main(String[] args) throws ClassNotFoundException.html File file = new File("myimage.

executeQuery("select BANNER from SYS. ResultSet rset = stmt. the first connection request to the OracleDataSource transparently creates a connection cache. we have a program with several threads. } } See also this HowTo to connect using the Oracle Connection Pool.getConnection(). a logical connection is returned wrapping the physical connection. 7. System.local:1521:prodsid".html The Oracle thin jdbc driver (v9.createStatement().12 Connect to Oracle using a connection pool Current version of this HowTo : http://www. Each thread makes a connection but the login process is done only once. wrapped in a logical connection.jdbc.rgagnon.").println ("Ok. whenever you retrieve a connection through an OracleDataSource.next()) { System.com/javadetails/."scott".local:1521/prod".out.getConnection(url.2) makes it very easy to use a connection pool. In this example.setAutoCommit(false).The getConnection() method checks if there are any free physical connections in the cache that match the specified criteria. } stmt.println (rset.registerDriver // (new oracle. and returned. it's all built in the OracleDataSource with the implicit connection cache mechanism.// DriverManager. // jdbc:oracle:thin:@host:port:SID Connection conn = DriverManager. "tiger"). After implicit caching is turned on. the JDBC drivers check to see if a connection is available in the cache. while (rset. // jdbc:oracle:thin:@//host:port/service // or // String url = "jdbc:oracle:thin:@server. 7. First a static class to manage the connection pool. a new physical connection is created. If no physical connection match is found.OracleDriver()).12 Connect to Oracle using a connection pool .setConnectionCachingEnabled(true).getString(1)). conn.driver. If a match is found. maximum connections and idle connections can be set to make sure the connection pool works well according to the environment it is deployed to work in. An application turns the implicit connection cache on by invoking OracleDataSource.out. A Connection Pool is a cache of database connections maintained in memory so that the connections can be reused when the database receives future requests for data.close().V_$VERSION"). Statement stmt = conn./javadetails/java−0545. After you have turned connection caching on. Various parameters such as number of minimum connections. String url = "jdbc:oracle:thin:@//server. Connection pools are used to enhance the performance of executing commands on a database..

OracleDataSource. unspecified").setConnectionCacheProperties(cacheProps).info("Initialisation du OracleDataSource"). cacheProps.sql. } public static void closePooledConnections() throws SQLException{ if (ods != null ) { ods.*. } public static Connection getConnection(String env) throws SQLException { System. cacheProps. } } /** * private constructor for static class */ private JDBCUtils() { } public static Connection getConnection() throws SQLException { return getConnection("env. Properties cacheProps = new Properties().setProperty("MinLimit".printStackTrace(). "1").util.12 Connect to Oracle using a connection pool .out.getConnection(). import java. } catch (SQLException e) { e. public class JDBCUtils { private final static String CACHE_NAME = "MYCACHE".setConnectionCachingEnabled(true).setProperty("ValidateConnection".local:1521/prod"). try { ods = new OracleDataSource().setConnectionCacheName(CACHE_NAME). } return ods. cacheProps. "5").setUser("scott"). import oracle."). ods. static { logger.setProperty("ConnectionWaitTimeout".println("Request connection for " + env).jdbc.pool. cacheProps.close().jdbc. "1"). "true"). // caching parms ods.setProperty("MaxLimit". ods. } } public static void listCacheInfos() throws SQLException{ OracleConnectionCacheManager occm = 7. private static OracleDataSource ods = null. if (ods == null) { throw new SQLException("OracleDataSource is null. import java. ods. cacheProps. "4").setProperty("InitialLimit".Properties.import oracle.setURL("jdbc:oracle:thin:@//server.OracleConnectionCacheManager. ods.setPassword("tiger"). ods.pool.

7.out.out.close().printStatckTrace() } finally { System.listCacheInfos(). try { Thread. while (rset.out.next()) System.executeQuery("select BANNER from SYS. stmt.. conn. Statement stmt = conn.getNumberOfActiveConnections(CACHE_NAME) + " connections are active").*. System.out. the main class import java. } public void run() { System.sql.URL.println ("Sleep.OracleConnectionCacheManager. public class TestDBOraclePool3Thread implements Runnable { private int noThread = 0.*. TestDBOraclePool3Thread(int n) { noThread = n. ResultSet rset = stmt.println ("Ok. JDBCUtils.V_$VERSION").createStatement().println (rset.").12 Connect to Oracle using a connection pool . } } then the working thread import java.println("Starting Thread " + noThread)..out.println (occm. } catch(Exception e) { } } } } } and finally.getNumberOfAvailableConnections(CACHE_NAME) + " connections are available in cache " + CACHE_NAME).sleep(1000). conn.println (occm.getConnection("env " + noThread).getConnectionCacheManagerInstance().getString(1)).out.close(). while (true) { try { Connection conn = JDBCUtils. } catch (SQLException e) { e. " + noThread).setAutoCommit(false).net. import java.sql. System. System.

java.com/javadetails/.util.Date sqlToday = new java.start(). it's the same idea java. Time or Timestamp in a query. Date {d 'yyyy−mm−dd'} Time {t {'hh:mm:ss'} Timestamp {ts `yyyy−mm−dd hh:mm:ss.Date().util.sql. java./javadetails/java−0113.util. new Thread( new TestDBOraclePool3Thread(2)). you can use JDBC escape codes.f .'} note: the .public class TestDBOraclePool3 { public static void main(String[] args) throws SQLException { new Thread( new TestDBOraclePool3Thread(1)). new Thread( new TestDBOraclePool3Thread(7)).start(). new Thread( new TestDBOraclePool3Thread(4)).sql.rgagnon.Timestamp now = new java.getTime()).Date today = new java.13 Get JDBC driver for major database vendors .com/javadetails/.getTime()).Date sqlToday = new java..start().. .sql.14 Handle dates Current version of this HowTo : http://www. For Timestamp.Date today = new java.sql.start()./javadetails/java−0114.sql.start().util.Date(today. } } 7. java. new Thread( new TestDBOraclePool3Thread(3)).util.Date(today.. 7.Date().13 Get JDBC driver for major database vendors Current version of this HowTo : http://www.util. .start()..f .html To get the current date in SQL format. java. a Statement with a Date will look like this java.start().Date today = new java.rgagnon.sql. new Thread( new TestDBOraclePool3Thread(6)). To use a Date.Date().. new Thread( new TestDBOraclePool3Thread(5)).getTime()).Timestamp(today.html JDBC vendors list Intersolv plugin to access ODBC database through a browser 7. is optional For example.

executeUpdate(). PreparedStatement p = theConn. To INSERT PreparedStatement p = theConn.?).Date(today.registerOutParameter(2.com/javadetails/. and milliseconds to zero in the particular time zone with which the instance is associated. then String query = "begin thePackage. CallableStatement cs = conn. ResultSet rs = p.sql. the JDBC driver will do the job for you.prepareStatement ("insert into TableWithADateColumn values(?)"). java.Date instance must be 'normalized' by setting the hours. p. seconds.Date today = new java. or p. // #1 is cs. With a PreparedStatement.registerOutParameter(3.getTime()).setInt(2./javadetails/java−0115. you don't need JDBC escape codes.15 Call a stored procedure Current version of this HowTo : http://www.execute().setDate(1. minutes.sql.Date sqlToday = new java.15 Call a stored procedure . INPUT INPUT OUTPUT OUTPUT // get the result from OUTPUT #2 7.getInt(2).?. int output_parm2 = cs.theProcedure(?.toString() + "' }"). One thing to remember when using java.setString(1. sqlToday).sql.setDate(1.String query = "select * from cust where purchase_date <{ d '" + sqlDate.executeQuery(). end.prepareCall(query). 7.INTEGER). // #2 is cs. // #3 is cs.executeUpdate ("insert into TableWithADateColumn values( { d '1999−12−31' } )").sql. the millisecond values wrapped by a java.date is (according to the javadoc) : To conform with the definition of SQL DATE. // and cs. p.util.INTEGER).html We assume that the Connection is known as : Connection conn.prepareStatement ("select * from cust where purchase_date <?").". p. "string parameter").rgagnon. Types. sqlToday).util. 1). Types. java.Date().. cs.

getInt(3). "").getString(j)).setString(3.?.prepareCall ("{? = call mypackage.out. cs.registerOutParameter(5.setString(4.registerOutParameter(6. int j = 1. 0).CHAR). Guirado for the tips.sql. java.?. // get the result from OUTPUT #3 7.?.com/javadetails/.insertElementAt(rs. ResultSetMetaData rsmd = rs. j++){ vResSet.Types.p_astoreproc (?.next ()) { System. else { // To retrieve columns info.int output_parm3 = cs.println( "No resultSet!"). k++ ) { if ( vResSet. "").out. k < nbColonnes . public static int storedProcWithResultSet (String parms) throws Exception // Stored procedure to be called.addElement(rs. java.println( "return code of Stored procedure = : " 7.out. } } // Retrieving Strored Procedure OUTPUT parameters System.16 Stored procedure with Input/Output parms and a ResultSet .executeQuery().?. cs. j <= nbCol .Types. else System. parms).out. java.registerOutParameter(7. cs.elementAt(k) != null) System. vResSet. int nbCol = rsmd. // putting the ResultSet columns in a vector for ( j = 1. // Note that you need to retrieve the ResultSet _before_ retrieving // OUTPUT parameters. Vector vResSet = new Vector().. // regsiter ouput parameters cs.html Thanks to T.out.getColumnCount(). int i = 0.sql. CallableStatement cs = conn. if ( rs == null) System.println( vResSet. // register input parameters cs.CHAR).getString(j)./javadetails/java−0120.Types.sql. while (rs.16 Stored procedure with Input/Output parms and a ResultSet Current version of this HowTo : http://www. cs.?)}").rgagnon.toString()).getMetaData(). // Procedure execution ResultSet rs = cs.?. } // Reading vector to print ResultSet data for ( int k = 0 .setString(2.println( "Record " + (i+1)). } i++.println( "Column " + (k+1) + " Null").CHAR).elementAt(k).

next().last().getString(i)).18 Get a record count with a SQL Statement Current version of this HowTo : http://www.html Statement s = conn.CONCUR_READ_ONLY).html Some JDBC driver have limit about how big returned records can be. Statement s = conn. return cs..17 Fix incomplete field returned by the ResultSet Current version of this HowTo : http://www..TYPE_SCROLL_INSENSITIVE. 7. Then getMaxFieldSize() and setMaxFieldSize() from the Statement class to adjust if necessary the current maximum value. ResultSet r = s. NOTE : Your JDBC driver may not support this feature. r. i ++) System. ResultSet.println( "parameter " + i + " : " + cs.createStatement().getRow().close() . } 7. int count = r. .getInt(1)..createStatement( ResultSet.com/javadetails/. System.rgagnon.beforeFirst().17 Fix incomplete field returned by the ResultSet . int count = r.out.rgagnon. // Retrieving OUTPUT parameters for ( int i = 5 ./javadetails/java−0121.. First use the getMaxRowSize() and doesMaxRowSizeIncludeBlobs() from the DatabaseMetaData class to see what the maximum supported by the driver.executeQuery ("SELECT * FROM employee WHERE id_emp LIKE '1%'").com/javadetails/.0 provides a way to retrieve a rowcount from a ResultSet without having to scan through all the rows or issue a separate SELECT COUNT(*)./javadetails/java−0292.getInt(1)). i <= 7.").getInt("rowcount") . r.executeQuery("SELECT COUNT(*) AS rowcount FROM MyTable").println("MyTable has " + count + " row(s). r. JDBC 2.out. 7. r. ResultSet r = s.+ cs.

setModel(aModel).doit().out.connect("myDSN". rs2 = dmd. while(rs1.executeQuery("select col1. tblnames = "".com/javadetails/./javadetails/java−0309.i<colNo.null). } aTable. ResultSet rs2. public static void main (String args[]) { new JDBCapp().next()) tblnames += rs2.getColumnCount(). // Loop through the ResultSet and transfer in the Model java.URL.next()) { ss = rs1.*. 7.i++){ objects[i]=rs.net. } aModel..7.addRow(objects).sql. 7. "%".getString(4) + "\n\r".19 Transfer a ResultSet to a JTable . } public void doit() { theConn = new MyConnection().getTables(null.20 List tables in a database Current version of this HowTo : http://www.html import java.sql."col 3"}. while(rs.com/javadetails/. DefaultTableModel aModel = (DefaultTableModel) aTable.next()){ Object[] objects = new Object[colNo].dbConn. // the query ResultSet rs = statement.getSchemas()."col 2". // tanks to umit ozkan for the bug fix! for(int i=0.ResultSetMetaData rsmd = rs.html // TableModel definition String[] tableColumnsName = {"col 1". DatabaseMetaData dmd = theConn. try { ResultSet rs1. class JDBCapp { static MyConnection theConn. while(rs2.getMetaData().col3 from mytable"). rs1 = dmd. "password"). import java. int colNo = rsmd.19 Transfer a ResultSet to a JTable Current version of this HowTo : http://www..setColumnIdentifiers(tableColumnsName).getString(1). theConn.getObject(i+1).rgagnon.rgagnon. } System.col2.getMetaData()./javadetails/java−0317.println("Tables :"). aModel. "user".ss. String ss.getString(3) + " " + rs2.getModel().

println("<P ALIGN='center'><TABLE BORDER=1>"). void connect(String db. String passw) { try { Driver d = (Driver)Class. } } } class MyConnection { Connection dbConn = null.21 Display ResultSet data in an HTML Table in Servlet Current version of this HowTo : http://www. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 7.next()) { rowCount++. } catch (Exception e) { e.close().sql.ResultSet rs.printStackTrace(). } } void disconnect() { try { dbConn. consider making a small donation to show your support for this Web site and its content. } catch (Exception e) { e. java. passw).html private int dumpData(java.printStackTrace().21 Display ResultSet data in an HTML Table in Servlet .odbc. } } } If you find this article useful.newInstance().. // URL corresponding to the ODBC DSN String URL = "jdbc:odbc:" + db.getConnection(URL. i < columnCount. ResultSetMetaData rsmd = rs.out.rgagnon. out.com/javadetails/.printStackTrace(). // the data while (rs.println("<TH>" + rsmd. i++) { out. // DB logon dbConn = DriverManager. user.forName ("sun.println("</TR>").io./javadetails/java−0378.PrintWriter out) throws Exception { int rowCount = 0.println(tblnames). // table header out. String user. for (int i = 0.println("<TR>").getColumnLabel(i + 1) + "</TH>").getColumnCount(). } catch (Exception e) { e.System. } out.jdbc.getMetaData(). int columnCount = rsmd.JdbcOdbcDriver"). 7.

i++) { out. but encounters a warning condition.println("<TD>" + rs.out. w = w.out. you ask the Connection object if there are any warnings.out. System.getString(i + 1) + "</TD>")."username".getErrorCode ()). the warning messages are displayed.out. The subclass code then indicates the cause of the warning. Class Subclass 01 000 01 01 01 01 01 01 002 003 004 005 006 007 Success with warning Disconnect error−transaction rolled back Null value eliminated in set function String data.println (""). it sets the SQLSTATE class field to "01"..println ("\n *** SQL Warning ***\n").println("<TR>")./javadetails/java−0331.getNextWarning (). 7. SQLWarning w = dbConn. informations (not only Warnings) can be found in the SQLWarning object. while (w != null) { System.out.println ("SQLState: " + w.getSQLState ()).getMessage ()).html Warning When the database server executes an SQL statement successfully. Warnings are silently chained to the object whose method caused it to be reported". } out.println ("Message: " + w.println("</TABLE></P>").getWarnings(). // You may have multiple warnings chained together if (w != null) { System. So after DB operation. for (int i = 0. Depending on the vendor driver."password"). System.com/javadetails/.22 Detect SQL errors or warnings Current version of this HowTo : http://www.22 Detect SQL errors or warnings . return rowCount.println ("VendorCode: " + w. dbConn = DriverManager. } out. i < columnCount.out. This warning can be an ANSI or X/Open warning message (if supported by the driver) the subclass code in the range "000" to "006".println("</TR>"). Also the driver can provide is own warning codes in the "01" class.getConnection ("jdbc:odbc:YourDatabaseName". right truncation Insufficient item descriptor areas Privilege not revoked PRIVILEGE NOT GRANTED The JDK API doc reveals that "The SQLWarning class provides information on a database access warnings. // If a SQLWarning object was returned by the // Connection object. System. } 7.rgagnon.

Note that SQLException can be chained. while (ex != null) { System.23 Using DSN−less connection Current version of this HowTo : http://www. } catch (SQLException ignored) { //do nothing } } Check your DBMS manual for a full list of supported SQLState.out.out.. System. let me know!.lang.. System. The SQLException object contains : 1.out.com/javadetails/.println ("Vendor ErrorCode: " + ex. Thanks (works on some Windows installation while on other it does not!) 7. 7.out.} } } Error When an error occurs.. try { if (con != null) con. A "SQLState" string. You can interrogate the SQLException object to know more details about the actual error. A string describing the error.out.println ("*** SQLException caught ***"). available via the getMessage method. This is used as the Java Exception message. 2. if anyone know what is problem.println("").out. which follows the XOPEN SQLState conventions.getSQLState () + "").html This HowTo seems broken. An integer error code that is specific to each vendor.getErrorCode() + "").close().out.println("*** Exception caught ***"). ex = ex.rgagnon. some SQL operations } catch (SQLException ex) { // SQLException occured.println ("SQLState: " + ex. System. System.println ("Message: " + ex.23 Using DSN−less connection . } finally { // Close the database connection.getMessage() + "").getNextException().println(ex. a SQLException is thrown./javadetails/java−0345. } } catch (java. // There could be multiple error objects chained together System.getMessage()+ "").out.Exception ex) { // Some other type of exception occurred System. try { // . 3.

createStatement(). Connection con = null.jdbc.executeQuery ("select lastname. Thanks to R. Microsoft provides an ODBC driver to Excel worksheet. String myDB = "jdbc:odbc:Driver={Microsoft Excel Driver (*.odbc. SQLException{ Class.24 Read data from Excel worksheet Current version of this HowTo : http://www.*.net.io. id from [Sheet1$]").READONLY=false". DBConn = DriverManager."").xls. java.*. public static final String DATABASE_URL = "jdbc:odbc:employee_xls". public static void main(String[] args) throws ClassNotFoundException. // For Access Class.sql. ResultSet rs = stmt.xls)}.getConnection(myDB."".forName("sun.getConnection(myDB.24 Read data from Excel worksheet . DriverManager.jdbc.odbc.rgagnon.forName("sun.JdbcOdbcDriver"). Hibberd for the tip."". java. firstname. // For Excel Class.odbc. we can use the JDBC−ODBC bridge. Define an ODBC datasource (system DSN) named "employee_xls" that points to that worksheet. public class EmployeeReader{ public static final String DRIVER_NAME = "sun.. 7.MDB". try { con = DriverManager." + "DriverID=22.JdbcOdbcDriver").util. 7.forName(DRIVER_NAME).It is possible to connect to a database without a User or System DSN.jdbc.mdb)}. java. String myDB = "jdbc:odbc:Driver={Microsoft Access Driver (*.getConnection(DATABASE_URL). Not all JDBC driver support this feature.com/javadetails/.*.html Let's assume we have a worksheet like this LASTNAME Reiser Ricci Gugliuzza FIRSTNAME Beth Dylan Brian ID 102 111 116 To access this data.JdbcOdbcDriver". example 1 import import import import java.DBQ=C:/data/month./javadetails/java−0362.DBQ=c:/data/month. Statement stmt = con.""). This is useful if you don't have easy access to a client registry to define the required DSN.*.

odbc.print("Exception: ").getColumnCount().out. i <= numberOfColumns. i++) { if (i > 1) System.*.println ( "No of cols "+numberOfColumns while (rs.close().close(). ResultSetMetaData rsmd = rs. } rs. } catch(Exception ex) { System. System.println(fname + " " + lname + " } rs.getString(1).getInt(3). Connection con = DriverManager.println(ex. try{ Class.*.forName("sun.getMetaData(). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 7. example 2 import java.io. Statement st = con.next()) { String lname = rs. import java.out. stmt.sql.close(). System.JdbcOdbcDriver").close().err. public class EmployeeReader{ public static void main(String[] args){ Connection connection = null.24 Read data from Excel worksheet .print(".getMessage()). } finally { if (con != null) con. ResultSet rs = st.getString(2).close(). ). System.getString(i). String columnValue = rs.print(columnValue).next()) { for (int i = 1.while (rs.createStatement(). int numberOfColumns = rsmd. } } } id : " + id). String fname = rs.getConnection( "jdbc:odbc:employee_xls" ). st. } finally { con. System. } } } If you find this article useful.out. } System. int id = rs.out.println(""). ").out. consider making a small donation to show your support for this Web site and its content.jdbc.executeQuery( "Select * from [Sheet1$]" ).close().err.

w.html There are many solutions to read or write Excel spreadsheets from Java.http.IOException.rgagnon. javax.xls"). javax. jxl.servlet. jxl.ms−excel").OutputStream.27 JExcel Java Excel API is a java API enabling developers to read.addCell(new Label(0.setContentType("application/vnd.servlet.close(). IOException { OutputStream out = null.Workbook. HttpServletResponse response) throws ServletException. 0).HttpServletRequest.write.25 Handle Excel files Current version of this HowTo : http://www. jxl.. s. w./javadetails/java−0516. Example : output an Excel file from a Servlet import java.Label.HttpServlet.7. "Hello World")). 0.com/javadetails/.io.26 JDBC−ODBC Excel driver This solution lets you access your Excel worksheet with SQL SELECT statement. See this HowTo for an example. 7.WritableSheet. WritableSheet s = w.setHeader ("Content−Disposition". write.write. try { response. public class Sample extends HttpServlet { public void doGet (HttpServletRequest request.HttpServletResponse. Any operating system which can run a Java virtual machine can both process and deliver Excel spreadsheets. WritableWorkbook w = Workbook. This HowTo is only about OpenSource (and free) solutions.io. import java.servlet. "attachment. } 7. and modify Excel spreadsheets dynamically.http.createWorkbook(response.WritableWorkbook. One nice thing about JExcelApi is that it has no dependencies on any third party libraries. import import import import import import import import javax. jxl. e).servlet.25 Handle Excel files .http.createSheet("Demo".ServletException. filename=sampleName.write(). response. javax. 7. } catch (Exception e){ throw new ServletException("Exception in Excel Sample Servlet".getOutputStream()).write. The required ODBC driver is included in a regular Windows installation and the JDBC−ODBC bridge is used to access the Excel DSN.

Example : create an Excel file HSSFWorkbook wb = new HSSFWorkbook(). wb.write(fileOut).close(). FileOutputStream fileOut = new FileOutputStream("workbook. } } } See http://jexcelapi.28 POI The POI project consists of APIs for manipulating various file formats based upon Microsoft's OLE 2 Compound Document format using pure Java. HSSF is the POI Project's pure Java implementation of the Excel '97(−2002) file format and it provides a way to read spreadsheets create.age} ${employee.createCell((short)0).payment} ${employee.). POI is your Java Excel solution as well as your Java Word solution. See http://jakarta.etc.log4j. formulas etc using specific notation to indicate placement of data and then write a couple lines of code to invoke jXLS engine passing XLS template and the exported data as parameters.finally{ if (out != null) out.setCellValue("HelloWorld").createRow((short)0). Example : The XLS Template Employees Name ${employee.xls"). row. all you need is to create XLS template file with all required formatting. read and write XLS spreadsheets.net/ 7.. HSSFRow row = sheet. The name was originally an acronym for "Poor Obfuscation Implementation" (ref: Wikipedia). POI has a dependencies with other JARs (commons.payment@)] with the code 7.apache.bonus} $[SUM(@employee. modify. With jXLS.org/poi/ 7. HSSFSheet sheet = wb.29 JXLS jXLS is a project that allows creation of extremely complex Excel reports just in several lines of code. fileOut.close()..createSheet("new sheet").sourceforge.28 POI .name} Age Payment Bonus ${employee. Since it's Jakarta project. It is based on Jakarta POI.

The documentation is minimal at this time. XLSTransformer transformer = new XLSTransformer(). Map beans = new HashMap().no_ji. See http://xlsql.println("UserName="+excel. // if already started.Version()). 0. Example : import import import import jp. destFileName). 35.println("Caption="+excel.out. System.ne. java. // display any information System.out. Documents can be read and written with SQL as if they were tables in a database. class TestExcel { public static void main(String[] args) throws Exception { ReleaseManager rm = new ReleaseManager(). 28.transformXLS(templateFileName.io.31 JCOM JCOM is a Java to COM bridge library. staff.15)).00% 1500 15.30 xlSQL xlSQL is a JDBC Driver for Excel and CSV data sources.. ExcelWorkbook xlBook = xlBooks.ne.add(new Employee("Derek".30 xlSQL .File. beans. java. beans.Visible(true). open new window ExcelApplication excel = new ExcelApplication(rm).println("EXCEL startup. 0.Workbooks().no_ji.println("Version="+excel.out.add(new Employee("Elsa".excel8. try { System.UserName()).Add().. staff).30)). // create new book 7.out.put("employee".so_net. jp.println("Value="+excel.Date. System.jcom.").net/ 7.*. staff.util.*. System.ga2. The documentation is minimal (in Japanese!). You can export XLS to XML or SQL INSERT statements.out.so_net.Collection staff = new HashSet().00% 4500 See http://jxls.sourceforge. With JCOM you can call a COM object from Java as if it were a Java object without having to deal with the internals of JNI.Value()).net/ 7.Caption()).ga2. gives the result Employees Name Age Derek 35 Else 28 Payment Bonus 3000 30. 1500.sourceforge. ExcelWorkbooks xlBooks = excel. 3000. transformer. xlSQL includes its own "zero−admin" mySQL database.jcom. excel.

Item(1).i+2).i+2). // output default printer.Item(4. xlBook. if book save to file. excel.length+2). // xlSheet.filenames.isFile()?"Yes":"No" ). xlBook.i+2).length+1)+")". save to(My Documents) System.1).Value( file.println ("save to file.Item(2.xls").Item(2.out.println("print out.. } catch(Exception e) { e.1). } String expression = "=Sum(B2:B"+(filenames.println(file). xlRange."). 7.Item(2.").out. if no path..Quit().Value( file.lastModified()) ). xlRange.1). i++) { File file = new File(filenames[i]). } finally { rm.Value("can write"). calculate sum of filesize: "+expression).release().filenames.Value("sum").Value("is directory").i+2). xlRange.1). System.Value("can read").Columns().Value( new Date(file.Item(5. xlRange. xlRange.Item(1.Item(3.out.Item(1.printStackTrace(). if print out.Item(1.isDirectory()?"Yes":"No" ).Close(false.Value("last modified time").AutoFit()..Worksheets(). ExcelWorksheets xlSheets = xlBook. xlRange. xlRange.length+2). System.xls"). xlRange. xlRange.30 xlSQL . for(int i=0... xlRange..list(). xlRange.1).canWrite()?"Yes":"No" ).SaveAs("testExcel.1).length() ).Value("filename" ). } } } See http://sourceforge. // System.out.getName() ). File path = new File(".println("thank you .Value("is file"). // fit columns // comment out.net/projects/jcom See also this HowTo for an alternative package to access a COM package from Java.false)."). xlRange.Value( file.println ("embed equation.i+2). ExcelRange xlRange = xlSheet. String[] filenames = path.canRead()?"Yes":"No" ).// enumurate all files System.Formula(expression). xlRange. xlRange.Item(3.Item(6.null.i+2). xlRange.println ("set infomation of files in current directory to cell . i<filenames. System. // // // // // comment out.1).out.i+2).Value("size" ). xlRange.Item(5.Value( (int)file.Item(4. ExcelWorksheet xlSheet = xlSheets.Cells(). (My Documents)\\testExcel.Item(7.Item(6.PrintOut().Value( file.Value( file.out. xlRange.Item(7./").length.

setX(100 + ix).setName("giffy"). // add to sheet ImageHandle giffy = new ImageHandle(fin.out.png"). WorkBookHandle tbo = new WorkBookHandle(workingdir + finpath).gif"). See http://www."Sheet1"). // get gif image input stream FileInputStream fin = new FileInputStream (workingdir + "testImages.getName()+". void doit(String finpath. and a png". 7. sheet.gif.close().setName("heart" + x).com/estore/product_detail. FileOutputStream outimg = new FileOutputStream (workingdir + extracted[t]. create a new workbook with them) : doit("testImages. // set the random x/y coords of picture int ix = Math. outimg. sheet)..flush(). // extract and output images for(int t=0. sheet). . a jpg.x<100.xls". .write(outimg). jpgy.7. // read images from sheet 1 −− .println("Successfully extracted: " + workingdir + "testImageOut_" + extracted[t].getType()).getWorkSheet(sheetname).setBounds(100.t<extracted. outimg.jpg ImageHandle[] extracted = sheet.add ("New workbook with 3 images: a gif.round((float)((x * (Math.png.insertImage(giffy). .32 OpenXLS Java Spreadsheet SDK . giffy.getWorkSheet("Sheet1"). jpgy.out. ImageHandle jpgy = new ImageHandle(fin. 400.." +extracted[t]. String sheetname){ System. "A1").x++) { fin = new FileInputStream(workingdir + "testImages.t++) { System.getImages().random()*10)))). try{ sheet = tbo. extracted[t]. 200).getName()+". // set picture size and location in sheet giffy. } tbo = new WorkBookHandle().extentech." +extracted[t].getType()).println("Begin parsing: " + workingdir + finpath). sheet = tbo. This open source effort is the result of over 6 years of development into it. 100. // add to sheet for(int x=0.length.32 OpenXLS Java Spreadsheet SDK OpenXLS claims that it has the best compatibility with complex Excel files and able to handle any kind of Excel file out there without corrupting it.jsp?product_group_id=228 Example (extract 3 images from a workbook. CellHandle a1 = sheet.

err.random()*10)))). prop..setY(100 + ix). bbout.util. username). } catch (java. 7.ix = Math. workingdir + "testImagesOut.put("user". jpgy.File(fout). prop.getConnection(url.println("IOException in Tester.forName(sun.put("charSet".JdbcOdbcDriver) .println("Successfully read: " + newbook). // for example.odbc. FileOutputStream fos = new FileOutputStream(f).insertImage(jpgy).0). bbout.toString()).com/javadetails/. WorkBookHandle newbook = new WorkBookHandle (workingdir + "testImagesOut.io. pngy.write(b.println("testImages failed: " + e. } // get png image input stream fin = new FileInputStream(workingdir + "testImages.out.insertImage(pngy)./javadetails/java−0371. fos. "iso−8859−7").33 Specify a CharSet when connecting to a DBMS Current version of this HowTo : http://www.xls".util...xls").jdbc. prop.Properties(). // setup the properties java.flush(). } catch(Exception e){ System. } public void testWrite(WorkBookHandle b.IOException e){ System.round((float)((x * (Math.getBytes()). sheet). sheet. } } See also this HowTo for a way to create a simple XLS without any additional library. // set just the x/y coords of picture pngy. String fout){ try{ java. sheet.Properties prop = new java.io. "+e).io. // Connect to the database con = DriverManager.err. } testWrite(tbo. 7. prop). System.File f = new java.html Class.close(). password).rgagnon.33 Specify a CharSet when connecting to a DBMS . // add to sheet ImageHandle pngy = new ImageHandle(fin.jpg"). BufferedOutputStream bbout = new BufferedOutputStream(fos).setX(10).put("password".setY(200).

out.getString(3) "\n " + rs. import java. while (rs. ResultSet rs = stmt. import java. " + {t '10:30:29' }. class JDBCapp { static MyConnection theConn. 7.2] Take the following program.net.executeQuery(sql)..rgagnon.34 Get current date using JDBC . } public void doit() { theConn = new MyConnection().sql.35 Enable JDBC logging Current version of this HowTo : http://www.getString(2) "\n " + rs.URL.com/javadetails/. you add the from dual SELECT {fn curdate() } FROM dual SELECT {fn curtime() } FROM dual SELECT {fn now() } FROM dual for current date for current hour for current date and hour Example : // for Oracle String sql = "select {fn " " " " dayname ({fn now()})}.next()) System.7.*.getString(4) " + rs. 7. JDBC function escape sequence can be used : SELECT {fn curdate() } SELECT {fn curtime() } SELECT {fn now() } for current date for current hour for current date and hour for Oracle.com/javadetails/.html [JDK1.34 Get current date using JDBC Current version of this HowTo : http://www.rgagnon.html With most DBMS.println("results: "\n " + rs. " + {ts '1997−05−24 10:30:29." + {d '1997−05−24'}./javadetails/java−0411..getString(1) + + + )./javadetails/java−0383.doit().123'}" + from dual" . public static void main (String args[]) { new JDBCapp().

szSqlStr=SELECT emp_id FROM employee Number of parameter markers (SQLNumParams).close(). hStmt=184290392 value=1 *PreparedStatement.JdbcOdbcPreparedStatement@19ee1ac *Connection.forName("sun. prepstmt.jdbc. } catch (Exception e) { e. DriverManager. "dba".io. fOption=0 Executing (SQLExecute). PreparedStatement prepstmt.execute Free statement (SQLFreeStmt).jdbc. dbConn = DriverManager. String user.setLogWriter(w).34 Get current date using JDBC .printStackTrace().PrintWriter w = new java.out)).odbc.JdbcOdbcDriver").disconnect().execute(). prepstmt.odbc.prepareStatement ("SELECT emp_id FROM employee" ). java.printStackTrace(). user. } catch (Exception e) { e. hStmt=184290392. } } class MyConnection { Connection dbConn = null. hDbc=185334988 hStmt=184290392 Setting statement option (SQLSetStmtOption).getConnection(URL.io.PrintWriter (new java. passw). void connect(String db. Preparing (SQLPrepare). } catch (Exception e) { e. } } void disconnect() { try { dbConn.prepareStatement (SELECT emp_id FROM employee) Allocating Statement Handle (SQLAllocStmt).newInstance().theConn.close(). try { prepstmt = theConn.connect("EAS Demo DB V3". hStmt=184290392.dbConn.close Free statement (SQLFreeStmt).JdbcOdbcPreparedStatement@19ee1ac *PreparedStatement. hStmt=184290392. hStmt=184290392 Number of result columns (SQLNumResultCols). hStmt=184290392. hStmt=184290392 value=0 Registering Statement sun. "sql").close 7.OutputStreamWriter(System.printStackTrace(). } theConn. } } } And the output at the console will look like this : *Connection. Setting statement option (SQLSetStmtOption). fOption=1 deregistering Statement sun.io. String URL = "jdbc:odbc:" + db.jdbc. String passw) { try { Driver d = (Driver)Class.odbc.

transform.xml. javax.sql.next()) { // Table exists } else { // Table does not exist } If you find this article useful. java.getMetaData(). null..ResultSet. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 7.*. java. hDbc=185334988 Closing environment (SQLFreeEnv).parsers. javax.w3c.html import import import import import import import import import import import import import java.sql.sql.sql.w3c.Element.Statement. hEnv=185334828 7. if (rs.xml.transform.transform. try { 7.. // check if "employee" table is there ResultSet tables = dbm.36 Detect if a table exists Current version of this HowTo : http://www.*.dom.37 Convert a ResultSet to XML Current version of this HowTo : http://www.stream.xml.*.36 Detect if a table exists . hDbc=185334988 Closing connection (SQLFreeConnect). java.DocumentBuilder. org. String sql. public static void main (String args[]) { ResultSet rs = null./javadetails/java−0511.parsers. javax.com/javadetails/.html Connection c = . javax. DatabaseMetaData dbm = c. java.sql.0 Statement(s) to close Disconnecting (SQLDisconnect). Statement stmt = null. org.Driver.dom. consider making a small donation to show your support for this Web site and its content.Document.. "employee".Connection..sql./javadetails/java−0485.rgagnon.getTables(null.DocumentBuilderFactory. java.xml. javax.com/javadetails/.xml. { class JDBCapp static Connection con.dom.rgagnon.ResultSetMetaData.DriverManager. null).

close().newDocument().ENCODING.METHOD. while (rs.appendChild(doc.println(getDocumentAsXml(doc)). if (stmt != null) stmt.transform(domSource. transformer. DocumentBuilder builder =factory.io. rs = stmt.setOutputProperty(OutputKeys. int colCount = rsmd. Object value = rs.io.createElement("Results")."ISO−8859−1").createElement("Row").close(). 7. ii++) { String columnName = rsmd. "xml").setOutputProperty ("{http://xml. StreamResult sr = new StreamResult(sw). ResultSetMetaData rsmd = rs. TransformerException { DOMSource domSource = new DOMSource(doc). if (rs != null) rs.next()) { Element row = doc.createStatement(). Element node = doc.getColumnCount().toString())). } catch (Exception e) { e. } catch (Exception e) { } } } public static String getDocumentAsXml(Document doc) throws TransformerConfigurationException.getObject(ii). Transformer transformer = tf.getColumnName(ii). // we want to pretty format the XML output // note : this is broken in jdk1. "4").printStackTrace(). for (int ii = 1.org/xslt}indent−amount".appendChild(row).createTextNode(value.createElement(columnName).getMetaData(). // java. TransformerFactory tf = TransformerFactory.newInstance().StringWriter sw = new java. stmt = con.appendChild(results).OMIT_XML_DECLARATION. transformer.5 beta! transformer.apache.36 Detect if a table exists .setOutputProperty(OutputKeys. sr). transformer.appendChild(node).newDocumentBuilder(). row. } } System. ii <= colCount. results. doc. transformer.out.newTransformer().DocumentBuilderFactory factory = DocumentBuilderFactory. "yes"). Document doc = builder."yes").INDENT.StringWriter().setOutputProperty(OutputKeys. node. sql = "select objet from Email".newInstance().setOutputProperty(OutputKeys. Element results = doc.close(). // connection to an ACCESS MDB con = AccessCon.getConnection(). //transformer. } finally { try { if (con != null) con.executeQuery(sql).

"user". The escape sequence must be at the end of the SQL statement.return sw. Find all rows in which a begins with the character "%" st = con.rgagnon. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 7.createStatement().executeQuery ("SELECT value FROM vendors WHERE value LIKE '$%%' {escape '$'}").getConnection(URL.mdb"). Connection c = DriverManager.createStatement(). 7.toString(). rs = st. */ } } If you find this article useful.38 Escape special character in a LIKE clause Current version of this HowTo : http://www.DBQ=c:/tech97. Connection c = DriverManager.html Your JDBC driver may support the {escape 'escape character'} syntax for using LIKE clause wildcards as literals.executeQuery ("SELECT value FROM vendors WHERE value LIKE '%=_' {escape '='}").mdb)}. consider making a small donation to show your support for this Web site and its content. rs = st.jdbc.forName ("sun. Find all rows in which a ends with the character "_" st = con. "pwd")./javadetails/java−0554. rs = st.. Searching for strings ending with "one%word" st = con.getConnection ("jdbc:odbc:Driver={Microsoft Access Driver (*. /* To use an already defined ODBC Datasource : String URL = "jdbc:odbc:myDSN".com/javadetails/.odbc.executeQuery ("SELECT value FROM vendors WHERE value LIKE 'one/_word' {escape '/'}"). Searching for "one_word" st = con.createStatement(). } } class AccessCon { public static Connection getConnection() throws Exception { Driver d = (Driver)Class.newInstance().38 Escape special character in a LIKE clause .executeQuery ("SELECT value FROM vendors WHERE value LIKE '%one/%word' {escape '/'} "). return c.JdbcOdbcDriver"). rs = st.createStatement().

com/javadetails/..rgagnon../javadetails/java−0602. Download at http://p6spy.html 7.com/javadetails/." "'" + custPhone + "'" + "./javadetails/java−0567. 7.If you don't want to use JDBC escape sequence then it's possible to use native SQL based on the target DBMS. it will look like this : SELECT value FROM vendors WHERE value LIKE '%=_%' ESCAPE '='.html It's good idea to use the JDBC escape function instead of using a specific DBMS function. The log file format is current time|execution time|category|statement SQL String|effective SQL string P6Spy is especially useful with an application server. 7.com/ 7. ref : Labo−Oracle. 7. sql = + + + "INSERT INTO CUSTOMERS VALUES(" "'" + custName + "'" + ".rgagnon. your code will be portable.com.41 Plain JDBC Logging See this HowTo.39 Insert the current date Current version of this HowTo : http://www. This way. For Oracle.39 Insert the current date .40 Log the SQL Statements Current version of this HowTo : http://www.42 P6Spy P6Spy is an open source framework for applications that intercept and optionally modify database statements." " {fn now() } )".

43 Proxool .com 7.7.rgagnon. Download at http://proxool.com http://www. It provides really nice logging facilities with the SQL statement and the running time.net/ Written and compiled Réal Gagnon ©2007 real@rgagnon.43 Proxool Proxool is a Java connection pool.sourceforge.

2 Use native code through JNI Current version of this HowTo : http://www./javadetails/java−0283. } } • Compile and execute. • Copy the javahowto. static { System. • In the same directory create a java source called JavaHowTo.dll in the same directory as the java program.sayHello()).cpp source. javah −jni JavaHowTo • In MSVC6.println(jht. System.rgagnon. jobject obj) { 8 JNI .1 java−jni 8.out. add the JavaHowTo.3 Pass a string to/from Java to/from C Current version of this HowTo : http://www. create a new Win32 DLL project (simple) and call it javahowto.html • With MSVC6.rgagnon..java class JavaHowTo { public native String sayHello()..h in your project header files • In the Tools − Options menu.h" JNIEXPORT jstring JNICALL Java_JavaHowTo_sayHello (JNIEnv *env. jobject obj) { return env−>NewStringUTF("Hello world").html To Java from C (as seen from the previous How−to) : #include "JavaHowTo.8 JNI 8. } } • Compile the Java program and use javah utility to generate the JavaHowTo./javadetails/java−0284.com/javadetails/. set the include directories to include the Java JNI headers files. • Create this new java program public class JNIJavaHowTo { public static void main(String[] args) { JavaHowTo jht = new JavaHowTo(). 8. add #include "JavaHowTo.h header file.com/javadetails/. } • Select the Release configuration and build the project. They are located in [jdk dir]\include and [jdk dir]\include\win32 directories • In the javahowto.h" JNIEXPORT jstring JNICALL Java_JavaHowTo_sayHello (JNIEnv *env.loadLibrary("javahowto").

// and the sayHello() method jmethodID methodID = env−>GetMethodID (myclass_class. "sayHello".sayHello(). // convert the Java String to use it in C str = env−>GetStringUTFChars(s. we want to call the Java sayHello() method which returns a String : JNIEXPORT void JNICALL Java_JavaHowTo_sayHello (JNIEnv *env. str). 0). From Java to C : Suppose we have a Java Class public class MyClass { public String sayHello(){ return "Hello world From Java". jht. "()V"). } } And finally. to use it public class JNIJavaHowTo { public static void main(String[] args) { JavaHowTo jht = new JavaHowTo().return } env−>NewStringUTF("Hello world"). env−>ReleaseStringUTFChars(s."). } } 8 JNI . methodID). } The Java JNI wrapper would be class JavaHowTo { public native void sayHello(). // call the sayHello() method jstring s = (jstring) env−>CallObjectMethod (myclass_object. str). "()Ljava/lang/String. jclass myclass_class =(jclass) env−>NewGlobalRef (env−>FindClass ("MyClass")). constructorID). // we need the MyClass constructor jmethodID constructorID = env−>GetMethodID (myclass_class. "". } } then from C. static { System. printf("%s" . // instanciate a MyClass object jobject myclass_object = env−>NewObject (myclass_class. jobject obj) { const char *str.loadLibrary("javahowto").

8.4 Set the computer clock . jshort hour. st. GetLocalTime( st. } } And finally. we need its signature. short minutes). SetLocalTime( } The Java JNI wrapper would be class JavaHowTo { public native void setSystemTime( short hour. } } 8.html Before calling a Java object's method from JNI.loadLibrary("javahowto").wMinute = minutes. static { System.com/javadetails/. jshort. the method long myMethod (int n.html Define the following prototype in the header file JNIEXPORT void JNICALL Java_JavaHowTo_setSystemTime (JNIEnv *./javadetails/java−0286. String s. jobject obj. int[] arr). minutes). // this example will set the system at 10h21 using the Windows API // SetLocalTime.4 Set the computer clock Current version of this HowTo : http://www..setSystemTime(hour.rgagnon.rgagnon.8.com/javadetails/. to use it public class JNIJavaHowTo { public static void main(String[] args) { short hour = 10. jshort minutes) { SYSTEMTIME st.wHour = hour. short minutes = 21. For example. JavaHowTo jht = new JavaHowTo().5 Determine the signature of a method Current version of this HowTo : http://www. the JNI function JNIEXPORT void JNICALL Java_JavaHowTo_setSystemTime (JNIEnv *env.. // set the time at 10h21 jht. jobject. jshort)./javadetails/java−0285.

Label Compiled from Label. /* ()V */ public java.Label(java. /* ()Ljava/lang/String.lang.int). /* Ljava/lang/String. The second portion follows the closing parenthesis and represents the return type. */ public int getAlignment(). /* (Ljava/lang/String. /* ()Ljava/lang/String. */ int alignment.awt.lang.)V */ public java. the "L" is followed by the object's class name and ends with a semi−colon.awt. The javap utility (included with the JDK) is very useful to show the signature to be used in JNI. /* (Ljava/lang/String.Label extends java.4 Set the computer clock .java public class java.awt. '. /* (Ljava/lang/String. The first part is enclosed within the parentheses and represents the method's arguments. /* ()Ljava/lang/String. /* I */ java.lang.is seen from JNI with the signature (ILJAVA/LANG/STRING.String text. /* ()V */ java.awt. /* I */ public static final int CENTER.lang. /* ()I */ public java.lang.)V */ 8.String).String.Component { public static final int LEFT.[I)J There are two parts to the signature. /* I */ static {}. */ protected java.String).String getText().I)V */ public void addNotify().Label().Label(java. /* (I)V */ public void setText(java.awt.String constructComponentName(). /* ()V */ public java. The mapping between the Java type and C type is Type boolean byte char double float int long object short void array Chararacter Z B C D F I J L S V [ Note that to specify an object.awt.String paramString(). */ public synchronized void setAlignment(int). X:\>javap −s java.lang.' . /* I */ public static final int RIGHT.lang.

6 Use arrays . 9. 0). return max. "[I"). JNIEXPORT jint JNICALL Java_JavaHowTo_max (JNIEnv * env. 0. } } This following how−to is currently broken.rgagnon. } The Java wrapper class JavaHowTo { public static native int max(int [] t). i=1.. int i. jclass cls = env−>GetObjectClass(obj).* or your own classes.The javap utility can be used on the java.. 7. jsize len = env−>GetArrayLength(arr. JNIEXPORT jint JNICALL Java_JavaHowTo_printArray (JNIEnv * env. Without passing the array directly to the JNI function. jint *body = env−>GetIntArrayElements(arr.html JNI provides special functions (relative to the type) to access Java arrays. for (max = body[0]. System. fid = env−>GetFieldID(cls. static { System. it's possible to fetch directly from the class the array.out.com/javadetails/. 1}. env−>ReleaseIntArrayElements(arr. tab = env−>GetIntArrayElements(jtab. 8. jobject jtab. if (fid == 0) return. 2..6 Use arrays Current version of this HowTo : http://www. body.println(JavaHowTo. 5. jclass obj. len = env−>GetArrayLength(jtab).max(myArray)). jsize len. 0)./javadetails/java−0287. } } The test program class JNIJavaHowTo { public static void main(String[] args) { int [] myArray = {4. 8. jintArray arr) { int i. i <len. jtab = env−>GetObjectField(obj. 0).loadLibrary("javahowto"). max = −1. i++) if (max <body[i]) max = body[i]. fid). This example returns the maximum of an int array. "myArray". jclass obj) { jfieldID fid.

9 Throw an Exception (from JNI code) Current version of this HowTo : http://www. 8.printf("int [] : [").html [pre JDK1.library. jobject.html Define the following prototype in the header file JNIEXPORT jdouble JNICALL Java_JavaHowTo_divide (JNIEnv *.load("d:/directoryX/subDirY/MyDll.4) may provide this functionality but for now.com/javadetails/.rgagnon.2 (or better).2] System.8 Use the MouseWheel Current version of this HowTo : http://www.. if the DLL is in the CLASSPATH then you don't need to specify a PATH. Do something like this instead.com/javadetails/. the JNI function JNIEXPORT jdouble JNICALL Java_JavaHowTo_divide 8.7 Load a DLL .rgagnon..path=c:/temp JNIJavaHowTo 8. or specify through the JVM command line the location where to find the JNI DLL to be loaded java −Djava. jdouble). tab[i]). If the DLL is not in the CLASSPATH then you need to specify the PATH. See this link http://www.rgagnon. } ".asp ./javadetails/java−0314.html Current JDK don't support scrolling via the MouseWheel./javadetails/java−0318.dll") In JDK1. 8.7 Load a DLL Current version of this HowTo : http://www.loadLibrary("d:\\directoryX\\subDirY\\MyDll.com/javadetails/. for (i = 0. jdouble.getRuntime()./javadetails/java−0323. i <len .dll").com/java/mousewheel.. Runtime.codeproject. i++) printf("%d printf("]\n"). Next version (JDK1. you need some JNI functions.

System. env−>ThrowNew(MyOwnException."Can't divide by zero.0. } } And finally.divide(9. 0. double d2).println("division 2 : " + jht.println("division 1 : " + jht.10 Throw my own Exception (from JNI code) .divide(9./javadetails/java−0322. 3.html The MyOwnException class public class MyOwnException extends Exception { public MyOwnException(){} public MyOwnException(String txt) { super(txt). static { System.com/javadetails/.0. } } 8. } return d1/d2.(JNIEnv *env. to use it public class JNIJavaHowTo { public static void main(String[] args) { JavaHowTo jht = new JavaHowTo(). } The Java JNI wrapper would be class JavaHowTo { 8. jobject obj. jobject obj) { jclass MyOwnException = env−>FindClass("MyOwnException"). jobject)."). env−>ThrowNew(Exception..0)). jdouble d2) { if (d2 == 0.rgagnon.out. System. } } the prototype in the header file JNIEXPORT void JNICALL Java_JavaHowTo_triggerException (JNIEnv *.").out."Exception triggered from JNI routine.loadLibrary("javahowto").0) { jclass Exception = env−>FindClass("java/lang/Exception").0)).10 Throw my own Exception (from JNI code) Current version of this HowTo : http://www. jdouble d1. } The Java JNI wrapper would be class JavaHowTo { public native double divide(double d1. the JNI function JNIEXPORT void JNICALL Java_JavaHowTo_triggerException (JNIEnv *env.

.rgagnon.html First you need the handle of the Window.11 JNI from a package Current version of this HowTo : http://www. static { System. jclass obj. JNIEXPORT jint JNICALL Java_JavaHowTo_getHwnd (JNIEnv *env. to use it public class JNIJavaHowTo { public static void main(String[] args) { JavaHowTo jht = new JavaHowTo(). If you have a Java native method in a class called MyClass like this: public native void myMethod().rgagnon). jht. jobject).rgagnon.11 JNI from a package .loadLibrary("javahowto").public native void triggerException().triggerException(). When you put the class into a package (say com.html JNI requires that the function names follow a specific format. To generated the proper header. } } And finally./javadetails/java−0353. compile the JNI class in the package then.com/javadetails/. you need to include the package information in the native function name like this: JNIEXPORT void JNICALL Java_com_rgagnon_MyClass_myMethod(JNIEnv *../javadetails/java−0348.MyClass If you find this article useful. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 8. the native function must look like this: JNIEXPORT void JNICALL Java_MyClass_myMethod(JNIEnv *. consider making a small donation to show your support for this Web site and its content.com/javadetails/. using the javah utility (from the root of the package) : javah com.12 Make a Window "stay on top" Current version of this HowTo : http://www. } } 8. jstring title){ 8. Call this JNI function with Window Title. jobject).rgagnon.

exit(1). title. } jclass cls = env−>FindClass("HelloWorld").version = JNI_VERSION_1_2. env−>FindClass("java/lang/String"). JNIEnv *env. title.ignoreUnrecognized = 1. vm_args. jint res = JNI_CreateJavaVM((void **) if (res < 0) { printf("Can't create Java VM\n").0.com/javadetails/.0. } jstring argString = env−>NewStringUTF(""). "([Ljava/lang/String. options[0].0.optionString = "−Djava. } jmethodID mid = env−>GetStaticMethodID(cls. vm_args.class.nOptions = 1.SWP_NOMOVE|SWP_NOSIZE). exit(1). jstring jstr. (*env)−>ReleaseStringUTFChars(env.h> int main() { JavaVM *vm.0. // in c:/myclasses if (cls == 0) { printf("HelloWorld class not found\n").)V").path=c:/myclasses".13 Start a JVM from C . "main".0. exit(1). vm_args.13 Start a JVM from C Current version of this HowTo : http://www. 0).rgagnon. if (mid == 0) { printf("main() method not found\n").0. else SetWindowPos((HWND) hwnd.0. const char *str = NULL.HWND hwnd = NULL.h> #include <stdio.html #include <jni. jboolean flag){ if (flag) SetWindowPos((HWND) hwnd. str). jclass obj. JavaVMInitArgs vm_args. vm_args. JavaVMOption options[1]. return./javadetails/java−0354. jobjectArray args.str). 8. //empty arg list jobjectArray args = env−>NewObjectArray(1. return (jint) hwnd.HWND_NOTOPMOST.SWP_NOMOVE|SWP_NOSIZE). } Then you pass the handle to this function JNIEXPORT void JNICALL Java_JavaHowTo_setWindowAlwaysOnTop (JNIEnv *env. str = (*env)−>GetStringUTFChars(env..0. jstr). hwnd = FindWindow(NULL. } 8. jint hwnd.HWND_TOPMOST.options = options.

com/javadetails/. jname. args).if (args == 0) { printf("Out of memory\n")./javadetails/java−0460. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 8. jname. } 8. 8. } env−>CallStaticVoidMethod(cls.loadLibrary("jni2").15 Get the PID Current version of this HowTo : http://www. } const char *name = (*env)−>GetStringUTFChars(env.14 Retrieve environment variable (JNI) . const char *value = getenv(name) . } } public class JNIJavaHowTo { public static void main(String[] args) { JavaHowTo jht = new JavaHowTo().html For some odd reasons. If you find this article useful. the getenv() method was removed from the JDK. But for now. return 0. return value ? (*env)−>NewStringUTF(env.14 Retrieve environment variable (JNI) Current version of this HowTo : http://www. See also this HowTo. } NOTE : This is fine if the environment variable contains only regular 7−bit ASCII characters.com/javadetails/.html class JavaHowTo { public native long getCurrentProcessId().. exit(1). jstring jname){ if ( jname == NULL ) { return NULL .rgagnon.. (jboolean *)NULL) . consider making a small donation to show your support for this Web site and its content. (*env)−>ReleaseStringUTFChars(env.rgagnon. jclass c./javadetails/java−0467. value) : NULL . static { System. name) . Rumors is that a mechanism to retrieve an environment will be back in JDK1. you can use −D switch to retrieve named environment variable and pass them to the JVM (see this HowTo) or use this JNI routine : JNIEXPORT jstring JNICALL JavaHowTo_getenv (JNIEnv *env.5 (see this HowTo). mid.

h" BOOL APIENTRY DllMain( HANDLE hModule.16 Clear the console..InputStreamReader(System.println("Press Any key. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 8..in)).cpp : Defines the entry point for the DLL application.} System.html [Windows only] First you need this Java stub (JavaHowTo."). FOREGROUND_INTENSITY = 0x8. jobject) { // return GetCurrentProcessId(). If you find this article useful.io.com/javadetails/. public static final short BACKGROUND_BLUE = 0x10.BufferedReader(new java.java) to provide an interface to the JNI DLL (jni3.System.io.out.16 Clear the console.getCurrentProcessId()). 8. java.} catch (Exception e) { e. DWORD ul_reason_for_call..readLine(). FOREGROUND_WHITE = 0x7. LPVOID lpReserved ) { return TRUE. } You can download the whole thing here. set color and cursor position (JNI) .h" #include <process.println(jht. set color and cursor position (JNI) Current version of this HowTo : http://www.out. consider making a small donation to show your support for this Web site and its content. FOREGROUND_RED = 0x4. // #include "stdafx. class JavaHowTo { public public public public public public static static static static static static final final final final final final short short short short short short FOREGROUND_BLACK = 0x0./javadetails/java−0469. } } // jni2. return getpid().h> #include "JavaHowTo. FOREGROUND_BLUE = 0x1. } JNIEXPORT jlong JNICALL Java_JavaHowTo_getCurrentProcessId (JNIEnv *. try { input.BufferedReader input = new java. public static final short BACKGROUND_GREEN = 0x20.rgagnon.printStackTrace().io.dll). FOREGROUND_GREEN = 0x2.

Y = 0. // #include "stdafx.X * strConsoleInfo.X. strConsoleInfo. // and so on. CONSOLE_SCREEN_BUFFER_INFO strConsoleInfo. BOOL APIENTRY DllMain( HANDLE hModule. jobject obj. Don't forget to include the folders %JAVAHOME%\include and %JAVAHOME%\include\win32 to have access to the JNI header files. GetConsoleScreenBufferInfo(hConsole. short y). EMPTY.cpp : Defines the entry point for the DLL application. hConsole = GetStdHandle(STD_OUTPUT_HANDLE). Home). I'm using VisualStudio v6. } JNIEXPORT void JNICALL Java_JavaHowTo_cls (JNIEnv *env.X = 0. Home. Home. public native void restoreColors(). public native void setColor( short foreground. DWORD ul_reason_for_call. } } Compile and generate an header with javah JavaHowto. static { System. COORD Home. Next we built a DLL. LPVOID lpReserved ) { return TRUE..loadLibrary("jni3"). // jni3.. the result is a file called JavaHowTo.dwSize. set color and cursor position (JNI) .dwSize.public static final short BACKGROUND_RED = 0x40. public native void keepColors(). public static final short BACKGROUND_INTENSITY = 0x80. short background). jshort y) { 8. unsigned long * hWrittenChars = 0.h> #include "JavaHowTo.h.h" int originalColors.16 Clear the console. // system("cls").the definition for the other colors is // left as an exercise :−) public native void cls(). FillConsoleOutputCharacter(hConsole. jobject obj) { HANDLE hConsole. static unsigned char EMPTY = 32. jshort x. will do the same as the above! } JNIEXPORT void JNICALL Java_JavaHowTo_setCursorPosition (JNIEnv *env. Home. public native void setCursorPosition( short x. SetConsoleCursorPosition(hConsole. hWrittenChars).h" #include <stdlib.

HANDLE hConsole.16 Clear the console.setColor(jht.(short)15). originalColors).X = x.dll. the result is jni3.(short)10). coordScreen ). coordScreen. Here an example how to use the DLL.BACKGROUND_BLUE). hConsole = GetStdHandle(STD_OUTPUT_HANDLE). // set the color as WHITE on BLUE jht. System. } JNIEXPORT void JNICALL Java_JavaHowTo_keepColors (JNIEnv *env.setCursorPosition((short)20. jobject obj. SetConsoleTextAttribute(hConsole. COORD coordScreen.print("http://www. jshort background) { HANDLE hConsole.cls(). hConsole = GetStdHandle(STD_OUTPUT_HANDLE). SetConsoleTextAttribute(hConsole. } JNIEXPORT void JNICALL Java_JavaHowTo_restoreColors (JNIEnv *env.print("Real's HowTo"). GetConsoleScreenBufferInfo(hConsole. set color and cursor position (JNI) .com").out.out. jobject obj) { HANDLE hConsole. 8. CONSOLE_SCREEN_BUFFER_INFO ConsoleInfo. // clear the screen jht. } JNIEXPORT void JNICALL Java_JavaHowTo_setColor (JNIEnv *env. // set the cursor at line 10 column 20 jht. // set the cursor at line 15 column 20 jht. } Build the DLL (target Release). jshort foreground. hConsole = GetStdHandle(STD_OUTPUT_HANDLE). SetConsoleCursorPosition( hConsole. coordScreen.Y = y.setCursorPosition((short)20. foreground + background). // keep the current colors jht.rgagnon.keepColors(). jobject obj) { HANDLE hConsole. hConsole = GetStdHandle(STD_OUTPUT_HANDLE). originalColors = ConsoleInfo.wAttributes.jht. public class JNIJavaHowTo { public static void main(String[] args) { JavaHowTo jht = new JavaHowTo().FOREGROUND_WHITE. System.

eaio.17 Call Windows API (Open source solution) .// restore the orginal colors jht.rgagnon.com/javadetails/.de/software/nativecall/ If you find this article useful.destroy(). ic. consider making a small donation to show your support for this Web site and its content.(short)20). // set the cursor at line 20 column 0 jht. Boolean.com 8. NativeCall. If you find this article useful.FALSE }). IntCall ic = new IntCall("CopyFileA").*.html NativeCall NativeCall is a Java toolkit that lets you call operating system methods from whithin Java without JNI code.. Written and compiled by Réal Gagnon ©1998−2005 [ home ] Written and compiled Réal Gagnon ©2007 real@rgagnon.restoreColors().nativecall. } } You can download a zip with everything here. See http://johannburkard.rgagnon.setCursorPosition((short)0. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 8.init().executeCall(new Object[] { "test.txt". // copying a file to a new one using the Windows API import com.17 Call Windows API (Open source solution) Current version of this HowTo : http://www. consider making a small donation to show your support for this Web site and its content. ic./javadetails/java−0497. "test_copy.com http://www.txt".

public class JavaChrono extends Applet { String previousTime = "0" . Unix/Linux But it seems that there is a LiveConnect−SDK for Unix. The only other thing then is to change the <applet> tags to <embed> tag (more info on this is on the Mozilla site).2 * Read me * Current version of this HowTo : http://www.rgagnon. The LiveConnect package is included with IE4/5 (Win version).*. Thanks to Neil English for the tip 9.sun. The LiveConnect package is included with the Java plugin too. It's based on N3 but works on N4 (at least on Solaris and Linux.rgagnon.. the Applet should stop.k.html.9 Javascript interaction 9. long j. thanks to A./javadetails/java−0168./javadetails/java−0169.3 Wake−up a Java applet Current version of this HowTo : http://www.com/javadetails/. 9 Javascript interaction .com/products/plugin/reference/docs/index. The JSObject package is included with Netscape 6 preview but it is broken but should be fixed for the release version! Mac To use the LiveConnect packages on the Mac you will need to install the latest MRJ available from the Apple website and then goto the Mozilla website and download the MRJ Plugin. boolean okToChrono = false.applet. Zisowsky for the tip). String currentTime = "0"..1 java−js 9.html When moving the mouse over an image. [JAVA APPLET] import java.awt.html The examples in these How−to's are tested with Netscape 7 (or better) on Windows.com/javadetails/. import java. The official documentation for the various versions can be found at http://java. we want to start an applet (here a simple chronometer). l. and when the mouse leave the image.*.

} public void startChrono() { j = System.applets[0]. g.setColor(b).startChrono()" onMouseOut="document.currentTimeMillis().applets[0]. l = k−j. f = getForeground().sleep(1000). } public void paint(Graphics g) { if (okToChrono) { g. k = System.drawString(currentTime.30). g.repaint().setColor(f).toString(l/1000). previousTime = currentTime. f. tm. currentTime = Long. this. } } } class MyThread extends Thread { JavaChrono theApplet.drawString(previousTime. MyThread tm = new MyThread(this).currentTimeMillis().gif" WIDTH=100 HEIGHT=100> </A> /BODY/HTML 9 Javascript interaction .class WIDTH=150 HEIGHT=150> </APPLET> <A HREF="" onMouseOver="document.start(). public MyThread(JavaChrono a) { theApplet = a. g.Color b.30).10. public void init() { b = getBackground().stopChrono()" > <IMG SRC="whatever. okToChrono = true. } public void run() { while (true) { try { theApplet.10. } catch(InterruptedException e) { } } } } [HTML] <HTML><HEAD></HEAD><BODY> <APPLET CODE=JavaChrono. } public void stopChrono() { okToChrono = false.

f = null.com/javadetails/.awt.myApplet.*. we tell the applet to open or close a frame.isActive()) document. In the following snippet.100).applets[0]. } } public void disposeFrame() { if (f != null) { f. calls a method in our Applet. In the next example.class" HEIGHT=1 WIDTH=1></APPLET> <FORM> <INPUT TYPE="button" VALUE="Start the Applet" onClick= "if (document.applet. public void init() { } public void showFrame() { if (f == null) { f = new Frame().4 Call a Java method from Javascript Current version of this HowTo : http://www. public class MyApplet extends Applet { Frame f = null. the first example calls the method in the Toolkit to retrieve the screen resolution./javadetails/java−0170. } } } Try it here. f.setVisible(true). 9. The second example.add(new Label("Hello World")).showFrame()"> <INPUT TYPE="button" VALUE="Stop the Applet" onClick= "if (document. [HTML] <HTML> <HEAD></HEAD> <BODY> <APPLET NAME="myApplet" CODE="MyApplet.*. f.4 Call a Java method from Javascript . 9.rgagnon.. when we click on a FORM's button.Try it here.applets[0].myApplet.isActive()) document.disposeFrame()"> /FORM/BODY/HTML [JAVA APPLET] import java. import java. f.html You call a Java method by giving its fully qualified name.dispose().setSize(100.

import java. 10.getScreenSize(). [Java applet] import java.height.4 Call a Java method from Javascript . } </SCRIPT> <FORM> <INPUT type="button" value="call Java Applet method" onClick = "document. } public int getScreenHeight() { return Toolkit. g. public class InJava extends Applet{ public void sayHello() { Graphics g = getGraphics().getScreenSize().applet.*. import java.applet.getDefaultToolkit().awt.class" NAME="myApplet" HEIGHT=100 WIDTH=100> </APPLET> /BODY/HTML Try it here import java.getDefaultToolkit().awt. So the solution is simple.* call in a public method of a "dummy" Applet. } } [Javascript and HTML (IE and Netscape)] <HTML><HEAD></HEAD><BODY> 9.NOTE: On IE4 or better.*.getScreenSize().getScreenSize().applet. you can't call java.Applet) but don't have a general access to other java classes .Toolkit.sayHello()"> </FORM> <INPUT type="button" value="call Java method direct" onClick = "getScreenDimension()"> <APPLET CODE="InJava.*.Toolkit. IE javascript can only access the public methods of an applet (a class derived from java.drawString("Hello from JAVA!".width.width + " height:" + java.getDefaultToolkit().* methods directly from Javascript or Jscript. 10). } } [Javascript and HTML (Netscape)] <HTML><HEAD></HEAD><BODY> <SCRIPT> function getScreenDimension() { alert("Screen Dimension\n" + " width:" + java.awt. wrap the java.*.height). // (IE and Netscape ok) public class InJava2 extends Applet{ public int getScreenWidth() { return Toolkit.awt.myApplet.getDefaultToolkit().

class" NAME="myApplet" HEIGHT=100 WIDTH=100> </APPLET> /BODY/HTML Try it here NOTE: This for demonstration only.. <PARAM NAME="scriptable" value="true"> <PARAM NAME="mayscript" value="true"> .> ..5 Calling Java applets methods using DOM and JavaScript . </OBJECT> [in your script] document.html Java variables can be used by giving the fully qualified name.all.getScreenWidth() + " height:" + document. the preferred way is to use special "access method" to read Java variables (only String or integer)./javadetails/java−0171.5 Calling Java applets methods using DOM and JavaScript Current version of this HowTo : http://www. This Sun's document describes how Java to Javascript communication works when using the Java Plug−in.width properties directly.myApplet.myMethod() You use the scriptable parameter if you call Java method from Javascript..com/javadetails/. 9. To be compatible Netscape AND MSIEv4..6 Access Java variables from Javascript Current version of this HowTo : http://www. On N4 or IE4.myApplet..html [IE4 or better] <OBJECT ID="myApplet" ./javadetails/java−0346. You use the mayscript parameter if you call Javascript function from Java. it's better to use screen.myApplet. there is a delay because the Applet need to load and initialize..com/javadetails/. } </SCRIPT> <FORM> <INPUT type="button" value="call JAVA" onClick = "getScreenDimension()"> </FORM> <APPLET CODE="InJava2.<SCRIPT> function getScreenDimension() { alert("Screen Dimension\r\n width:" + document.rgagnon.getScreenHeight() ). 9.rgagnon. 9.. There is no need for a Java Applet! NOTE: The first time.height and screen. In Java. the variable must be declared as "public"..

*. } </SCRIPT> <FORM> <INPUT type="button" value="Java says" onClick = "JavaSays().[Java applet] import java. 9.*. public String sJava = "String from JAVA".7 Call Javascript from a Java applet . you have to create a method in your applet class that calls the other class's method. 9. public class InJava4 extends Applet{ public void init(){ String msg = "Hello from Java (using javascript alert)". using the javascript: protocol A Javascript function is called from Java by using the showDocument method.7 Call Javascript from a Java applet Current version of this HowTo : http://www. import java.net. public int getIntJava() { return iJava.*.getIntJava() + "\n" + "and sJava is :" + document.applet. } public String getStringJava() { return sJava.. import java.applet.myApplet.*.com/javadetails/. public class InJava3 extends Applet{ public int iJava = 123."> </FORM> <APPLET CODE="InJava3.myApplet.class" NAME="myApplet" HEIGHT=0 WIDTH=0> /APPLET/BODY/HTML Try it here Remember that IE4 can access only attributes and methods from a class derived from java.applet./javadetails/java−0172.awt. A URL is needed with "javascript:" as the protocol.Applet.rgagnon.getStringJava()). If you want to call a method or use an attribute in another class. [Java applet] import java. } } [Javascript and HTML] <HTML><HEAD></HEAD><BODY> <SCRIPT> function JavaSays() { alert("Java says\n the value of iJava is :" + document.html Netscape only.

Netscape and IE Ok.*.javascript.showDocument (new URL("javascript:doAlert(\"" + msg +"\")")). b = new Button("execute Javascript").0/1.4. b.JSObject package ? For Java 1. java.g. public class InJava5 extends Applet implements ActionListener { Button b.jar to your classpath. In the following example. The Applet must contains the MAYSCRIPT parameter to be able to use JSObject.*. TextField t. It can be found in the lib directory of your JRE installation. } </SCRIPT> <APPLET CODE="InJava4.javascript.jar For Java 1.event.*.*. C:\Program Files\Java\jre1. add(b).1: use jaws.try { getAppletContext(). Or you can execute function defined on the same page as the Applet. you type in the TextField a Javascript function and press the button to execute the function. java.jar (same directory).awt.0\lib\plugin.7 Call Javascript from a Java applet .applet. add(t).JSObject package How to compile when using the netscape.awt. public void init() { t = new TextField(20). } catch (MalformedURLException me) { } } } [Javascript and HTML] <HTML><HEAD></HEAD><BODY> <SCRIPT> function doAlert(s) { alert(s). try alert('Hello from JAVA').class" NAME="myApplet" MAYSCRIPT HEIGHT=10 WIDTH=10> </APPLET> </BODY> /HTML Try it here Netscape and IE ok.javascript. } 9.4. import import import import java. e.addActionListener(this). For example.2 and later: add plugin.5. using the netscape. netscape.4.

i < ms.getWindow(this). } catch (Exception e) { jsresult = "" + e. boolean success = false.compareTo("eval") == 0) eval = ms[i]. // posted by C Werner on the realhowto list import java.. a[0] = this. result is " + jsresult)... /* this is the applet */ jswin = getw. success = true. That way you don't need to modify your CLASSPATH for compilation or even import the netscape. Object result = eval.JSObject")..println("eval succeeded. a). if (result instanceof String) jsresult = (String) result. else if (ms[i]. .public void actionPerformed(ActionEvent ae) { if (ae.invoke(c.close()".*. /* does it in IE too */ Method ms[] = c. } catch (InvocationTargetException ite) { jsresult = "" + ite. String jscmd = "window. } if (success) System.println("eval failed with error " + jsresult).eval(t. /* JavaScript command */ String jsresult = null. i++) { if (ms[i]... 9. } } } Try it here Another way is to use the Reflection API.javascript.toString().getText()). /* this yields the JSObject */ a[0] = jscmd.reflect.invoke(jswin.getName(). try { Method getw = null.7 Call Javascript from a Java applet .out. else System. eval = null.getName(). for (int i = 0.getSource() == b) { JSObject win = (JSObject) JSObject. } } Object a[] = new Object[1].length.jsobject package. Object jswin = null.out. a). . // Somewhere in the applet class .compareTo("getWindow") == 0) getw = ms[i]. Class c = Class.getTargetException(). win.lang.forName("netscape.getMethods(). else jsresult = result.

class MAYSCRIPT WIDTH=150 HEIGHT=150> /APPLET/BODY/HTML Try it here 9.applet. win.write(s)./javadetails/java−0173. } </SCRIPT> <APPLET CODE=HtmlFromJava.html We can use the netscape.document.*.eval("createHTML(\"" + HTML +"\"). java.getSource() == aButton){ String HTML = "<HTML><HEAD></HEAD><BODY>".document. public class HtmlFromJava extends Applet implements ActionListener { Button aButton. aButton = new Button("create HTML").javascript.*.* included with Netscape browser and IE4 (Win version). JSObject win = (JSObject)JSObject. aButton.*.event.1 Netscape/IE4 (win) OK] import import import import java.rgagnon.addActionListener(this).8 Create dynamic HTML from a Java applet Current version of this HowTo : http://www.9. HTML += "<TABLE BORDER=1><TR><TD>Hello world</TD></TR></TABLE>". win. See also this HowTo to learn how to compile with this package. win.awt.javascript. } public void actionPerformed(ActionEvent ae) { if (ae..8 Create dynamic HTML from a Java applet .*. public void init(){ setLayout(new FlowLayout()).getWindow(this). java.com/javadetails/. netscape.close().open("about:"). HTML += "</BODY></HTML>"."). [Java applet JDK1. } } } [Javascript and HTML] <HTML><HEAD></HEAD><BODY> <SCRIPT> function createHTML(s) { win = window.awt. add(aButton).

*"> <FRAME SRC="interframe1.html" NAME="f1" > <FRAME SRC="interframe2.fromOtherFrame(a).html" NAME="f2"> </FRAMESET> </HEAD> [frame 1 HTML (interframe1.html)] <HTML><HEAD></HEAD> <BODY> <APPLET CODE="InterFrameDemo.app1.html You can use a Javascript function as a bridge between the 2 frames.html)] <HTML><HEAD></HEAD> <SCRIPT> function toOtherFrame(a. else parent.com/javadetails/. [main HTML (interframe0.awt.class" NAME="app2" MAYSCRIPT HEIGHT=200 WIDTH=200> WIDTH=200> <PARAM NAME="target" VALUE="f1"> </APPLET></BODY></HTML> [Java applet (InterFrameDemo.awt. 9.*.applet.fromOtherFrame(a).html)] <HTML><HEAD></HEAD> <FRAMESET COLS="50%.f2.9 Have Applets on different frames communicates with each other Current version of this HowTo : http://www.document. } </SCRIPT> </HEAD> <BODY> <APPLET CODE="InterFrameDemo.9 Have Applets on different frames communicates with each other . import java./javadetails/java−0174. target) { if (target == "f1") parent.9.rgagnon.*.class" NAME="app1" MAYSCRIPT HEIGHT=200 WIDTH=200> <PARAM NAME="target" VALUE="f2"> </APPLET></BODY></HTML> [frame 2 HTML (interframe2.*.java)] import java.f1. import java.event.app2.document..

\"" + target + "\")"..getText() + "\".b).net.addActionListener(this). tf).10 Send a message from an Applet to another Applet on a different page Current version of this HowTo : http://www. FirstApplet.out. setLayout(new BorderLayout()).toOtherFrame(\"" + tf. public class InterFrameDemo extends Applet implements ActionListener { TextField tf.html URL. add("South".javascript.html FirstApplet encodes the message for SecondApplet in the search (or query) section of SecondApplet. System.println("to Javascript:" + js). win.getSource() == b) { String js = "parent. Button b.rgagnon.URL.10 Send a message from an Applet to another Applet on a different page .html decodes the search section and dynamically creates a new page containing the APPLET tag for SecondApplet and a PARAM with the message coming from FirstApplet. tf = new TextField(20). A simple script in SecondApplet. String target.setText(s). b = new Button("To other frame"). public void init() { target = getParameter("target").import java. add("North".html <HTML><HEAD></HEAD><BODY> <APPLET CODE="FirstApplet.*.class" HEIGHT=100 WIDTH=300> /APPLET/BODY/HTML 9.f1. JSObject win = (JSObject) JSObject./javadetails/java−0181. } } public void fromOtherFrame(String s) { tf. } public void actionPerformed(ActionEvent ae) { if (ae. import netscape.com/javadetails/.eval(js). } } Try it here For a JAVA−only solution check this Java How−to 9.getWindow(this). b.

TextField t. t. b. ' ') // replace encoded chars by decoded chars if any theMessage = unescape(theMessage) html = '<APPLET CODE="SecondApplet.event.java import import import import java. java.*.search // strip the "message header" theMessage = theMessage.strlen) // replace all '+" by space theMessage = replace(theMessage.awt.*.length). function replace(s. return r.getSource() == b) { try { getAppletContext().showDocument (new URL(getCodeBase().i) + u.location.class"' html += ' HEIGHT=100' html += ' WIDTH=400> ' 9. r += s.substring(1 + 'message='.html?" + "message=" + URLEncoder. '+'. t.length if (strlen > 0) { theMessage = document.search. r = "". // replace all occurrence of token by another // in a string.FirstApplet.indexOf(t).length <s. } } } } SecondApplet. java.substring(0.awt. s.getText()))).*. add(b = new Button("Load 2nd applet")). u).10 Send a message from an Applet to another Applet on a different page .addActionListener(this).net.applet.location. public void init() { add(new Label("Message to 2nd applet :")). "SecondApplet.html <HTML><HEAD></HEAD><BODY> <SCRIPT> // from Javascript How−to general part 3. } public void actionPerformed(ActionEvent ae) { if (ae.*. } strlen = document. } catch (Exception e) { e.length. add(t= new TextField(20)).encode(t.length. public class FirstApplet extends Applet implements ActionListener { Button b. java.substring(i + t.printStackTrace().length) r += replace(s. u) { i = s. if ( i + t. if (i == −1) return s.

String s = getParameter("Message").applet.java import java. you have TextField in your Applet and // you want to transert its content to the HTML FORM // return myTextField.rgagnon.myForm./javadetails/java−0175.com/javadetails/.close() } </SCRIPT> /BODY/HTML SecondApplet.*.value = document.close() document.getFirstName().*.q.11 Retrieve values from a Java applet for HTML form (CGI) .applet. } } [HTML and Javascript] <HTML><HEAD> <SCRIPT> function getValueFromApplet(){ document.awt. public class SecondApplet extends Applet { public void init() { Label l = new Label("Message from 1st Applet"). take a look at this Java How−to.html Retrieve the value with a Javascript function called via the onSubmit event of the form. return "Real's HowTo". TextField tf = new TextField( 50 ). 9.11 Retrieve values from a Java applet for HTML form (CGI) Current version of this HowTo : http://www. } 9. return true.setText(s).java] public class InitHTMLForm extends java.myApplet. add(tf).getText(). } } You can try it here! This method is useful when you need to pass the message to the SecondApplet via PARAM tag.open() document. add (l). tf. But if you don't need the PARAM tag.html += '<PARAM NAME="Message" VALUE="' + theMessage + '"> ' html += '</APPLET>' document. import java. [InitHTMLForm.Applet { public String getFirstName() { // in real life..write(html) document.

com/javadetails/. To execute a Javascript only when an Applet is ready : <SCRIPT> function waituntilok() { if (document..applets[0])) alert("not ready").class" NAME="myApplet" HEIGHT=0 WIDTH=0> </APPLET> <FORM ACTION="http://www.12 Detect if an Applet is ready Current version of this HowTo : http://www.ca/search" NAME="myForm" onSubmit="return getValueFromApplet()"> <INPUT TYPE="hidden" VALUE="" NAME="q"> <INPUT TYPE="submit" VALUE="Submit" > </FORM> /BODY/HTML Try it here 9.. /BODY 9../javadetails/java−0176.rgagnon."> .google. <BODY onLoad="waituntilok()..</SCRIPT> <BODY> <APPLET CODE="InitHTMLForm.5000) } } function doit() { .isActive(). } </SCRIPT> .. } </SCRIPT> <FORM> <INPUT TYPE=button VALUE="Check applet" onClick="if (!isAppletReady(document.myApplet..isActive()) { doit().html <SCRIPT> function isAppletReady(a) { return a..."> /FORM An Applet is ready when it's loaded and its init() method is done.. } else { settimeout(waituntilok().12 Detect if an Applet is ready .

By calling the javascript function from the BODY onLoad handler, we can assume that the Applet is loaded, initiated and started. Here a "browser friendly" solution from N. Witteman to check if an Applet can be loaded (or found).
<HTML> <HEAD> <SCRIPT LANGUAGE="JavaScript"> onError = errHandler; // Without he parentheses, because we don't want IE // to do this. Like this, only NS does. function appLoaded() { if (!document.applets[0].isActive) // in IE: isActive returns an error if the applet IS loaded, // false if not loaded // in NS: isActive returns true if loaded, an error if not loaded, // so never reaches the next statement alert("IE: Applet could not be loaded"); } function errHandler() { alert("NS: Applet could not be loaded"); consume(); // stops further processing of the error } </SCRIPT> </HEAD> <BODY onLoad = appLoaded();> <APPLET code=someClass.class codeBase=someURL height=50 width=300><PARAM NAME="bgcolor" VALUE="FFFFFF"> </APPLET> </BODY> /HTML

9.13 Read/Write HTML field values from JAVA
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0177.html [Netscape AND IE4 compatible] The netscape.javascript.* (LiveConnect) package provides facilities to directly manipulate HTML FORM components.
JSObject win = (JSObject)JSObject.getWindow(this); JSObject inputText = (JSObject) win.eval("document.forms[0].elements[0]"); String value = (String)inputText.getMember("value"); // read form value inputText.setMember("value" , value + " new stuff"); // write form value

But this action requires a signed applet. in Netscape, you must
PrivilegeManager.enablePrivilege("UniversalBrowserRead"); PrivilegeManager.enablePrivilege("UniversalBrowserWrite");

9.13 Read/Write HTML field values from JAVA

before using an JSObject related to an HTML document. But there is a workaround, simply pass the informations through Javascript functions! [JSjava.java]
import import import import java.applet.*; java.awt.event.*; java.awt.*; netscape.javascript.*;

public class JSjava extends Applet implements ActionListener { Button b1,b2; TextField tf; JSObject win; public void init(){ setLayout(new FlowLayout()); tf = new TextField(10); b1 = new Button("to FORM"); b2 = new Button("from FORM"); b1.addActionListener(this); b2.addActionListener(this); add(tf);add(b1);add(b2); } public void actionPerformed(ActionEvent ae) { if (ae.getSource() == b1) { // send TO FORM JSObject win = (JSObject)JSObject.getWindow(this); win.eval("setHTMLInputText('"+tf.getText()+"');"); } if (ae.getSource() == b2) { // receive FROM FORM JSObject win = (JSObject)JSObject.getWindow(this); tf.setText((String)win.eval("getHTMLInputText();")); } } }

[JSjava.html]
<HTML><HEAD> <SCRIPT> function getHTMLInputText(){ return document.forms[0].elements[0].value; } function setHTMLInputText(s){ document.forms[0].elements[0].value = s; } </SCRIPT></HEAD><BODY> <FORM> <INPUT TYPE=text SZIE=20> </FORM> <APPLET NAME="JS" CODE=JSjava.class MAYSCRIPT WIDTH=200 HEIGTH=200> /APPLET/BODY/HTML

9.13 Read/Write HTML field values from JAVA

For best result, never use LiveConnect JSObject in Applet's init() method.

9.14 Detect if Java is enabled
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0178.html from Javascript :
function isJavaAvailable(){ return ( navigator.javaEnabled &navigator.javaEnabled() ); }
For an HTML solution, check this How−to

9.15 Detect if Java 1.1 (with event delegation) is available
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0179.html On some version of Netscape (eg.4.03), even if the JDK1.1 is reported as the Java version, you need to apply a special patch to upgrade to the event delegation model. Here how you can detect if the patch has been applied.
function isJava11Available() { if (java.awt.event.MouseEvent) return true; else return false; }

Someone at Netscape suggests a better way to check :
function isJava11Available(){ if (java.awt.event.MouseEvent == "[JavaClass java/awt/event/MouseEvent]") return true; return false; }

because Unknown Java classes are reflected as JavaPackages, for reasons related to the fact that there's no way to tell if something is a valid package.

9.16 Access Cookies from a Java Applet
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0180.html This Applet uses the package netscape.javascript.JSObject. To compile such program, you have to include in the CLASSPATH a special jar included in the JRE 9.14 Detect if Java is enabled

installation. For Java 1.4.2 and later: add plugin.jar to your classpath when compiling. It can be found in the lib directory of your JRE installation, ex. C:\Program Files\Java\jre1.5.0\lib\plugin.jar NOTE : For Java 1.4.0/1.4.1: use jaws.jar (same directory). [HTML file (testCookie.html)]
<HTML><HEAD></HEAD><BODY> <APPLET CODE=TestCookie.class MAYSCRIPT HEIGHT=150 WIDTH=200> /APPLET/BODY/HTML

[Java applet (TestCookie.java)]
import import import import netscape.javascript.*; java.awt.*; java.awt.event.*; java.applet.*;

public class TestCookie extends Applet implements ActionListener { TextField tf1, tf2; Button b1, b2, b3;

public void init() { tf1 = new TextField(20); tf2 = new TextField(20); b1 = new Button("Write Cookie"); b2 = new Button("Read Cookie"); b3 = new Button("Delete Coookie"); setLayout(new FlowLayout()); add(tf1); add(tf2); add(b1); add(b2); add(b3); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); } public void actionPerformed(ActionEvent ae) { if (ae.getSource() == b1) { /* ** write a cookie ** computes the expiration date, good for 1 month */ java.util.Calendar c = java.util.Calendar.getInstance(); c.add(java.util.Calendar.MONTH, 1); String expires = "; expires=" + c.getTime().toString(); String s1 = tf1.getText() + expires; System.out.println(s1);

9.14 Detect if Java is enabled

JSObject myBrowser = JSObject.getWindow(this); JSObject myDocument = (JSObject) myBrowser.getMember("document"); myDocument.setMember("cookie", s1); } if (ae.getSource() == b2) { /* ** read a cookie */ tf2.setText(getCookie()); } if (ae.getSource() == b3) { /* ** delete a cookie, set the expiration in the past */ java.util.Calendar c = java.util.Calendar.getInstance(); c.add(java.util.Calendar.MONTH, −1); String expires = "; expires=" + c.getTime().toString(); String s1 = tf1.getText() + expires; JSObject myBrowser = JSObject.getWindow(this); JSObject myDocument = (JSObject) myBrowser.getMember("document"); myDocument.setMember("cookie", s1); } } public String getCookie() { /* ** get all cookies for a document */ try { JSObject myBrowser = (JSObject) JSObject.getWindow(this); JSObject myDocument = (JSObject) myBrowser.getMember("document"); String myCookie = (String)myDocument.getMember("cookie"); if (myCookie.length() > 0) return myCookie; } catch (Exception e){ e.printStackTrace(); } return "?"; } public String getCookie(String name) { /* ** get a specific cookie by its name, parse the cookie. ** not used in this Applet but can be useful */ String myCookie = getCookie(); String search = name + "="; if (myCookie.length() > 0) { int offset = myCookie.indexOf(search); if (offset != −1) { offset += search.length(); int end = myCookie.indexOf(";", offset); if (end == −1) end = myCookie.length(); return myCookie.substring(offset,end); } else System.out.println("Did not find cookie: "+name);

9.14 Detect if Java is enabled

} return ""; } }
You can try it here.

See this text file with some useful Javascript functions for cookies handling. Check this How−to to detect if Cookies are enabled or not.

9.17 Set Applet PARAM VALUE from javascript
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0182.html PARAM VALUE can't be changed ar run−time but during layout time, javascript "entities" can be used to set calculated VALUES. In this How−to, VALUES are coming from a javascript variable, a javascript function and a javascript expression.
<HTML><HEAD></HEAD><BODY> <SCRIPT> var jsVar = "Hello World from jsVar"; function jsFnct() { return "Hello World from jsFnct"; } </SCRIPT></HEAD><BODY> <<APPLET CODE ="MyApplet.class" HEIGHT=100 WIDTH=400> <PARAM NAME="first" VALUE="&{jsVar};"> <param name="second" value="&{jsFnct()};"> <param name="third" value="&{'hello world'.toUpperCase() + ' from js Expression'};"> </APPLET> /BODY/HTML

For demonstration purpose, the MyApplet class
import java.applet.*; import java.awt.*; public class MyApplet extends Applet {

public void init() { add(new Label(getParameter("first"))); add(new Label(getParameter("second"))); add(new Label(getParameter("third"))); } }
NOTE: Javascript entities are not supported in IE. The workaround is to use the document.write() method to customize the APPLET PARAM during layout time. See this How−to for an example.

9.17 Set Applet PARAM VALUE from javascript

9.18 Pass an Array between Java and Javascript
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0183.html Javascript can read directly a Java Array but the other way don't seem be true. NOTE : Reading a Java array from Javascript may crash your browser for some unknown reason. So it's safer to use the next technique! A safe and simple way is to transform the Array as a big String with a known character used a separator. From there, it's trivial to do some manipulations to retrieve the array. In the following example, the first button is used to read directly the Java array. The second button call a Java method which to transform the array as a string, then the Javascript function split() is used to retrieve the array. The third button will modify the Java array. A Javascript array is transformed with the function join() and on the Java−side, a StringTokenizer will do the rest. [Java applet]
import java.awt.*; import java.applet.*; import java.util.*; public class TestJavaArray extends Applet{ public String javaArray [] = { "array 1", "array 2" , "array 3" }; public String [] getJavaArray() { return javaArray; } public String getJavaArrayAsAString() { // you need more error checking here, of course... int k; String s = ""; k = javaArray.length; s = javaArray[0]; for (int i= 1 ; i < k; i++) { s += "|" + javaArray[i] ; } return s; } public void putJavaArray(String arrayAsAString) { int i = 0; String s; StringTokenizer st = new StringTokenizer(arrayAsAString, "|"); while(st.hasMoreTokens()){ javaArray[i++] = st.nextToken(); } } }

[HTML and Javascript]

9.18 Pass an Array between Java and Javascript

<HTML><HEAD></HEAD><BODY> <SCRIPT> function getJavaArray() { arrayFromJava = document.myApplet.getJavaArray(); alert("Java Array length = " + arrayFromJava.length + "\r\n" + "element 2 is " + arrayFromJava[1]); } function getJavaArrayAsAString() { var arrayAsAString = document.myApplet.getJavaArrayAsAString(); realJsString = arrayAsAString + ""; arrayFromJava = realJsString.split("|"); alert("Java Array length = " + arrayFromJava.length + "\r\n" + "element 2 is " + arrayFromJava[1]); } function putJavaArray() { arrayFromJs = new Array("ARRAY 1", "ARRAY 2", "ARRAY 3"); arrayAsAString = arrayFromJs.join("|"); document.myApplet.putJavaArray(arrayAsAString); } </SCRIPT> <FORM> <INPUT type="button" value="get JAVA array" onClick = "getJavaArray();"> <INPUT type="button" value="get JAVA array (as a string)" onClick = "getJavaArrayAsAString();"> <INPUT type="button" value="put JAVA array" onClick = "putJavaArray();"> </FORM> <APPLET CODE="TestJavaArray.class" NAME="myApplet" HEIGHT=0 WIDTH=0> /APPLET/BODY/HTML

Try it here. Here an interesting piece of code submitted by M. Caetano which does basically the same thing. Note the use of regular expressions to keep the code short and compact. Since java classes are called directly by javascript, these functions won't work with IE (only with Netscape).
/* COPYJAVA (by Mike Caetano)

Array prototype method to transfer array elements between javascript and java java array arg fills this empty js array with elements from java array empty js array assigns its elements to string cast java array Use: // fill empty jsArray with the elements from the java array as strings var jsArray = []; jsArray.copyJava(javaArray) // fill a javaArray with the elements from jsArray cast as java.lang.String var javaArray2 = jsArray.copyJava()

9.18 Pass an Array between Java and Javascript

Note: doesn't include cast for netscape.javascript.JSObject − that requires a more stringent type checking ie. typeof( [object Layer] ) => netscape.javascript.JSObject − for now just don't call copyJava on an array of objects −−−−−−−−−−−−−−−−−−−−−−−−−−−− */ function copyJava(arg_) { if ( /^\bnull\b$|^\bundefined\b$|^\s?$/i.test(arg_) ) { if ( this.length > 0 ) { var temp = makeJavaArray('String',this.length); var i=0; while ( i < this.length ) { temp[i] = ''+this[i++]; } return temp; } else { return null; } } else { if ( /^\bobject\b$/i.test(typeof(arg_)) ) { if ( this.length == 0 ) { var len = java.lang.reflect.Array.getLength(arg_); var i=0; while ( i < len ) { this[i] = ''+arg_[i++]; } } } } } function makeJavaArray(type_,size_) { if ( !/^\bnull\b$|^\bundefined\b$|^\s?$/i.test(type_) ) { if ( /boolean|byte|int|long|short|double |float|char|void|String|Object|Class|Thread/.test(type_) ) { var type = type_.charCodeAt(0)<91 ? 'java.lang.' + type_: type_; var size = !isNaN(Number(size_)) ? Number(size_) : 1; return ( new java.lang.reflect.Array.newInstance (java.lang.Class.forName(type),size) ); } // else invalid cast } // else invalid args }

9.19 Interaction without LiveConnect
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0184.html Java−Javascript interaction is not possible on many browsers or platforms. On Mac, for example, the LiveConnect package is not available, even with the latest Netscape version. On IE3, the interaction is very limited too. Java to Javascript One way to pass information from Java to Javascript, without LiveConnect or scripting support, is to have an hidden frame acting as a bridge. From Java you do a showDocument() with a particuliar page passing the message as parameter to the hidden frame, something like showDocument("mypage.html?HelloJavascriptFromJava", "hiddenframe"). The mypage.html page contains a javascript script to extract the parameter received in the URL (using the 9.19 Interaction without LiveConnect

document.search property). And then the parameter extracted is send to another javascript function in the visible frame. First, define the frameset with an invisible frame.
[SimpleJ2JS.HTML] <FRAMESET ROWS="100%,*"> <FRAME NAME="mainFrame" SRC="visiblepage.html" border=0> <FRAME NAME="scriptFrame" SRC="invisiblepage.html" border=0> </FRAMESET>

visiblepage.html contains the Applet and a javascript function. The idea is to type something in a TextField, press a Button to send a string to a javascript to do an alert() with the TextField content.
[visiblepage.html] <HTML><HEAD> <SCRIPT> function showMessage(s) { alert(s) } </SCRIPT> </HEAD><BODY><H1>Simple Java to Javascript interaction</H1><P> <APPLET CODE=SimpleApplet.class WIDTH=150 HEIGHT=150> </APPLET></BODY></HTML>

invisiblepage.html contains the function to extract the parameter and call the showMessage() function in the visible frame.
<HTML><HEAD> <SCRIPT> function replace(s, t, u) { i = s.indexOf(t); r = ""; if (i == −1) return s; r += s.substring(0,i) + u; if ( i + t.length < s.length) r += replace(s.substring(i + t.length, s.length), t, u); return r; } function getAndSendMessage() { theMessage = document.location.search.substring(1,255) if (theMessage.length > 0) { // replace all '+" by space theMessage = replace(theMessage, '+', ' ') window.parent.mainFrame.showMessage(unescape(theMessage)) } } </SCRIPT> </HEAD><BODY onLoad="getAndSendMessage();"> </BODY></HTML>

and finally the Applet (a JDK102 style, since we want to be friendly to older browsers).
[SimpleApplet.java] import java.applet.Applet; import java.awt.*;

9.19 Interaction without LiveConnect

public class SimpleApplet extends Applet { TextField aMessage; Button sendButton; public void init() { aMessage = new TextField(20); add(aMessage); sendButton = new Button("Send to Javascript"); add(sendButton); } public boolean action(Event e, Object o) { if (e.target.equals(sendButton)) { try { getAppletContext().showDocument (new java.net.URL (getCodeBase(), "invisiblepage.html?"+ java.net.URLEncoder.encode(aMessage.getText())), "scriptFrame"); } catch (Exception ex) { ex.printStackTrace(); } } return true; } }
Try it here.

Javascript to Java The idea here is to have an invisible Applet in an invisible frame that will receive a message (from Javascript in the visible frame) through the search part of its URL. Then via a static pointer to the visible Applet, the invisible Applet pass the message to the visible Applet by calling the appropriate function. Frames definition
[SimpleJS2J.html] <FRAMESET ROWS="100%,*"> <FRAME NAME="visibleFrame" SRC="visiblepage2.html" border=0> <FRAME NAME="invisibleFrame" SRC="invisiblepage2.html" border=0> </FRAMESET>

The visible page
[visiblepage2.html] <HTML><HEAD> <SCRIPT> function send2Java() { // you may need to encode the value with the escape() function parent.invisibleFrame.location = "invisiblepage2.html?" + document.forms[0].FromJs.value } </SCRIPT> </HEAD><BODY><H1>Simple Javascript to Java interaction</H1> <FORM> <INPUT TYPE=input NAME=FromJs WIDTH=50 VALUE="HelloWorld">

9.19 Interaction without LiveConnect

<INPUT TYPE=button VALUE="Send to JAVA" onClick="send2Java();"> </FORM> <APPLET CODE=SimpleApplet2.class WIDTH=300 HEIGHT=150> </APPLET></BODY></HTML>

The class to hold a static pointer to SimpleApplet2. This pointer will be used by the InvisibleApplet.
[SimpleAppletRegistered.java] public class SimpleAppletRegistered { static SimpleApplet2 sa; }

The SimpleApplet2 is TextField which will be used to display the message type in the HTML FORM.
[SimpleApplet2.java] import java.applet.Applet; import java.awt.*; public class SimpleApplet2 extends Applet { TextField aMessage; public void init() { add(new Label("Message from Javascript ")); aMessage = new TextField(20); add(aMessage); // put a pointer to this Applet in a static // variable which can be shared with the InvisibleApplet SimpleAppletRegistered.sa = this; } public void setMessage(String msg) { aMessage.setText(msg); } }

And finally the invisible page and InvisibleApplet
[invisiblepage2.html] <HTML><HEAD> </HEAD> <BODY> <APPLET CODE=InvisibleApplet.class WIDTH=1 HEIGHT=1> </APPLET> </BODY></HTML> [InvisibleApplet.java] import java.applet.Applet; public class InvisibleApplet extends Applet { public void init() { String completeURL = getDocumentBase().toString(); System.out.println("URL received : " + completeURL); int i = completeURL.indexOf("?");

9.19 Interaction without LiveConnect

if (i > −1) { String msg = completeURL.substring(completeURL.indexOf("?") + 1); // call SimpleApplet via the static pointer // you may to decode the string here with // java.net.URLDecoder.decode() method. SimpleAppletRegistered.sa.setMessage(msg); } } }
Try it here. NOTE: To send a message containing spaces and other special characters like &or ?, you will need to encode the message from Javascript (with the escape function) and decode the message in Java.

With IE, you need to run this sample through a Web server.

9.20 Directory listing on the Web server in a Java Applet
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0185.html There is no way for an Applet to retrieve a directory contents without the help of server side process(servlet/CGI). But here a way to do it with some help from Javascript. In a browser, loading a URL with no file specified will return a directory listing under the following conditions : 1. The directory doesn't contain a default page like index.html, default.htm or default.html. 2. The web server allows directory exploration. For example, the URL http://www.tactika.com/realhome/images shows a directory listing of the files in the images directory. The listing is actually a real HTML page build on the fly. Our applet will extract the links in this page and present them in a List. Links in a page are listed in the document property called links. This property can be easily transform into a String array by a Javascript function. Then the array is passed to a Java method. The Applet is very simple and can be customized to display more useful descriptions or filter some entries. We have 3 frames, 2 visibles and 1 invisible. The invisible one will contains the directory listing. Frame visible #1 is for the Applet, by doubleclicking on a line in the List, the corresponding images will be displayed in frame visble #2. Frames definitions Note that the 2 visibles frames are initially loaded with a "blank.html" to allow the third frame (the invisible one) to be loaded with the directory content (here "../images"). browse.html
<HTML><HEAD> <SCRIPT> function reload_master() { window.master.location.href = "./selector.html";

9.20 Directory listing on the Web server in a Java Applet

} </SCRIPT></HEAD> <FRAMESET ROWS="35%,65%,*" onLoad="reload_master()"> <FRAME SRC="blank.html" NAME="master"> <FRAME SRC="blank.html" NAME="detail"> <FRAME SRC="../images" NAME="contents" NORESIZE> </FRAMESET> /HTML

blank.html
<HTML<<HEAD><TITLE </TITLE></HEAD><BODY> </BODY></HTML>

When all pages are loaded, the selector.html page is loaded into the first visible frame. That page contains the Applet. During layout time, Javascript extracts links to the an Array. Via the BODY onLoad event handler, we trigger a Javascript function to transfer the Array to the Applet. selector.html
<HTML><HEAD> <SCRIPT> var LinksLength = parent.contents.window.document.links.length var AllTheLinksAsArray = new Array() // start at the second link because // we dont want the root directory for (var i = 1; i < LinksLength ; i++) { s = parent.contents.window.document.links[i]; AllTheLinksAsArray[i] = s; } function putLinksIntoApplet() { AllTheLinksAsString = AllTheLinksAsArray.join("|"); document.Selector.insertData(AllTheLinksAsString); } </SCRIPT></HEAD> <BODY onLoad ="putLinksIntoApplet()"> <P ALIGN="center">Doubleclick to view <APPLET CODE=Selector.class HEIGHT=100 WIDTH=400 NAME=Selector> <PARAM NAME="targetFrame" VALUE="detail"> </APPLET> </BODY> /HTML

Selector.java
import import import import import java.awt.*; java.awt.event.*; java.applet.*; java.util.*; java.net.*;

public class Selector extends Applet implements ActionListener { java.awt.List l;

9.20 Directory listing on the Web server in a Java Applet

boolean okToDisplay = false; String targetFrame = ""; public void init() { setLayout(new BorderLayout()); add(l = new java.awt.List(5), "Center"); l.addActionListener(this); targetFrame = getParameter("targetFrame"); } public void actionPerformed(ActionEvent ae) { if (okToDisplay) { try { URL urlToDisplay = new URL(ae.getActionCommand()); getAppletContext().showDocument(urlToDisplay, targetFrame); } catch (Exception e) { e.printStackTrace(); } } } public void insertData(String arrayAsAString) { int i = 0; String s; StringTokenizer st = new StringTokenizer(arrayAsAString, "|"); while(st.hasMoreTokens()){ s = st.nextToken(); l.add(s); // or l.addItem(s); System.out.println(s); } okToDisplay = true; } }
You can try it here. NOTE: This How−to is inspired by an article by Martin Webb on http://www.irt.org

9.21 Have a Java button close the browser window
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0282.html
import import import import java.applet.*; java.awt.*; java.awt.event.*; netscape.javascript.*;

public class WinClose extends Applet implements ActionListener{ Button wc = new Button("Close me"); public void init() { wc.setActionCommand("CLOSE"); wc.addActionListener(this); add(wc); }

9.21 Have a Java button close the browser window

public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.equals("CLOSE")) { JSObject win = (JSObject) JSObject.getWindow(this); win.eval("self.close();"); } } }

Try it here

9.22 Detect if cookies are enabled
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0303.html The detection is made by trying to write a cookie and reading it back. The value is passed to a Java Applet by create dynamically the APPLET tag. [testcookie.html]
<HTML><HEAD></HEAD><BODY> <SCRIPT> document.write("<APPLET CODE='MyApplet.class' HEIGHT=100 WIDTH=400>"); // check if cookie are enabled cookieBackup = document.cookie document.cookie = "cookie=yep" cookieOk = document.cookie.indexOf("cookie=yep") > −1 document.cookie = cookieBackup document.write(" <PARAM NAME='okToCookie' document.write("</APPLET>"); </SCRIPT> </BODY></HTML> VALUE=" + cookieOk + ">");

[MyApplet.java]
import java.applet.*; import java.awt.*; public class MyApplet extends Applet {

public void init() { add(new Label("Cookie enabled :")); add(new Label(getParameter("okToCookie"))); } }
If you find this article useful, consider making a small donation to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998−2005 [ home ]

9.22 Detect if cookies are enabled

."> <DIV name=mypage style="visibility:hidden" > . the DIV visibility attribute is set to true. <HTML> <HEAD> <SCRIPT> function doIt() { if (document.visibility="visible" } </SCRIPT></HEAD> <BODY onLoad="doIt().mypage. Initially the visible attribute is false.com 9. </DIV> </BODY> </HTML> Written and compiled Réal Gagnon ©2007 real@rgagnon..9.visibility="visible" else document.23 Display a page after all applets are loaded . When the page is completely loaded.com/javadetails/.style.rgagnon.23 Display a page after all applets are loaded Current version of this HowTo : http://www.com http://www..html Place your page completely in a DIV tag.all) mypage./jsdetails/js−0071.rgagnon.

3 Get parameters passed to a servlet Current version of this HowTo : http://www.1 java−jsp 10./javadetails/java−0357. out. res).servlet.getWriter(). out.com/javadetails/. consider making a small donation to show your support for this Web site and its content. import javax. public class MyServlet extends HttpServlet { public void doPost(HttpServletRequest req. res.rgagnon..rgagnon.println("the value is : " + valuePassed). out.html You may to take a look to these related How−to's in the EAServer/Jaguar section.println("</body></html>")../javadetails/java−0379.2 Read me Current version of this HowTo : http://www. } } If you find this article useful.setContentType("text/html").http.io.PrintWriter out = res.*.println("<html><head></head><body>").*. 10.com/javadetails/.getParameter("someValue"). } public void doGet(HttpServletRequest req. HttpServletResponse res) { // note : if "someValue" is missing a null is returned String valuePassed = req. HttpServletResponse res) { doPost(req. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10 Servlet/JSP .html <HTML> <HEAD></HEAD> <BODY> <FORM METHOD=POST ACTION="/servlet/MyServlet"> value : <INPUT TYPE="TEXT" NAME="someValue"> </FORM> </BODY> </HTML> import javax.servlet. java.10 Servlet/JSP 10.

nextElement(). out.println(parm + " = " + request. } else { out..println(" Message<INPUT TYPE=INPUT NAME=message>").getParameterMap().println("<HEAD><TITLE>MyServlet (no args)</TITLE></HEAD>"). out. out. out.println("<H1>Servlet</H1>"). while(paramNames. response. // do something with this parm } } Previous version of the Servlet API protected void doGet (HttpServletRequest request.println("<BODY>").getParameterNames(). if (!request.getParameterNames().setContentType( "text/html" ).hasMoreElements()) { String parm = (String)paramNames.hasMoreElements()) { String parm = (String)paramNames. out.4 Detect no argument condition in a Servlet .println("<BODY>"). out. out.getWriter(). if (i = 0) { // no arguments } else { Enumeration paramNames = req. out.10. out. } out.getParameterNames()./javadetails/java−0341. out.println(" Subject<INPUT TYPE=INPUT NAME=subject>").hasMoreElements()) { // no arguments out.4 Detect no argument condition in a Servlet Current version of this HowTo : http://www.com/javadetails/.println(" <INPUT TYPE=SUBMIT VALUE='Ok'>").println(" Recipients<INPUT TYPE=INPUT NAME=to>").println(" </FORM>").3 int i = req.html Servlet 2.util. consider making a small donation to show your support for this Web site and its content. IOException { PrintWriter out = response. while(paramNames.println("<HTML>").println("<H1>MyServlet</H1>"). } } If you find this article useful.println("<HEAD><TITLE>MyServlet (with args)</TITLE></HEAD>").println("<FORM METHOD='GET' ACTION='Servlet1'>").rgagnon.println("</BODY></HTML>").Enumeration paramNames = request. HttpServletResponse response) throws ServletException. out. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10. java. out.size().nextElement().getParameter(parm) + "<BR>").

5 Set a Cookie from a servlet .PrintWriter out = res.html import javax. HttpServletResponse res) { doPost(req. public class MyServlet extends HttpServlet { public void doPost (HttpServletRequest req.6 Read a Cookie from a servlet Current version of this HowTo : http://www. public class MyServlet extends HttpServlet { public void doPost(HttpServletRequest req.rgagnon. } } If you find this article useful.5 Set a Cookie from a servlet Current version of this HowTo : http://www. consider making a small donation to show your support for this Web site and its content.getValue()).10. i<cookies.servlet. 10.length. } } If you find this article useful.rgagnon.*.servlet.io./javadetails/java−0359.http.getWriter(). res). i++) { Cookie aCookie = theCookies[i]. HttpServletResponse res) { res../javadetails/java−0358. HttpServletResponse res) { doPost(req.servlet.getCookies().addCookie(new Cookie("mycookie_name". res). out. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10.com/javadetails/.servlet. consider making a small donation to show your support for this Web site and its content.getName() + " Value: " + aCookie. import javax. import javax.println ("Name : " + aCookie. "mycookie_value"))..*.com/javadetails/. } public void doGet(HttpServletRequest req. } } } public void doGet(HttpServletRequest req. if (theCookies != null) { java. HttpServletResponse res) { Cookie[] theCookies = request.html import javax.http.*. for (int i =0.*.

9 Talk to a CGI/Servlet Current version of this HowTo : http://www.com/javadetails/.Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10. } then the browser will popup a dialog for username/password 10./javadetails/java−0082.servlet.SC_UNAUTHORIZED). import javax. HttpServletResponse res) { doPost(req.html public void askPassword(HttpServletResponse response) { response./javadetails/java−0360.setMaxAge( 0 ).servlet. } } 10. // Expire after the browser is closed // cookie. HttpServletResponse res) { Cookie cookie = new Cookie ("myCookie".html 10. // Expire right now // cookie.7 Delete (or expire) a Cookie from a servlet .8 Ask for a password from a Servlet Current version of this HowTo : http://www.rgagnon../javadetails/java−0342.. res).*.setHeader("WWW−Authenticate". "BASIC realm=\"protected−area\""). "theCookieValue").com/javadetails/.setMaxAge( 300 ).. response.http.com/javadetails/.html import javax.rgagnon.7 Delete (or expire) a Cookie from a servlet Current version of this HowTo : http://www.rgagnon. // Expire in five minutes (5 * 60) cookie. } public void doGet(HttpServletRequest req.*.setMaxAge( −1 ). public class MyServlet extends HttpServlet { public void doPost(HttpServletRequest req.setStatus(response.

getOutputStream()). Here we calling a script called aCGI.encode("Real Gagnon").showDocument(cgiurl).10 Test for Cookies .close(). URL CGIurl = new URL(theCGI). First a connection is made to the CGI. String encoded = "name=" + URLencoder.com/cgi−bin/aCGI."application/x−www−form−urlencoded").setRequestProperty("content−type". Once the URL is constructed.setDoOutput(true).writeBytes(encoded). c.println(aLine).flush().com/javadetails/. there is no difference talking to CGI or Servlet. String aLine. There is no "dialog" between the client and the server. The CGI will process the result and produce a page to be displayed. DataOutputStream out = new DataOutputStream(c. Then InputStream is created to receive the result. A typical URL talking to CGI using the GET method would be: new URL("http://www.setUseCaches(false). String encoded = "name=" + URLencoder.rgagnon.pl".pl (a PERL script) passing the parameters name and site. getAppletContext(). BufferedReader in = new BufferedReader(new InputStreamReader(c. Each parameter is delimited by the character "Habitually the encoding is done through the static method encode of the java.com/cgi−bin/aCGI.server. There is two ways to send a request to a CGI.net. you call the CGI using the showDocument method (Applet). c. The client make a request and the server send back the result and close the connection. out.From the client point of view. spaces are changed to "+" and special character to hexadecimal using a 3−letter escape sequence.pl?name=real). Parameters are encoded. out.getInputStream()).URLencoder class. an OutputStream is open to send the parameters (if any).encode("Real Gagnon").. The POST method allows the programmer to manipulate the data received from the CGI.server.10 Test for Cookies Current version of this HowTo : http://www. URL cgiurl = new URL(thecgi + encoded). String theCGI = "http://www. The GET method contains encoded parameters in the URL.pl?". while ((aLine = in.com/cgi−bin/acgi. String theCGI = "http://www.html 10.out. } You can't do some output then some input and do again some output./javadetails/java−0374. 10. URLConnection c = CGIurl. c. out.openConnection().readLine()) != null) { // data from the CGI System. You must do all the output and then the input.server.

getString(i + 1) + "</TD>").sql. // table header out.println("<TD>" + rs. } 10. int columnCount = rsmd. } out.PrintWriter out) throws Exception { int rowCount = 0. } } 10.11 Display ResultSet data in an HTML Table in Servlet Current version of this HowTo : http://www. i++) { out. paramName = "foo". } out.println("<P ALIGN='center'><TABLE BORDER=1>"). java.println("<TR>"). out.getColumnLabel(i + 1) + "</TH>"). i < columnCount.getParameter( paramName ) == null ) { res.println("</TR>"). ResultSetMetaData rsmd = rs. i++) { out. public void doPost(HttpServletRequest req.println("</TABLE></P>"). "world" ).length == 0 ) ? failureURI : successURI ) } public void doGet(HttpServletRequest req. i < columnCount.sendRedirect(req.*.servlet. successURI = "/success.*.ResultSet rs. HttpServletResponse res) { doPost(req. // the data while (rs.com/javadetails/.next()) { rowCount++.getCookies().htm"..getColumnCount(). public class Test4Cookies extends HttpServlet { private private private private static static static static final final final final Cookie String String String cookie = new Cookie( "hello" .html private int dumpData(java. res.println("</TR>"). for (int i = 0.servlet. out.getRequestURI() +"?"+ paramName +"=bar" ). for (int i = 0.11 Display ResultSet data in an HTML Table in Servlet . return rowCount.import javax./javadetails/java−0378.getMetaData(). failureURI = "/failure.htm".sendRedirect (( req. HttpServletResponse res) { if ( req. } out. } else { res.println("<TR>"). res).println("<TH>" + rsmd.io. import javax.http.addCookie( cookie ).rgagnon.

setAttribute("foo".12 Specify the filename to be used for a file sent by a Servlet .getParameter("sitename"). requestVar).length())).setFooProperty("Real's HowTo"). "Real's HowTo"). To specify the correct filename String filename = "abc.Integer.toString(textFile.com/javadetails/. // open the file and write it in the OutputStream NOTE: For PDF output. consider making a small donation to show your support for this Web site and its content.setAttribute("foo". myBean. Then you forward the request RequestDispatcher dispatch = request.setAttribute("foo".html Say that your servlet called ""/servlet/GetFile" send back a file to a client request. request. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10.12 Specify the filename to be used for a file sent by a Servlet Current version of this HowTo : http://www.rgagnon. File textFile = new File(filename)."inline.forward(request.rgagnon.setHeader("Content−disposition"... response)."application/octetstream"). A parameter received by the first servlet to the second one String requestVar = request. dispatch.setHeader("Content−length".jsp"). see this HowTo If you find this article useful. request.html You set attributes on your request object and then forward the request object to the other servlet/jsp.10.dat" . response.getRequestDispatcher("next.com/javadetails/.setHeader("Content−type". filename=" + filename ). A Bean MyBean myBean = new MyBean(). the browser will suggest "GetFile" as the filename. myBean). response. 10. response. That file needs to be saved by the client.13 Pass information to another servlet/jsp Current version of this HowTo : http://www. If you do nothing./javadetails/java−0387. For a simple string request./javadetails/java−0401.

like: http://x.pdf" extension is an easy way. ex. consider making a small donation to show your support for this Web site and its content.html public isDefined(HttpServletRequest req. String fieldNameToSearchFor) { return req.14 Handle PDF output Current version of this HowTo : http://www.containsKey(fieldNameToSearchFor). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10.If you find this article useful.com/javadetails/./javadetails/java−0404. • An additional thing that seems to help some IE browsers is to also have : response.14 Handle PDF output . • Add a dummy parameter on the end of the url. response. so you need to give it a hint. Or you look at these HTTP headers : CERT_KEYSIZE .html • Set the content−type of the response to "application/pdf".16 In a Servlet./javadetails/java−0415..size()). "inline.html Use the servlet request's isSecure() or getAuthType() methods. and the ".rgagnon. If you find this article useful./javadetails/java−0443.filename=somepdf.setHeader("Content−Disposition". • Set the "content−length" on the response. consider making a small donation to show your support for this Web site and its content.setContentLength(bos. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10.getParameterMap(). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10. check if Form Field is present Current version of this HowTo : http://www.rgagnon. CERT_KEYSIZE.com/javadetails/.com/javadetails/. ex.rgagnon. } 10.pdf because IE ignores content−types.. response.pdf"). HTTPS_KEYSIZE Note: for a javascript solution see this HowTo If you find this article useful.. consider making a small donation to show your support for this Web site and its content.setContentType("application/pdf").z/DoGenCompStmt?filename=dummy.15 Detect if the connection is via a secure channel Current version of this HowTo : http://www. otherwise the Acrobat Reader plugin may not work properly.y.

you will get the IP of the proxy and not the client.html You can't.getRealPath("/"). From JSP. the proxy may include the requesting client IP in a special HTTP header. %> 10.getRemoteHost() ).18 Get client IP address from JSP Current version of this HowTo : http://www..print( request.getRemoteAddr() ).rgagnon.com/javadetails/.html <% out..19 Output a binary stream from a JSP Current version of this HowTo : http://www.com/javadetails/./javadetails/java−0363.. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10.getHeader("x−forwarded−for") ).getRealPath("/").rgagnon.com/javadetails/. consider making a small donation to show your support for this Web site and its content. However.html In a JSP String path = application.print( request.17 Get the root dir of a web app . In a Servlet String path = getServletContext.print( request.17 Get the root dir of a web app Current version of this HowTo : http://www. only character stream should be used./javadetails/java−0366./javadetails/java−0519. consider making a small donation to show your support for this Web site and its content. <% out. out. 10.If you find this article useful. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10.rgagnon. If you find this article useful. %> You may not get the real client IP if a the client is behind a proxy.

nRead). NOTE: Java component can't use cached ODBC connection.*" %> <% com.rgagnon.close(). Driver Tab : DLL or class name = sun. General Tab : Server name = jdbc:odbc:YourSystemDSNName with user/pwd 2./javadetails/java−0380. 10.gif"). Cache Tab : checkbox cache−by−name checked <%@page contentType="text/html"%> <html> <head><title>JSP Page</title></head> <body> <%@ page import="java.io. which means it will play games with text encoding. it's a better idea to use a servlet. it's still possible to use the ODBC−JDBC provided by Sun. since a JSP will be converted to a servlet. InputStream is = new URL("http://myserver/myimage.jcm. [image. byte[] buf = new byte[32 * 1024].JCMCache jcmCache= null. JDBC or Oracle cached connections. you define the cache : 1. Define a regular System DSN (through the ODBC Administration panel) 2. Having said that.20 Use a connection cache from JSP . follow these steps: 1. } o.JSP pages were designed for *text* output. To define a cache using ODBC−JDBC (bridge) connection. like PDF or dynamically generated GIF. it's possible to modifed the output stream.read(buf)) != −1 ) { o..jaguar. In jaguar. For binary output.jsp] <%@ page import="java.write(buf.getOutputStream().flush(). If there is no JDBC driver available.getInputStream().20 Use a connection cache from JSP Current version of this HowTo : http://www. You can have ODBC. you need to use a cached JDBC connection. % Thanks to Benjamin Grant for the bug fix. 0.net.com/javadetails/.sybase.*" %> <%@ page import="java.jdbc. The "out" object is a Writer. o.JdbcOdbcDriver with JDBC radio button selected 3. // 32k buffer int nRead = 0. But performance of such a bridge is poor and the reliability is not good in a multi−threaded environment.odbc.sql. 10.html Jaguar provides a very useful cache mechanism to speed up database requests.*" %> <%@page contentType="image/gif" %><% OutputStream o = response.// *important* to ensure no more jsp output return. while( (nRead=is.

createStatement().PreparedStatement stmt = con. java.JCM_WAIT). make the name available through a Property (of the Environment) of the Web application.Connection con = ds. java.naming. dbConn = jcmCache.sql.next()) { //do something } If you find this article useful. dbConn.getConnection(com. In this example. javax. } %> msgtext = <i><%= msg %></i> </body> </html> Instead of hard−coding the cache name into your java component.sybase. This way your components are more flexible and you are using the "J2EE way" to make a connection..jcm.close().getMessage() + "<BR>").InitialContext ctx = new javax.java.21 Read a Web Application property .sql.close().sql. } } rs. } catch (Exception e) { out. try { jcmCache = com.Connection dbConn = null.getConnection().DataSource ds = (javax.JCM.lookup("java:comp/env/jdbc/myconnection").html 10.sql.rgagnon.getCacheByName(jcmCacheString).prepareStatement(sql). java. String msg = "".executeQuery ("select msg from messages where msgid='00001'"). myconnection contains the cache name to be used. String jcmCacheString = "mycachename".getString("msg").println("OUPS " + e.sql.21 Read a Web Application property Current version of this HowTo : http://www.DataSource) ctx.naming.ResultSet rs = stmt.sql.next()) { msg = rs.com/javadetails/. javax.jaguar. if(rs != null) { while(rs./javadetails/java−0381.InitialContext().jcm. ResultSet rs = stmt.executeQuery().jaguar.JCMCache. consider making a small donation to show your support for this Web site and its content. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10.sybase. Statement stmt = dbConn. while (rs.

22 Use EJB from JSP Current version of this HowTo : http://www.lang.MyBean bean=new com.html <%! public String sayHello(){ return "Hello". } %> <%= sayHello() %> 10.22 Use EJB from JSP .xml deployment descriptor (in between the <webapp> </webapp> tag) <env−entry> <env−entry−name>docPath</env−entry−name> <env−entry−value>c:/doc/doc1</env−entry−value> <env−entry−type>java.23 Define a method in a JSP page Current version of this HowTo : http://www.lookup("java:comp/env")../javadetails/java−0410.company. String docBaseUser = (String) env..lang.lookup("docPath"). %> 10./javadetails/java−0396.String</env−entry−type> </env−entry> <env−entry> <env−entry−name>docUser</env−entry−name> <env−entry−value>net1</env−entry−value> <env−entry−type>java.lookup("docUser").rgagnon. String docBase = (String) env. 10.MyBean(1. Context env = (Context) new InitialContext(). 4).company.putAttribute("myBean". session.String</env−entry−type> </env−entry> Then from your JSP or Servlet.com/javadetails/.MyBean"/> EJB with constructor with parameters <% com. 3.company.html EJB with constructor with no parameter <jsp:useBean id="myBean" scope="session" class="com.com/javadetails/. bean).Web Application properties are defined in the WEB−INF/web. 2.rgagnon.

com/mywebapp/mypage.getServletContext(). HttpServletRequest request.servlet. uri). 10. the JSP page will be compiled if necessary. }.*"%> import="javax. RequestDispatcher rd = getServletContext().util.2 of the JSP 1. out. response).10. response.html Some JSP containers (as per section 8.getRequestDispatcher(uri).JSPs</title></head> <body><h4>Precompiling *.jsp?jsp_precompile The JSP page will not be executed. To precompile a JSP page.JSPs:</h4> <ul> <% HttpServletRequest req = new HttpServletRequestWrapper(request) { public String getQueryString() { // can be "jsp_precompile=true" return "jsp_precompile".24 Precompile JSP pages .*.2 specification) support the capability of precompiling a JSP page.jsp")) { out. }.http./javadetails/java−0414. If the container supports precompilation. JspWriter out. ServletException { Set set = pageContext.*"%> import="java. out.java. } } } %> <html><head><title>Precompiling *. if (rd == null) { throw new Error(uri +" − not found").hasNext().javax. } rd..rgagnon. iter.4.getResourcePaths(uripath).) { String uri = (String) iter.next(). for (Iterator iter = set.include(request.IOException"%> <%! private void compileAllJsps (PageContext pageContext.com/javadetails/.Set. } else if (uri.servlet. <%@ <%@ <%@ <%@ page page page page contentType="text/html. if (uri. access the page with a query string of ?jsp_precompile http://hostname.iterator().jsp.flush().servlet.util.write("<li>"+ uri +"</li>").Iterator. Here a JSP page that will scan the current directory (and subdirectories) to precompile all JSP found.endsWith("/")) { compileAllJsps(pageContext.charset=UTF−8" language="java" %> import="javax.java.HttpServletResponse response.io.24 Precompile JSP pages Current version of this HowTo : http://www.endsWith(". request. String uripath) throws IOException.

/javadetails/java−0508.. java. consider making a small donation to show your support for this Web site and its content.html I have a class public class Hello { public String say() { return "Hello"./javadetails/java−0417.rgagnon.File file. out..io. if (file.io. if (list.rgagnon.io.length.html <h1>Directories</h1> <ul> <% String root="c:/Repository/WebApplication/mydocs/javadoc/". Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10. String[] list = dir.compileAllJsps(pageContext.list(). response. Check for a JSPC command file. i++) { file = new java.com/javadetails/. BEAWLS).isDirectory()) { %> <li><a href="javadoc/<%=list[i]%>" target="_top"><%=list[i]%></a><br> <% } } } %> </ul> If you find this article useful. EAServer.com/javadetails/. i < list.File(root). 10.io. %> </ul> <h4>Done. java.</h4> </body> </html> NOTE: Many Application servers provide an utility to precompile JSP pages (ex.26 Use and share a class in JSP pages Current version of this HowTo : http://www.length > 0) { for (int i = 0.25 Get a list of directories for JSP Current version of this HowTo : http://www. "/").File(root + list[i]). } } and I need to use it in many JSP pages using 10.File dir = new java. req.25 Get a list of directories for JSP .

getOut().jsp.println("Hello").print(h. import javax.servlet. TLD configuration (in the WEB−INF/tlds as hello. <% Hello h = new Hello()..<%= say() %> They are many to achieve that goal : • Create a Java class with the method in it. public class HelloTag extends TagSupport { public int doStartTag() throws JspException { try { pageContext.tagext.tld) <taglib> <tag> <name>hello</name> <tagclass>test. } } the resulting class should go in the WEB−INF/class directory.*. import java.class file(s) and deploy the resulting JAR file via your webapp's WEB−INF/lib directory. deploy it via the webapp's WEB−INF/tld directory.say()). compile it.*.jsp. TAG source code TAG source code : package test.*.class file(s) in your webapp's WEB−INF/class directory. <ht:hello/> • Create the desired method at the top of the page and copy it from page to page <%! public static String say() { 10.say()). %> • Create a tag library for it. out. <% Hello h = new Hello().25 Get a list of directories for JSP .tld" %> . out. and deploy the resulting . } catch (IOException e) { } return SKIP_BODY.servlet.print(h. %> • Create a JAR file containing the .. import javax.HelloTag</tagclass> </tag> </taglib> and to use the tag <%@ taglib prefix="ht" uri="WEB−INF/tlds/hello.io.

consider making a small donation to show your support for this Web site and its content. place the method noted above in it.inc).27 Get the root dir of a web app .html The jsp:plugin tag will generate the right html code to load your Applet. In a Servlet String path = getServletContext. 10. and include it at the top of each JSP page <%@ include file="hello. If you find this article useful.28 Launch an applet from a JSP Current version of this HowTo : http://www.return "Hello"..getRealPath("/"). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10.html In a JSP String path = application. consider making a small donation to show your support for this Web site and its content.com/javadetails/.com/javadetails/. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10.inc" %> If you find this article useful.rgagnon. } %> • Create an "include file" (say hello./javadetails/java−0534.27 Get the root dir of a web app Current version of this HowTo : http://www.class" width="500" height="300"> <jsp:params> <jsp:param name="message" value="Hello. consider making a small donation to show your support for this Web site and its content./javadetails/java−0519. world"/> <jsp:param name="action" value="<%=AppletAction%>"/> </jsp:params> <jsp:fallback> <p> unable to start plugin </p> </jsp:fallback> </jsp:plugin> If you find this article useful.rgagnon. <jsp:plugin type="applet" code="TestApplet..getRealPath("/").

setHeader("Cache−Control".html InitialContext ctx = new InitialContext(). Object objref = ctx.setHeader("Pragma". See http://support. MyEJBHome home = (MyEJBHome) PortableRemoteObject. response..setDateHeader ("Expires"."no−cache").30 Call another EJB Current version of this HowTo : http://www.class)."no−cache")."no−cache")./javadetails/java−0384.29 Prevent caching of a JSP output Current version of this HowTo : http://www.setHeader("Pragma". 10.setHeader("Cache−Control". %> However. See also this HowTo and this one.microsoft. response.Written and compiled by Réal Gagnon ©1998−2006 [ home ] 10. %> <HTML> <HEAD> </HEAD> <BODY> my page body </BODY> <HEAD> <META HTTP−EQUIV="PRAGMA" CONTENT="NO−CACHE"> <META HTTP−EQUIV="Expires" CONTENT="−1"> </HEAD> </HTML> NOTE: Pragma: no−cache prevents caching only when used over a secure connection. response.lookup("MyPackage/MyEJB").rgagnon. −1).html You will need to set the appropriate HTTP header attributes.rgagnon."no−cache"). MyEJBHome. 10. cache handling is tricky with IE brower.com/kb/q222064/..setDateHeader ("Expires". Expires: −1 should do the job over unsecure conection. −1). response.29 Prevent caching of a JSP output ./javadetails/java−0590. By adding a second HEAD is supposed to solve the problem! <% response. <% response.com/javadetails/.com/javadetails/.narrow(objref.

jsp If you find this article useful.com/javadetails/.rgagnon.VersionInfo"%> .%> . 10.jar in the classpath. with weblogic.return (MyEJB) home. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10.getImplementationVersion()% or from the command line java −cp weblogic..internal. consider making a small donation to show your support for this Web site and its content../javadetails/java−0446.common.create().31 Keep java files generated from JSP (BEA WLS) Current version of this HowTo : http://www.com/javadetails/./javadetails/java−0447.xml to 'true' <jsp−descriptor> <jsp−param> <param−name> keepgenerated </param−name> <param−value> true </param−value> </jsp−param> </jsp−descriptor> or. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10..theOne().html <%@page import = "weblogic..html Set the 'keepgenerated' parameter in weblogic.jar weblogic. consider making a small donation to show your support for this Web site and its content..version Thanks to Frederic Close for the tip! If you find this article useful. <%VersionInfo serverVersion = VersionInfo.32 Get the server version (BEA WLS) Current version of this HowTo : http://www..rgagnon. %=serverVersion. java weblogic.jspc −keepgenerated Your.31 Keep java files generated from JSP (BEA WLS) .

33 Quickly create a Web application with BEA WLS . charset=ISO8859−1"> <%@ LANGUAGE="JScript" %> <% Response.) which accepts as a parameter an XML filename and transforms the passed filename using the XSL.ddinit.rgagnon. <META http−equiv="Content−Type" content="text/html..rgagnon. While it's possible to consult the data using a regular text editor. a sample web. 10. As an added bonus. follow these steps : 1.cmd 3.XML informations Current version of this HowTo : http://www.buffer = true.marathon. or do the transformation in Java. the css file.Main testapp If you find this article useful. Type this command : md testapp\WEB−INF 5.34 Nicely display WEB.com/javadetails/. Here the modified xsl file. See the sample output if your browser supports XML/XSL transformation. consider making a small donation to show your support for this Web site and its content.xsl"?> .html A web. Open a Shell window in %BEA%\user_projects\domains\[mydomain]\applications 2./javadetails/java−0449../javadetails/java−0451. Run this script : .0" encoding="UTF−8"?> <?xml−stylesheet type="text/xsl" href="tree−view.com/javadetails/.xml.. Type this command : md testapp 4.xml file contains informations about a web application hosted by a application server.. it maybe easier to use a special stylesheet to nicely format the data for easy browsing. run this program java weblogic. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10. the original XML filename is displayed (you will need this XSL)..\setenv. var xmlfile.html To create a web application without an EAR or WAR. Attach the xsl to the xml by adding this line to the xml file : <?xml version="1. for a hint see this How−to..WebInit testapp and that's all. I found a nice generic stylesheet on the Web and adapted it a little bit for that purpose. Run this program : java weblogic. To configure your new application.. Here an ASP page (yeah I know.10.33 Quickly create a Web application with BEA WLS Current version of this HowTo : http://www.marathon.

html 10. // get the PARAM=??? (assumes you have used GET request method!).rgagnon.QueryString('xmlfile'). try { oXSLProcessor.... oXML.xmlfile. // tell the XSL processor of the XML you want to have transformed. oXSLProcessor.MapPath('xmldoc/tree−view2.async = false .write(oXSLProcessor. oXSL = Server..MapPath(xmlfile).XSLTemplate').write ('The file ' +e.. oXSLProcessor = oXSLTemplate.validateOnParse = false .var var var var var var oXML.com/javadetails/. // create the XSL template and processor. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10. oXSLTemplate..input = oXML. // assume something like http://.load(SrcXML). oXSLTemplate.. oXML.. // we don't want to waste time validating the file oXSL. // place the ?xmlfile=xxx value into the XSL processor..CreateObject('Msxml2.CreateObject('Msxml2. oXSLProcessor..CreateObject('Msxml2.35 Reverse the CLASSLOADER order (BEA) Current version of this HowTo : http://www.load(SrcXSL).createProcessor.35 Reverse the CLASSLOADER order (BEA) .. oXML. oXSL. Response.addParameter('xmlfile'./javadetails/java−0551. // load the XML and XSL into your documents. oXSLTemplate = Server. oXML. } % If you find this article useful.reason )./docxml.resolveExternals = false .DOMDocument')..asp?xmlfile=myxml. // create documents for the XML and XSL.FreeThreadedDOMDocument').xsl'). SrcXSL = Server.. SrcXML.url + ' is not valid.transform .xml xmlfile = '' + Request. // get the source file (XML and XSL) paths SrcXML = Server.''). oXML = Server. oXSLProcessor.. } catch (e) { Response.stylesheet = oXSL. consider making a small donation to show your support for this Web site and its content. SrcXSL. Reason: ' + e..output).

com/javadetails/. Dependencies are also checked and recursively reloaded if changed. pages are checked on every request. Inc.xml configuration file.xml in the WEB−INF directory with the content : <!DOCTYPE weblogic−web−app PUBLIC "−//BEA Systems./javadetails/java−0562. at which WLS checks to see if JSP files have changed and need recompiling.html By default. If set to 0.com/servers/wls810/dtd/weblogic810−web−jar.com 10. This can be a problem.1//EN" "http://www. if you deployed an application in exploded mode. Written and compiled Réal Gagnon ©2007 real@rgagnon.//DTD Web Application 8.rgagnon.36 Detect change in JSP and recompile (BEA) Current version of this HowTo : http://www. BEA WLS doesn't recompile a modified JSP.bea..rgagnon.com http://www. in seconds.36 Detect change in JSP and recompile (BEA) .By default. if you have a JAR version in the server LIB directory and your web app requires an another version. If set to −1. Weblogic loads a class by asking the parent classloader to load the required class. ref : WebLogic Server Application Classloader Overview To make sure that your web app will use the JAR located in its WEB−INF\LIB. page checking and recompiling is disabled. create a file called weblogic. You change this behaviour by adding this directive in a weblogic.dtd"> <weblogic−web−app> <container−descriptor> <prefer−web−inf−classes>true</prefer−web−inf−classes> </container−descriptor> </weblogic−web−app> 10. <jsp−descriptor> <jsp−param> <param−name>page−check−seconds</param−name> <param−value>60</param−value> </jsp−param> </jsp−descriptor> page−check−seconds sets the interval.

* • news.rgagnon. Specialized server from vendors can be accessed to obtain support : • forums.2 * Read me * Current version of this HowTo : http://www.netbeans. try do use search on this site using Google.rgagnon. Be sure to search the forums first before asking a question because regular posters can be a little bit rude if you don't! Stack Overflow A site where you can ask question (not restricted to Java).1 java−language 11. Enter your search terms www.eclipse.html If you have difficulty to find what you are your are looking for.com Easerver and Powerbuilder • news. Participants are really cool.gmane. Usenet's newgroups are very useful too.4 (exampledepot.comp.11 Language 11.org Netbeans.com Web Submit search form If you can't find then you may want to look at these other sites : Java Glossary Many subjects covered in depth.org 11 Language . Also check out my Java links page. really innovative in the way it works.* groups on your favorite Usenet newserver.java.java. Check out the comp./javadetails/java−0290. look for the hierarchy gmane.lang. The Java Developers Almanac 1.com/javadetails/..com) Contains many code examples. Sun Developers Online Community You need to register first (free).sybase.

rgagnon. s.com/javadetails/.println("This class (FromWhere) is located at : " + u).getResource("").getCodeSource().org Mozilla • msnews.mozilla.3 Obtain from where a Class is loaded Current version of this HowTo : http://www.com BEA WebLogic 11.eclipse.class.out. • news.getClass(). } } The output >java LoadingFromWhere LoadingFromWhere is loaded from file:/C:/temp/ MyClass is loaded from file:/C:/temp/ Other technique (doesn't work with jar) public class FromWhere { public static void main(String args[]){ Class theClass = FromWhere.out.getName() + " is loaded from " + getClass(). System.getLocation()). } public void doit() { System.URL u = theClass.doit().bea.getClass().com Microsoft • news.getProtectionDomain().net./javadetails/java−0300.ibm.println(this.getProtectionDomain().microsoft.getClass(). java.getName() + " is loaded from " + this.Eclipse.3 Obtain from where a Class is loaded ..getLocation()).html public class LoadingFromWhere { public static void main(String args[]){ LoadingFromWhere s = new LoadingFromWhere(). } 11. need to ask for username first at http://www.php.out. } } class MyClass { MyClass() { System.org/newsgroups/register.getCodeSource().com IBM (WebSphere) • newsgroups.software.println (this. MyClass s = new MyClass().

} public void doit() { System./javadetails/java−0420.getStackTrace()[0].out..5 Get the current method name Current version of this HowTo : http://www./javadetails/java−0402. } } } 11.5 11.getName().lang. } } The output doit JDK1.println (new Exception().doit().4 Get the class name in a static method .. } public static class CurrentClassGetter extends SecurityManager { public String getClassName() { return getClassContext()[1].println ("I'm in " + new CurrentClassGetter().4 Get the class name in a static method Current version of this HowTo : http://www.out.4 public class MyTest { public static void main(String args[]) { new MyTest().rgagnon.rgagnon.getClassName() + " class").html JDK1.} The output > java FromWhere This class (FromWhere) is located at : file:/C:/temp/ See these related HowTo's : 1 2 11.com/javadetails/.getMethodName()).com/javadetails/. } public static void someStaticMethod() { System.String[] args) { someStaticMethod().html public class ClassFromStatic { public static void main(java.

getMethodName()).currentThread().println( Thread.getMethodName().5. new Test(). } public static void trace(StackTraceElement e[]) { boolean doNext = false.currentThread(). for (StackTraceElement s : e) { if (doNext) { System.currentThread().currentThread(). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11. } } } main doit doitagain main To get the calling method public class Test { public static void main(String args[]) { new Test().out.getStackTrace()).com/javadetails/. public class Test { public static void main(String args[]) { trace(Thread. } doNext = s.println(s. it is expensive since we need to create an Exception.getStackTrace()). } public void doit() { System./javadetails/java−0031.getStackTrace()[3]. } public void doit() { trace(Thread.out.getStackTrace()).rgagnon. If you find this article useful.getStackTrace()).6 Call a method dynamically (Reflection) .equals("getStackTrace"). consider making a small donation to show your support for this Web site and its content. } } See also this HowTo..currentThread(). doitagain().html 11. With JDK1. trace(Thread.While the above snippet is not bad.getMethodName()). a new technique is available. return.doit().6 Call a method dynamically (Reflection) Current version of this HowTo : http://www. } public void doitagain() { trace(Thread.doit().

params). // get the method Method thisMethod = thisClass. System.lang.*.getDeclaredMethod(aMethod. return input.6 Call a method dynamically (Reflection) . public class TestReflect { public static void main(String s[]) throws Exception{ String aClass.forName(aClass).newInstance().Date Method: toString Sat Aug 11 13:18:39 EDT 2007 Class : java.util.in)).lang.print(prompt). String aMethod.util. 11. // get an instance Object iClass = thisClass. Method2 ### Class : java. import java.println (thisMethod.out.*. Method1 ***".*. } /* Output examples: Class : Class1 Method: class1Method2 ### Class 1. Method2 ###".io.reflect.toString()). paramsObj). } } The next example calls a class method with 2 arguments : import java.reflect. // call the method System. // get the Class Class thisClass = Class.Date Method: getTime 1186852732140 */ } public static String lineInput (String prompt) throws IOException { BufferedReader input = new BufferedReader(new InputStreamReader(System. } } class Class1 { public String class1Method1() { return "*** Class 1. while (true) { aClass = lineInput("\nClass : ").invoke(iClass. } public String class1Method2() { return "### Class 1. aMethod = lineInput("Method: ").import java. // we assume that called methods have no argument Class params[] = {}. Object paramsObj[] = {}.readLine().out.

out. String.out.isAvailable("javax. new Object[] {new String("Hello")./javadetails/java−0422.invoke("Class1".println ("SAX " + (ClassUtils. Object i = c. try { 11.out.invoke(i.println ("Swing " + (ClassUtils. String s2) { System.com/javadetails/.jai.media.out.7 Detect if a package is available . new String("World")}). args). System.out. String aMethod. Class[] params.forName(aClass).out. Object[] args) throws Exception { Class c = Class.isJava3dAvailable()?"present":"absent")). System.println ("JAI " + (ClassUtils.println(s1 + " " + s2). /* output : Hello World */ } public static void invoke (String aClass. System.class.sax.JComponent")?"present":"absent")).xml.isAvailable("org.public class TestReflect { public static void main(String[] args) throws Exception { TestReflect.ImaginaryClass")?"present":"absent")). Method m = c.println ("ImaginaryClass " + (ClassUtils.class}.getDeclaredMethod(aMethod. /* output : Swing present JAI absent SAX present ImaginaryClass absent Java3d absent */ } public static boolean isAvailable(String className) { boolean isFound = false. } } class Class1 { public void say( String s1.ImageJAI")?"present":"absent")).rgagnon.swing.7 Detect if a package is available Current version of this HowTo : http://www.println ("Java3d " + (ClassUtils.isAvailable("imaginary.html public class ClassUtils { public static void main(String args[]) { System. } } 11. Object r = m. new Class[] {String.newInstance(). params).isAvailable("javax.. "say".XMLReader")?"present":"absent")). System.

forName(name). try { String name = "com.String".8 Create an object from a string Current version of this HowTo : http://www. Class [] classParm = null. but this time we are passing a parameter to the constructor and calling a method dynamically.8 Create an object from a string . return null. String methodName = "toLowerCase". Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11. consider making a small donation to show your support for this Web site and its content.lang.com/javadetails/. // get the constructor with one parameter java.reflect.printStackTrace().rgagnon.reflect. } catch (ClassNotFoundException e) { isFound = false.media.html import java. } return isFound..class}).Class. false.newInstance(objectParm).*.reflect.rgagnon.View"). } catch (Exception e) { e.getConstructor (new Class[] {String.lang.j3d. } public static boolean isJava3dAvailable() { return isAvailable("javax.forName(className.Constructor co = cl. } Another example.getConstructor(classParm).MyClass". return co. Class cl = Class.lang.lang. isFound = true. } } If you find this article useful. // get String Class Class cl = Class. null)./javadetails/java−0351.forName(name).Constructor constructor = cl. java. public class Test { public static void main(String args[]) { try { String name = "java. Object [] objectParm = null. // create an instance 11.

Class clazzType = field."thirdValue")). // the method has no argument Class arguments[] = new Class[] { }.reflect. // and finally return field.9 Get a variable value from the variable name Current version of this HowTo : http://www.html import java.getValueOf(test.out.println (ReflectUtils.getValueOf(test.toString(). 11.getMethod(methodName.lang.9 Get a variable value from the variable name .get(clazz). // else other type .invoke (invoker.getValueOf(test. // convert "REAL'S HOWTO" to "real's howto" Object result = objMethod. /* output : 3.out.com/javadetails/.getInt(clazz).equals("double")) return field. // get the method java.1416 42 Hello world */ } public static Object getValueOf(Object clazz. public class ReflectUtils { public static void main(String[] args) throws Exception{ TestClass test = new TestClass()..Method objMethod = cl. } catch (Exception e) { e.out. (Object[])arguments).*. String lookingForValue) throws Exception { Field field = clazz. } } } 11.getClass().println(result).lang.getField(lookingForValue).getType().equals("int")) return field.out.reflect.rgagnon.Object invoker = constructor.println (ReflectUtils.printStackTrace().newInstance (new Object[]{"REAL'S HOWTO"})./javadetails/java−0038.. System.toString(). else if (clazzType.."firstValue")). System. arguments)."secondValue")).getDouble(clazz). System.println (ReflectUtils. if (clazzType. System.

"value n" ).out. } public void myMethod(Object parms[]) { for (int i=0. public class Howto { public static void main(String args[]) { Howto howto = new Howto().10 Make methods that have unspecified number of parameters . i++) System. howto.println(arg).. parms) { for(Object parm:parms) { System. thirdValue = "Hello world". 11.length.myMethod ( new Object[] {"value 1".html You pass an array of Objects. new Integer(2).out. i < parms.10 Make methods that have unspecified number of parameters Current version of this HowTo : http://www. } 11./javadetails/java−0289.doit ( "value 1".com/javadetails/.. "value n"} ).println(parm). /* output : value 1 2 value n */ } public static void doit(Object . } } } public class TestIt { public static void main(String .1416..println(parms[i]).rgagnon. secondValue = 42.5.. we have VARARGS parameters so this not needed anymore! public class TestIt { public static void main(String args[]) { TestIt. args) { for(String arg:args) { System. new Integer(2).out.} } class TestClass public double public int public String } { firstValue = 3. } } NOTE : In JDK1..

11 Create a java source dynamically.createIt().todayClass + ":\n\n").println(\""+todayMillis+"\").runIt(). mtc.Main(baos.todaySource + " is bad. import java. String todayMillis = Long.").lang.source[0]). String todaySource = todayClass + ". if (mtc.getTime()).compile(source).util.*. } else System.} /* output : >java TestIt 1 2 3 how−to 1 2 3 how−to */ } 11. } public void createIt() { try { FileWriter aWriter = new FileWriter(todaySource. compile and call Current version of this HowTo : http://www.write(" System. aWriter."). import java. aWriter.compile(source). ByteArrayOutputStream baos= new ByteArrayOutputStream().io.html import java. } } public boolean compileIt() { String [] source = { new String(todaySource)}.close().3 then use // public static int com.write(" public void doit() {").flush().com/javadetails/.*.*.11 Create a java source dynamically. aWriter.indexOf("error")==−1).sun.Main. mtc. aWriter. compile and call .println(mtc. true).out.tools.out.javac.write(" }}\n"). return (baos.toString().java". new sun. } catch(Exception e){ e.javac. 11.write("public class "+ todayClass + "{").printStackTrace(). public static void main (String args[]){ MakeTodayClass mtc = new MakeTodayClass().println("Running " + mtc.tools.toString(today. public class MakeTodayClass { Date today = new Date().reflect./javadetails/java−0039. aWriter. String todayClass = "z_" + todayMillis..compileIt()) { System. // if using JDK >= 1. aWriter.out.rgagnon.

it is more appropriate to instanciate and called the main method of the other application. } } To call the above application from another public class Program1a { public static void main(String arg[]) { System.println("Hello from Program1b"). The dynamic version is little more tricky.out. } catch (Exception e) { e. public class Program1b { public static void main(String arg[]) { System. params). paramsObj). take this simple application : public class Program2 { public static void main(String arg[]) { System.start(). For example.12 Launch an application from another application .println("Hello from Program2"). } } } 11. Object iClass = thisClass.println("Hello from Program1a").forName(todayClass).. new Thread(){ public void run() { Program2.out.out. Method thisMethod = thisClass.execute("Program2"). thisMethod. Class thisClass = Class. } public void execute(String name) { 11.getDeclaredMethod("doit".main(new String[]{}). new Program1b().invoke(iClass.html While you can exec("java myaotherapp").12 Launch an application from another application Current version of this HowTo : http://www.rgagnon. } } The above example is used when the class is hard−coded.printStackTrace(). Object paramsObj[] = {}.com/javadetails/./javadetails/java−0394.} }.newInstance().} public void runIt() { try { Class params[] = {}.

printStackTrace().out.forName(name).java] public class Program2 { public static void main(String arg[]) { System.println("Hello from Program1a").13 Access the enclosing class from an inner class .main(new String[]{}).13 Access the enclosing class from an inner class Current version of this HowTo : http://www. invoke(null. /* output : 11.com/javadetails/.html public class TestIt { public static void main(String a[]){ new TestIt().out.doit(). t1.join().} }.println("Hello from Program2"). Thread t1 = new Thread(){ public void run() { Program2.println("Hello from Program2")..} } } Launch many programs using Thread and use join() to wait for the completion. } catch(Exception e){ e.println("Hello from Program2"). // Class params[] = new Class[] { args. System.class}.Class params[] = {String[]. params). try { Class. System. System.java] public class Program1a { public static void main(String arg[]) throws Exception{ System.out. } } [Program1a./javadetails/java−0037. System.println("Hello from Program2").out. [Program2. t1. } } The output : C:\>java Program1a Hello from Program1a Hello from Program2 Hello from Program2 Hello from Program2 Hello from Program2 Hello from Program1a 11. getDeclaredMethod("main". "world" }.out. new Object[] {new String[] {}}).println("Hello from Program1a").start(). // if you need parameters // String[] args = new String[] { "Hello".rgagnon.out.getClass() }).

} public void enclosingClassMethod(){ System.com/javadetails/.out.Hello world! */ } public void doit() { new InnerClass().enclosingClassMethod(). public static void main(String a[]){ new TestIt().doit().println("Hello world!"). /* output : Hello world! */ } public void doit() { new InnerClass()./javadetails/java−0425.sayHello().14 Access inner class from outside . } class InnerClass { public void sayHello() { TestIt.rgagnon.enclosingClassMethod().14 Access inner class from outside Current version of this HowTo : http://www. outer.sayHello().html public class TestIt { public static void main(String[] args) { Outer outer = new Outer(). } } } or public class TestIt { TestIt testItClass = this.hello(). } } } 11.. /* output : Hello from Inner() */ 11.out. } class InnerClass { public void sayHello() { testItClass.this.println("Hello world!"). } public void enclosingClassMethod(){ System.new Inner().

APPVERSION = "version 1... The CONSTANT class is included in the classpath.jdbc.println("Hello from Inner()"). } else { .SUCCESS) { .0".} } class Outer { public class Inner { public void hello(){ System.. consider making a small donation to show your support for this Web site and its content. integer NOTFOUND = 0./javadetails/java−0040. then to use a constant.driver.. } Via an interface This technique can be used if the constants are not really global but especially designed to be used in a specific application for example. Since the members of the class are defined as "static". To use a constant. } } } If you find this article useful.OracleDriver". An application−level class needs to implement the interface to be able to see the constant definitions. They are very generic by nature.[constant name] if (myMethod()==CONSTANT. integer FAILURE = −1. public class CONSTANT public static final public static final public static final } { integer SUCCESS = 1. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11. there is no need to instantiate the class.15 Use globally defined constants .. public interface APPCONSTANT public static final String public static final String public static final String } { APPNAME = "The Super APP".html Via a class This technique is useful for constants defined on a corporate level..com/javadetails/.out.. simply implement the interface public class TheAppFrame extends Frame implements APPCONSTANT { 11. simply use CONSTANT.15 Use globally defined constants Current version of this HowTo : http://www.rgagnon. DBDRIVER = "oracle.

0.out. constant name are always in CAPITALS.5 JDK1.. // instead of System. } } If you find this article useful. First the Queue state is saved to a file. The object needs 2 functions with these signatures private void writeObject(java.println(Math..println(Math.. NOTE: By convention.lang. System. it must implements the Serializable interface.16 Serialize an Object .out. // System..io.5 import statement can be used to import only static member from a class.rgagnon.. . JDK1. } . } NOTE : This is not considered as good practice (depending on who you are talking to!) to use an interface this way. import static java. 11. System.out. setTitle(APPNAME).Math..16 Serialize an Object Current version of this HowTo : http://www. public class DemoImport { public static void main(String[] args) { double x = 16.html To serialize an object.com/javadetails/.PI).println(abs(x)). we use a Vector to simulate a Queue. In the following snippet.abs(x)).println(PI)./javadetails/java−0042..ObjectOutputStream out) throws IOException private void readObject(java.io. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11. Many standard Java objects already implements the Serializable interface so there is almost nothing to do.ObjectInputStream in) throws IOException. consider making a small donation to show your support for this Web site and its content.out.TheAppFrame { .*. ClassNotFoundException.

Now the snippet read the file to reload the Queue from the data previously saved. return firstElement(). } void put(Object o) { addElement(o).put("element 1"). 11.toString()).Then rename main to main_serialize and main_reload to main and compile.println("serializing theQueue").out. public class Queue extends Vector { /* ** FIFO */ Queue() { super(). } catch (Exception e) { e.writeObject(theQueue). ObjectOutputStream oos = new ObjectOutputStream(fout).put("element 2"). oos. System. } public static void main(String args[]) { Queue theQueue. oos. theQueue.println("unserializing theQueue").io.dat"). // unserialize the Queue System. theQueue = new Queue(). } } public static void main_load(String args[]) { Queue theQueue. theQueue = new Queue().out. theQueue.util. theQueue. try { FileInputStream fin = new FileInputStream("thequeue.Vector. import java.close().out. ObjectInputStream ois = new ObjectInputStream(fin). theQueue = (Queue) ois. theQueue. try { FileOutputStream fout = new FileOutputStream("thequeue.16 Serialize an Object .readObject(). } Object peek() { if (isEmpty()) return null.put("element 4"). } Object get() { if (isEmpty()) return null.printStackTrace(). import java. ois.dat"). // serialize the Queue System.println(theQueue.*. return o.put("element 3"). removeElement(o). Object o = firstElement().close().

17 Serialize an Object over a socket . you use the ObjectInputStream. you have a class called Debug. That's because Java keeps objects sent in an internal cache and the old version will be taken in account instead of the new one. Without editing the source to remove the debugging codes. public class Debug { public static final boolean RELEASE = true.html From the client side.18 Easily remove my debugging code Current version of this HowTo : http://www.rgagnon.} catch (Exception e) { e. On the server side. but the execution time will be a little faster too by not making unnecessary test. In the development environment. The fix is to do an ObjectOutputStream. } } Note : See this How−to to serialize using XML format. there is no JAVA compiler directive to exclude certain source code parts from compilation.html Unlike a C/C++ compiler. the loading process will faster./javadetails/java−0130.readObject method.printStackTrace().sourceforge. you open a Socket and then oos = new ObjectOutputStream(socket..out. you can rely on the simple optimization that the JAVA compiler always do.println(theQueue. The technique is simple. the code in the if statement will not be included in the compilation. you will not see a change on the server side. } In your source.rgagnon.17 Serialize an Object over a socket Current version of this HowTo : http://www. If a if expression is always false.reset() before re−sending the object or open a new connection each time. oos. take a look at this open−source project.com/javadetails/.toString()). If you need to serialize and manipulate huge objects. } System. when you need some debugging codes. Not only the resulting class will be smaller..getOutputStream()).com/javadetails/. By making the release version of a class smaller. 11. 11.net. NOTE: If the OutputStream is kept open and you modify your object and resend it. joafip( java data object persistence in file ) at http://joafip./javadetails/java−0043. you included them in a if statement like 11.writeObject(someObject).

private OnlyOne(){} public static OnlyOne getInstance() { return one.release is always false. In the production environment.com/javadetails/. (System. If you find this article useful. the Debug class looks like this: public class Debug { public static final boolean RELEASE = false. } During compilation.print(".19 Have a singleton Current version of this HowTo : http://www.rgagnon.out.close() too for (int i=0. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11.out. public class TestOut { public TestOut() { } public static void main(String s[]) { System. the code will be present.19 Have a singleton . i++){ System.err. i <100000. } When compiling in that environment.if (Debug.close()./javadetails/java−0355.html A singleton is a class that can be instantiated only one time in a JVM. the debugging code will be absent from the class file since Debug.").RELEASE) { System. } } To use it OnlyOne myOne = OnlyOne. Repeated calls always return the same instance.println() will be present in your class but the output is disabled).RELEASE is always true.println("The value of i is " + i).out. consider making a small donation to show your support for this Web site and its content.} } } 11.getInstance().out. public class OnlyOne{ private static OnlyOne one = new OnlyOne(). // may want System. since Debug.. Another way is to simply close the out stream.

// generictostring{i=42.html A nice idea is to put this toString() into a base class so all the descendents inherit from it. consider making a small donation to show your support for this Web site and its content..21 Handle the List conflict Current version of this HowTo : http://www.util..util package and the List class is in the java. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11. If you find this article useful. int i = 42.com/javadetails/.println ("i = " + i + " j= " + j). } } 11.awt.com/javadetails/.rgagnon.awt.rgagnon. java. import java.*. public class generictostring { String hello = "world". hello=world} } 11..List(). j−−) System.List myAwtList = new java. import java..awt. i++.html You do it "à la C". .rgagnon.awt package. The solution is to fully qualify the name used when you reference the List class or interface. j=0..out.println(new generictostring().20 Multiple expressions in for loops Current version of this HowTo : http://www. i < 10..11./javadetails/java−0316.toString()).20 Multiple expressions in for loops ./javadetails/java−0372.22 Use a generic toString() Current version of this HowTo : http://www.. . So if both import are defined in your source you won't be able to compile properly because this will cause a name conflict./javadetails/java−0432.*.com/javadetails/. public class MultipleFor{ public static void main (String [] args){ for (int i=0.html The List interface is declared in the java.out. public static void main(String args []) { System.

getSuperclass().20 Multiple expressions in for loops .length.getSuperclass() != null ) toString( o. java.concat( list.1415.printStackTrace(). java.getSuperclass().2 for (int i = 0.util.Field[] f = cls. list ). } } if (cls.f[i]. Class clazz. i++) { try { h. return o.getDeclaredFields().get(this)).com import java.AccessibleObject. } return cls.getClass().toString()).util.lang. toString( o. but has some drawbacks: − it based on inheritance − an attribute of a subclass cannot overlap an attribute of a superclass (because of hashtable) So I changed your solution a bit: // @author Christian Ullenboom // @url http://java−tutor.getClass(). } catch ( IllegalAccessException e ) { e. class ToStringHelper { public static String toString( Object o ) { ArrayList list = new ArrayList().getSuperclass().printStackTrace(). AccessibleObject.reflect. your solution is fine.public String toString() { java. //jdk1. i++ ) { try { list.setAccessible( f. } private static void toString( Object o.Field.getName().Hashtable h = new java. i < f. private double d = 3. for ( int i = 0. } public class ToStringHelperTest extends Ober { 11. } } class Ober { int i = 123.lang. i < f. } } if ( clazz.setAccessible(f.length.getSuperclass() != null) { h. o. true).lang.Hashtable(). import java.put(f[i].getDeclaredFields().reflect.getName() + "=" + f[i].put("super". } } Christian Ullenboom wrote: Hi. true ).get(o) ).ArrayList.add( f[i].getName().toString() ). clazz.getName() + h. Class cls = getClass().AccessibleObject. import java. list ).reflect. } catch (IllegalAccessException e) { e. super.util.lang. ArrayList list ) { Field f[] = clazz.reflect.

it is possible to modify because a Date object is mutable and we have a reference to it. System. i=42.clone() .1415] } } If you find this article useful. public static void main(String args[]) { Ober t = new ToStringHelperTest(). Date d = mydata. } public void setdate(Date d) { aDate = d.com/javadetails/. consider making a small donation to show your support for this Web site and its content.println( ToStringHelper.rgagnon.out.out.getDate(). class MyData { private Date aDate.println(mydata./javadetails/java−0433.clone() Current version of this HowTo : http://www. The solution is to return a copy of aDate.println(d). System. MyData() { aDate = new Date().23 Use Object. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11. // Sat Apr 19 23:17:43 EDT 2003 // Wed Dec 31 19:00:01 EST 1969 // Wed Dec 31 19:00:01 EST 1969 which is no good } } Even if aDate is declared as private. System. } } public class DemoClone { public static void main(String args[]) { MyData mydata = new MyData().getDate()).setTime(1000). int i = 42. so even if you have reference to 11.out.println(d). System.String hello = "world". d. i=123. d=3.Date.toString(t) )..23 Use Object. // ToStringHelperTest[hello=world. import java.util.html Consider the following example.out. } public Date getDate() { return aDate.

Date d = mydata.clone(). any modification will be done on the copy. System. } public void setdate(Date d) { aDate = d.setTime(1000)..out. consider making a small donation to show your support for this Web site and its content.com/javadetails/.Date. } } public class DemoClone { public static void main(String args[]) { MyData mydata = new MyData(). . // Sat Apr 19 23:17:43 EDT 2003 // Wed Dec 31 19:00:01 EST 1969 // Sat Apr 19 23:17:43 EDT 2003 which is good } } If you find this article useful. MyData() { aDate = new Date(). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11.24 Static field. class MyData { private Date aDate. import java. System.util.println(d).println(d). } public Date getDate() { return (Date)aDate.24 Static field..println(mydata.out.html Consider the following class public class Foo { private static Bar b = new Bar().getDate().it. not the original. constructor and exception . d. constructor and exception Current version of this HowTo : http://www.rgagnon.. System.getDate()). } class Bar { public Bar ( ) throws Exception { } } 11.out./javadetails/java−0444.

println(j). col++ ) if( row == limit) break out. public class Foo { static Bar bar . consider making a small donation to show your support for this Web site and its content. consider making a small donation to show your support for this Web site and its content. } catch ( Exception e ) { e. This way. col< max. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11. row++ ) { for( int col=0. // output 5 } } If you find this article useful.25 Use a Label break . Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11.com/javadetails/. int j = 0. To solve this situation. out: { for( int row=0. you can almost simulate a GOTO! class JavaGoto { public static void main(String args[]) { int max = 10.25 Use a Label break Current version of this HowTo : http://www./javadetails/java−0500. } } } class Bar { public Bar ( ) throws Exception { } } If you find this article useful..html Labelled breaks allow breaking out of several levels of nested loops inside a pair of curly braces.out. row< max.printStackTrace() . } } System.rgagnon. j += 1. static { try { bar = new Bar() . int limit = 5.it will not compile because Bar() is declared to throw an exception. use a static block.

In the following example.27 Use a Hashtable Current version of this HowTo : http://www.html public class TestException { public static void main(String args[]) { try { throw new Exception("for no reason!").toString(). If you find this article useful. e.io. } catch (Exception e) { StringWriter sw = new StringWriter().io.printStackTrace().PrintWriter.. System.rgagnon. 11.out.StringWriter.Exception: for no reason! // at TestException.com/javadetails/.MAIN(TESTEXCEPTION. PrintWriter pw = new PrintWriter(sw). we retrieve a String array with a String.JAVA:7) } This can be useful if you want to format the StackTrace before showing it to the user.. With an arbitary key. } catch (Exception e) { e. public class TestException { public static void main(String args[]) { try { throw new Exception("for no reason!").LANG.rgagnon.printStackTrace(pw).26 Put printStackTrace() into a String .11. } } // output : // JAVA.println(sw. consider making a small donation to show your support for this Web site and its content.toUpperCase()).main(TestException./javadetails/java−0027.EXCEPTION: FOR NO REASON! // AT TESTEXCEPTION.26 Put printStackTrace() into a String Current version of this HowTo : http://www.java:8) } You redirect the StackTrace to a String with a StringWriter/PrintWriter : import java. import java./javadetails/java−0537.lang. } }2 // output : // java. you can retrieve easily an Object. Written and compiled by Réal Gagnon ©1998−2006 [ home ] 11.html Hashtables are very useful for maintaining a 1−to−1 relationship between Objects.com/javadetails/.

} 11.nextElement(). String[] array2 = {"X". int from. while( keys. Comparer comparer) { sort(a. " + resultArray[2]).28 Scan the content of a hashtable Current version of this HowTo : http://www.com/javadetails/.length < 2) return.28 Scan the content of a hashtable ."Y". } 11."C"}."B".length − 1.html [ArraySorter. Object[] b."3"}. a. Comparer comparer) { // No sort if (a == null || a. Hashtable arrays = new Hashtable().println (resultArray[0] + ".put("Array1".get(key). Object value = hash./javadetails/java−0008. j = to.rgagnon. null. array1).html Enumeration keys = hash.com/javadetails/.. array2). arrays. do { if (ascending) { while( (i < to) &(comparer."Z"}. arrays.rgagnon.hasMoreElements() ) { Object key = keys. array3).String[] array1 = {"A".compare( center. } /* ** Sort a and b. // sort using Quicksort int i = from. a[j]) < 0) ) j−−. while( (j > from) &(comparer. arrays. " + resultArray[1] + ".. Object center = a[ (from + to) / 2 ]. 11. comparer).keys()./javadetails/java−0032. System. boolean ascending.out.compare(center. int to. String[] resultArray = (String[])(arrays."2".1 public class ArraySorter { /* ** Sort in the same array */ public static void sort(Object[] a.get("Array2")).java] JDK1. String[] array3 = {"1".put("Array2". true.put("Array3".29 Sort an array Current version of this HowTo : http://www. a[i]) > 0) ) i++. using a as the reference */ public static void sort(Object[] a. 0.

java. a[i] = a[j].sort(args. b. } } if (i <= j) { i++. a[j] = temp. Object b) { return ((String)a). a[j]) > 0) ) j−−. i < args. } if (i < j) { // Swap elements Object temp = a[i].sort(myArray). j.java] public class testArraySorter { public static final ASCIIComparer asciiComparer = new ASCIIComparer(). to. while( (j > from) &(comparer. b[j] = temp.length. } } [testArraySorter. } public static interface Comparer { /** * The interface implementation should compare the two * objects and return an int using these rules: * if (a > b) return > 0. i.out. from. ascending. else { ArraySorter.Comparer { public int compare(Object a. 11. comparer). b[i] = b[j]. b. public static void main(String args[]) { if (args.compare(center. asciiComparer). * if (a == b) return 0. j−−.println("give me some args to sort")."bar". // Swap in b array if needed if (b != null) { temp = b[i].compareTo((String)b).28 Scan the content of a hashtable .Arrays.else { // Decending sort while( (i < to) &(comparer. } } while(i <= j). */ public int compare(Object a. // Sort the rest if (from < j) sort(a. } } } JDK1.length == 0) System. } } } public static class ASCIIComparer implements ArraySorter.compare( center.out.4 case−sensitive String[] myArray = new String[] {"foo".println(args[i]). if (i < to) sort(a. for (int i = 0. Object b). comparer). * if (a < b) return < 0. i++) { System."baz"}. ascending. a[i]) < 0) ) i++.util.

50. 2.length). System.println("Dimension 1: " + data.30 Initialize multidimensional array ..html class ArrayLength { public static void main(String args[]) { String[][] data = new String[3][4].00} }. 3.11.getInstance()).90. 0.com/javadetails/.20. {4. dim++.sort(myArray..length). java.40.80}./javadetails/java−0036.10. // expected output : // "This array has 2 dimensions" } public static int getDim(Object array ) { int dim=0.Collator. 4. 2.out. 1.rgagnon.00.println("This array has " + getDim(data) + " dimensions")..90. 0.getComponentType(). 3.80.70. 0. {2. 0. 6.com/javadetails/.isArray() ) { c = c.html Simply use braces./javadetails/java−0280.00.00}.20}. 8."Bar".70. java. Class c = array.println("Dimension 2: " + data[0]. System.getClass().60.50.31 Get array upperbound Current version of this HowTo : http://www. {0. 1.util."baz"}.out. 1.out. 2. {1.60}.50.20.10}.50.rgagnon.50. static double[][] Rates = { {0.50. } return( dim ). 4. 11..60. System.40. 1. } } 11.text. } } To get the number of dimensions : class ArrayDim { public static void main(String args[]) { String[][] data = new String[3][4].case−insensitive String[] myArray = new String[] {"foo".Arrays.30}. 0. 11.10. 5. {6. {0. 0.30 Initialize multidimensional array Current version of this HowTo : http://www. while( c.

y + 1). for ( int i = 0. z++. buf.toString(). } To transform back to String public String arrayToString(String s[].charAt(i) ) != −1 ) arraysize++.substring (0.32 Convert a String to an array Current version of this HowTo : http://www. i < buf.lastIndexOf(sep) ) { elements[z] = buf. } else if ( buf.length() ). the elements // are delimited by sep StringBuffer buf = new StringBuffer(s).html NOTE: This HowTo was designed for JDK 1.delete(0.. GUIRADO public String[] stringtoArray( String s. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11. Thanks to T. elements[z] = buf.toString().indexOf(sep). return elements.toString(). Starting with version 1. buf.com/javadetails/.toString().rgagnon. buf.substring(0. int arraysize = 1. buf.indexOf(sep) != −1 ) { y = buf.0.indexOf(buf.z++. int y. } } } } else { elements[0] = buf. consider making a small donation to show your support for this Web site and its content. See this HowTo.toString(). It's the String.toString().length() > 0 ) { if ( buf. if ( y != buf.indexOf(sep)). y ).toString().4.delete(0. z++.delete(0. i++ ) { if ( sep. buf. String sep) { int k.z = 0. } buf = null. } String [] elements = new String [arraysize]. the String class offers a better way to split a String into an Array. 11./javadetails/java−0368.toString().indexOf(sep) != −1 ) { while ( buf.toString().lastIndexOf(sep) == y ) { elements[z] = buf.toString(). if ( buf.2.indexOf(sep) + 1). String sep ) { // convert a String s to an Array. buf.length().If you find this article useful.toString().32 Convert a String to an array .split(regexp) method.

Array. If you find this article useful.println("The i array length is " + i.33 Sort in reverse order Current version of this HowTo : http://www.com/javadetails/.out. // 20 s = (String[])ArrayUtils.reflect.2 . int length = Array. System.isArray()) return null. you can use System.getLength(a).. // 6 } public static Object expand(Object a) { Class cl = a.println("The s array length is " + s. 4}.html Arrays cannot be resized dynamically.out.length.sort (myArray.reverseOrder()).. } 11.length). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11.expand(s). System.arraycopy() method to copy the content of an array to another one.length).getClass(). Collections.33 Sort in reverse order . i++) { result += sep + s[i] . } } return result. // 4 i = (int[])ArrayUtils.3. i < k.lang. public class ArrayUtils { public static void main (String arg[]) { String s[] = new String[20]..html Arrays.length). you use a Collection (Map.rgagnon.34 Resize an array Current version of this HowTo : http://www. import java.length).println("The s array length is " + s.out. // 30 int i[] = {1 .String result = ""./javadetails/java−0428. if (k > 0) { result = s[0].expand(i). System.com/javadetails/.rgagnon. System.. k = s. consider making a small donation to show your support for this Web site and its content. ArrayList. If you need to expand. for (int i= 1 .)..println("The i array length is " + i. if (!cl.out. 11. If you want a dynamic data structure with random access./javadetails/java−0431.

list. list.35 Dump array content Current version of this HowTo : http://www. ArrayList l2 = new ArrayList().. public class ArrayListDemo { public static void main (String arg[]) { ArrayListDemo x = new ArrayListDemo(). newLength). return newArray.add("c"). // a // 1 Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11. } public void doit1() { // single dimension ArrayList list = new ArrayList().size().add("a"). consider making a small donation to show your support for this Web site and its content. l2.doit2().int newLength = length + (length / 2).get(0))./javadetails/java−0465.getComponentType().html 11.out. l1.getClass().doit1(). // 2 System.size().add(l3). ArrayList l1 = new ArrayList(). int size = list.add("b"). newArray.arraycopy(a. l3.get(0)).util. 0. import java. x. // 50% more Class componentType = a.com/javadetails/.get(0).println("Array 2 " + ((ArrayList)list.ArrayList. // 3 int size2 = ((ArrayList)list. ArrayList is roughly equivalent to Vector. length). System.newInstance(componentType. x.add(l1). list. except that it is unsynchronized. Object newArray = Array.add(l2). 0.add("a"). list.size().out.println("Array 1 " +list. int size1 = list. System. // b } } If you find this article useful. } } But a better way is to use a Vector or an ArrayList.get(1)).add("b"). list. } public void doit2() { // multi dimensions ArrayList list = new ArrayList().35 Dump array content . ArrayList l3 = new ArrayList().rgagnon.

d] } } JDK1.html import java. "c". 0.println(java.5.util. {0. c. // output // [a.8]] } } You can also use the new shorthand notation to iterate through an array : public class Test { public static void main(String args[]) { String s[] = {"a".toString()).util. b.5. System. "b". public class Test { public static void main(String args[]) { String s[] = {"a". d] // [[0. consider making a small donation to show your support for this Web site and its content.Convert the array to a List and then convert to String. public class Test { public static void main(String args[]) { String s[] = {"a".println(java.util. 1.asList(s). 0.5.40.10. for (String element : s) System.50.60}. 0. "b".Arrays.36 Initialize a static array Current version of this HowTo : http://www. "d"}. [0.io.out.70.4.Arrays. import java. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11. 0.80} }.6].util.rgagnon.5 java.Arrays provides new ways to dump the content of an array.out.deepToString(d)). "c".com/javadetails/. It's even possible to dump muti−dimensional arrays. 0. 0. double d [][]= { {0.toString(s)).out.*.utils.println(element)./javadetails/java−0475.*. class InitStaticArray { 11.50. "c".println(java. System. 1. This technique works only with classes and not with primitives like int or double.36 Initialize a static array . } } If you find this article useful. "b".out. // output // [a. "d"}.50. 0. System. 0..7. "d"}.1. 0. c.Arrays. b. 0.

11.next().*. public static void main(String args[]) { Hashtable h = new Hashtable().iterator(). new Integer(3).keySet().length.println(element + " " + (String)h. array2[2]). // sorted keys output thanks to T. h."3"}. consider making a small donation to show your support for this Web site and its content. it = v."A"}. } } } If you find this article useful. h. GUIRADO for the tip! Vector v = new Vector(h.hasNext()) { String element = (String)it. new Integer(2).com/javadetails/. new Integer(4). }.put(array1[2].put(array1[0]. static { integerArray= new Integer[] { new Integer(1). static String[] array2 = {"1"./javadetails/java−0478.37 Sort an Hashtable Current version of this HowTo : http://www. public class HashtableTest { static String[] array1 = {"C"..util. while (it. i++){ System. array2[0]).get(element)). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11. } public static void main(String args[]) { for (int i=0. array2[1]).hasNext()) { String element = (String)it.static Integer[] integerArray. } System.out.out. import java. // unsorted keys output Iterator it = h. Collections.next().put(array1[1]. System."B".37 Sort an Hashtable .rgagnon.println(integerArray[i]). while (it.sort(v). i <integerArray. h.println("============").iterator().keySet()). We extract the keys and sort them.html Data in hashtable are not sorted.out."2".

add("hello"). Iterator<String> it = data..add("world")." compiler warning .. consider making a small donation to show your support for this Web site and its content. } /* output : A 3 C 1 B 2 ============ A 3 B 2 C 1 */ } } NOTE : When possible always use an HashMap instead of an Hashtable. data.java:22: warning: [unchecked] unchecked call to add(E) as a member of the raw type java.ArrayList data.System. } } } When compiling the above class.ArrayList data. while (it. Since Hashtable methods are synchronized they are slower than those in HashMap.println( element + " " + (String)h.println(s).38 Eliminate "[unchecked] unchecked call .. If you find this article useful.5) emits the following warnings : C:\ArrayListGeneric.out.util./javadetails/java−0521. ^ C:\ArrayListGeneric.com/javadetails/.next(). public class ArrayListGeneric { public static void main(String[] args) { ArrayList data = new ArrayList().38 Eliminate "[unchecked] unchecked call .util.add("hello")." compiler warning Current version of this HowTo : http://www. the compiler (jdk1.hasNext()) { String s = it... ^ 11.html import java.*. System.out.add("world"). See this Howto.rgagnon.java:21: warning: [unchecked] unchecked call to add(E) as a member of the raw type java.get(element)).util. data.iterator(). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11.

iterator(). data.C:\ArrayListGeneric. } } } A complete list of possible @SuppressWarnings parameters can be found at http://mindprod. import java.java:25: warning: [unchecked] unchecked conversion found : java.out. it's not bad idea to eliminate the warnings in production code.." compiler warning .next().util. data.. Iterator it = data.*.println(s).38 Eliminate "[unchecked] unchecked call .println(s). something like : import java. System.iterator(). Simply add the expected type (between < and >) after the class.add("hello").Iterator required: java. while (it. System. public class ArrayListGeneric { @SuppressWarnings("unchecked") public static void main(String[] args) { ArrayList data = new ArrayList()..hasNext()) { String s = it.iterator(). Iterator<String> it = data.util.6.util.add("hello").Iterator Iterator it = data.com/jgloss/annotations. data. } } } In JDK 1. 11.html. your class is ready to run but .util. while (it. it will be possible to insert a special annotation to suppress this kind of warning.*. ^ 3 WARNINGS Since there are only warnings. data.hasNext()) { String s = it.add("world"). public class ArrayListGeneric { public static void main(String[] args) { ArrayList<String> data = new ArrayList<String>().add("world").next()..out.

.lastName = l.firstName = f./javadetails/java−0520. String l) { this.html We want to sort a Collection of Person objects based on their LastName and Firstname. but it's not easy to see the details of those unsafe operations. [javac] Note: Recompile with −Xlint:unchecked for details. int deptComp = firstName. } public String getFirstName() { return firstName. you need to use the compilerarg tag in the javac task definition. public Person(String f.12 ANT When compiling with ANT. } public String toString() { return "[ firstname=" + firstName + ". To add the −Xlint. First the Person class class Person implements Comparable { String firstName. 12 ANT . lastName.rgagnon. Something like <target name="compile" description="Compile code"> <mkdir dir="${bin}"/> <mkdir dir="${lib}"/> <javac srcdir="${src}" destdir="${bin}" includeAntRuntime="no" classpathref="lib.debug}"> <compilerarg value="−Xlint:unchecked"/> </javac> </target> 12. } public String getLastName() { return lastName.getFirstName()).lastname=" + lastName + "]". you see the following output : [javac] Note: Some input files use unchecked or unsafe operations.path" debug="${compile.1 Sort on many fields Current version of this HowTo : http://www. } public int compareTo(Object obj) { Person emp = (Person) obj. this.com/javadetails/.compareTo(emp.

"Smith").iterator(). java. java. It's in there where we put the logic behind the sorting.add(one).util.out. names.getLastName().getFirstName()) : nameComp).util. "Lisa". i ++) { Person one = new Person(Smith[i].getLastName()) : deptComp). } // do the simpsons for(int i = 0 .println("BEFORE:"). Object obj2) { Person emp1 = (Person) obj1. "Homer". "Maggie" }. import java.Iterator.compareTo(emp2.return ((deptComp == 0) ? lastName.Collections. "Vincent". "Nathalie".length .util. return ((nameComp == 0) ? emp1.compareTo(emp2. } } then we need a class to implement the Comparable interface. i < Smith. java.length ."Simpsons"). return firstName.getFirstName()) &lastName. int nameComp = emp1. while (iter1.util.equals(emp. "Christine" }.util.Arrays.hasNext()) { 12 ANT . "Marge". class PersonComparator implements Comparator{ public int compare(Object obj1.add(one). // do the smith for(int i = 0 . } Person emp = (Person) obj. ArrayList names = new ArrayList(). public class TestSort { public static void main(String args[]) { String Smith[] = { "Real". String Simpsons[] = { "Bart". Iterator iter1 = names. java. } public boolean equals(Object obj) { if (!(obj instanceof Person)) { return false.List.util.equals(emp.getLastName()).Comparator. i < Simpsons.ArrayList.compareTo(emp.getLastName()). names. i ++) { Person one = new Person(Simpsons[i]. } System. Person emp2 = (Person) obj2.getFirstName(). } } To test it : import import import import import java.

io.lastname=Simpsons] [ firstname=Homer. as you can see depending on the Collection used. System.com/javadetails/.*.lastname=Simpsons] [ firstname=Homer.lastname=Simpsons] [ firstname=Christine.lastname=Smith] [ firstname=Vincent. consider making a small donation to show your support for this Web site and its content.iterator(). (a post by ""Ed") a post to demonstrate that depending on your need. } // now sort everything Collections. the execution time is very different! import java. we read a huge text file war−and−peace. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 12.lastname=Smith] [ firstname=Vincent.out. In the demonstration.sort(names.lastname=Simpsons] [ firstname=Marge.println("AFTER:"). class TestCollectionPerformance { 12.System.2 Optimize Collection usage ./javadetails/java−0553.out. choosing the right Collection implementation can be really important.util.lastname=Smith] [ firstname=Nathalie.lastname=Smith] [ firstname=Christine.lastname=Simpsons] [ firstname=Marge.lastname=Smith] [ firstname=Nathalie.out. } /* output : BEFORE: [ firstname=Real. while (iter2.lastname=Simpsons] [ firstname=Maggie.lastname=Smith] [ firstname=Bart.html From Usenet.lastname=Simpsons] [ firstname=Maggie.*. new PersonComparator()). Iterator iter2 = names.rgagnon.println(iter2. import java.next()).lastname=Simpsons] AFTER: [ firstname=Bart.lastname=Smith] [ firstname=Real.next())..lastname=Simpsons] [ firstname=Lisa.txt and then count the duplicated words.hasNext()) { System.2 Optimize Collection usage Current version of this HowTo : http://www.lastname=Smith] */ } } If you find this article useful.lastname=Simpsons] [ firstname=Lisa.println(iter1.

for (StringTokenizer i = new StringTokenizer(text). time = 100937ms.currentTimeMillis(). } catch (Throwable t) { System. • The ArrayList provides a collection backed by an array. words."). Using Using Using Using java. To make this happen.println(numDuplicatedWords + " duplicated words. and works best when elements are only added and removed at the end.private static String TEXT_BOOK_NAME = "war−and−peace. but it doesn't guarantee uniqueness. • A TreeSet keeps the elements in the collection in sorted order.util.readLine()) != null) { text.out. java. StringBuffer text = new StringBuffer().out. 12. if (listOfWords. • A Set offers a collection of unique elements. java.getName() + ". java. " + "Using " + listOfWords. words.getClass(). System. new HashSet<String>()). countDuplicateWords(text. } private static void countDuplicateWords(String text.txt".currentTimeMillis(). } } private static String readText() throws Throwable { BufferedReader reader = new BufferedReader(new FileReader(TEXT_BOOK_NAME)). time = " + (endTime − startTime) + "ms.TreeSet.nextToken().append(line + " ").toString(). i.hasMoreElements().util. new ArrayList<String>()). while ((line = reader.util. time = 453ms. long startTime = System.LinkedList.) { String word = i. new LinkedList<String>()). new TreeSet<String>()).contains(word)) { numDuplicatedWords++. // Read text into RAM countDuplicateWords(text.add(word).println(t.ArrayList. It provides quick indexed access to its elements. Collection<String> listOfWords) { int numDuplicatedWords = 0. • A List provides ordered access (by index).util.toString()).HashSet. • An HashSet maintains its collection in an unordered manner. time = 1031ms. } } Result : 522396 522396 522396 522396 duplicated duplicated duplicated duplicated words. } else { listOfWords. public static void main(String[] args) { try { String text = readText(). words.2 Optimize Collection usage . countDuplicateWords(text. } return text. time = 129375ms. String line = null. countDuplicateWords(text. ArrayList performs an internal move operation when an element is added or removed. } } long endTime = System.

html [Java 5] 12.4 Get a key from value with an HashMap Current version of this HowTo : http://www. ref : Sun's Java tech Tips Feb2003 12./javadetails/java−0564. while (it.iterator(). for (int i=0. Object[] sortedArray = sortedSet.com/javadetails/.3 Sort an HashMap Current version of this HowTo : http://www..rgagnon. not only at the end.indexOf(sortedArray[i])). Iterator it = ref. List yourMapValues = new ArrayList(yourMap. Sort based on the values HashMap yourMap = new HashMap(). // put some tuples in yourMap .keySet()).The LinkedList is best when add and remove operations happen anywhere.toArray(). But LinkedList's added flexibility comes at an added cost −− it results in much slower indexed operations. sortedArray[i]).next(). LinkList doesn't do an internal move operation for an element insert or remove.values()). List yourMapKeys = new ArrayList(yourMap.rgagnon. i<size. } To iterate your new Sorted Map Set ref = map.com/javadetails/./javadetails/java−0561. it just manipulates reference pointers.. i++) { map... int size = sortedArray.get(yourMapValues.html Sort based on the keys Map yourMap= new HashMap(). // put some tuples in yourMap . TreeSet sortedSet = new TreeSet(yourMapValues). // to hold the result HashMap map = new LinkedHashMap(). } 12. Map sortedMap = new TreeMap(yourMap).put (yourMapKeys.3 Sort an HashMap .hasNext()) { String file = (String)it.keySet()..length..

Iterator it = ref. list.equals("Barney")) { list. list. for(String s: list) { if (s. you decide to remove an item. while (it.keySet()){ if(hm.remove("Barney").Object value){ for(Object o:hm./javadetails/java−0619.get(o). import java.hasNext()) { Object o = it. if(o.keySet().add("Maggie"). list.add("Bart").5 Iterate a Collection and remove an item . } } return null.add("Marge"). public class Simple { public static void main(String args[]) { ArrayList<String> list = new ArrayList<String>().public static Object getKeyFromValue(HashMap hm.Object value){ Set ref = hm. } } /* output : Bart Lisa Marge Barney 12.html You get an exception if while scanning a Collection.5 Iterate a Collection and remove an item Current version of this HowTo : http://www. list.rgagnon. } [Java 1.iterator()..println(s). list.com/javadetails/.4] public static Object getKeyFromValue(HashMap hm. } } return null.ArrayList.add("Homer").add("Barney").add("Lisa").util.next().equals(value)) { return o. } 12. } System.equals(value)) { return o.out. list.

iter.main(Simple.checkForComodification(Unknown Source) at java.util. list.ConcurrentModificationException at java.rgagnon.add("Barney").Exception in thread "main" java.remove() import java.howto. import java.) { String s = iter. if (s. public class Simple { public static void main(String args[]) { ArrayList<String> list = new ArrayList<String>().ArrayList.iterator().html 12.AbstractList$Itr.add("Marge").next(Unknown Source) at com.util.Iterator.hasNext().rgagnon. } } for(String s: list) { System.out.6 Count distinct elements in a Vector .java:20) */ } The trick is to use an Iterator and remove the item with Iterator.out.add("Homer"). list.6 Count distinct elements in a Vector Current version of this HowTo : http://www./javadetails/java−0377.println(s).add("Bart")..add("Maggie"). for (Iterator<String> iter = list.equals("Barney")) { iter. list.add("Lisa"). list.util. list.remove().next().com/javadetails/.Simple.AbstractList$Itr. list.util. } } /* output : Bart Lisa Marge Homer Maggie Bart Lisa Marge Homer Maggie */ } 12.util.println(s). } else { System.

equals(v.size() .int position.size().E. return set. position+count). i++) { boolean isFound = false. j < v. i < source.size() .6 Count distinct elements in a Vector . set.G ** length is 3 ** from position 0 in each series we have A.• Submitted by T GUIRADO /** ** This method counts distinct elements from a given position in vector ** containing series of element. } catch ( Exception e ) {return 0.} } Submitted by bdobby2000 protected static int countDistinctElements ( Vector source.size().addElement( (String)source. consider making a small donation to show your support for this Web site and its content. for (int i = 0 . Written and compiled by Réal Gagnon ©1998−2005 [ home ] 12.C D. j++) { if ( source.elementAt(i) ).D.elementAt(j) ) ) { isFound = true. first position = 0 ** count = serie length ** ** ex : ** source = A.B.F D.size(). if ( i % count == position ) { if ( null != v ) { for (int j = 0 . int count ) throws IllegalArgumentException .G ** this method returns 2 because there are 3 distinct elements (C. } } try { return v. IndexOutOfBoundsException { List list = source.addAll(list).int count){ Vector v = null.F. j = v. Set set = new HashSet(). } i += count − position. int position. } } } if ( !isFound ) { if ( null == v ) v = new Vector(1. v.F. 1). ** Arguments : source = vector containing the vectors of elements ** position = which element to search. } If you find this article useful.FandG) **/ protected synchronized int countDistinctElements (Vector source.subList(position.D ** this method returns 2 because there are 2 distinct elements (A and D) ** from position 2 in each series we have C.elementAt(i).

configuration file are stored in properties file.com/javadetails/.5) Current version of this HowTo : http://www.out.props")).ArrayList theSimpsons = new java. props. 12.*.doit(). theSimpsons. for (String character: theSimpsons) { System. [Props file : user. class ReadProps { public static void main(String args[]) { ReadProps props = new ReadProps().add("Maggie"). theSimpsons.println(character).props] # this a comment ! this a comment too DBuser=anonymous DBpassword=DBlocation=bigone [JAVA code] import java.rgagnon. By convention.util.util.add("Bart").com/javadetails/. The structure is very similar to Windows INI file with except that there is no [.7 Dump the content of a Collection (JDK 1.rgagnon..7 Dump the content of a Collection (JDK 1.ArrayList().. theSimpsons.html In Java..io. theSimpsons.12.add("Barney").*./javadetails/java−0024.8 Use an INI file (properties) Current version of this HowTo : http://www.] section./javadetails/java−0628. p. theSimpsons.util.add("Homer"). } } } 12. import java.load(new FileInputStream("user.add("Marge").5) . theSimpsons. the filename extension is props or properties. } public void doit() { try{ Properties p = new Properties().html public class DumpCollection { public static void main(String[] args) { java.add("Lisa")..

println("user = " + p.props").put("DBpassword". To read a Properties file via an Applet.out.5) .out)."foo").load(url.println(e).list(System.props")).out. See also this HowTo.openStream()).load((new URL(getCodeBase().load(new FileInputStream("user.getProperty("DBlocation")).util.getSystemResource("/com/rgagnon/config/system.*.save(out. class WriteProps { public static void main(String args[]) { WriteProps props = new WriteProps().println(e). This can be useful to store user preferences for example. } catch (Exception e) { System. if (url != null) props. System.out). Note that the order is not preserved.props")).System.getProperty("DBuser")). load the Properties files this way : p. } } } This ok with an application but you can't do it from an Applet since you can't write directly on the server without some kind of a server−side process.out. p.println("password = " + p. import java. props. p. } catch (Exception e) { System. The modified data can be saved back to a file with the save method.openStream()).out. } } } Since the Properties class extends the Hashtable.*.list(System.doit(). import java.out. new Date().println("location = " + p. p.io.7 Dump the content of a Collection (JDK 1.props"). } public void doit() { try{ Properties p = new Properties(). "/* properties updated */"). "user. // modify a Property p. A Properties file stored in a JAR can be loaded this way : URL url = ClassLoader. System.getProperty("DBpassword")). // new Property p.put("today". FileOutputStream out = new FileOutputStream("user. this one and finally this one too! 12. we can manipulate the Properties through the get and put methods. p.toString()).

consider making a small donation to show your support for this Web site and its content.doitagain().Properties props = new java.util.out.openStream()). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 12. notation • To avoid having to type all the \u.FileInputStream fis = new java. String path = getClass(). java.File( path + "\\myprops. props.9 Load a properties file .substring(6).net.getSystemResource("myprops.Properties().FileInputStream (new java.12.util. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 12. h. System..doit().props")).com/javadetails/. java.rgagnon.html The rules are • Only use ISO Latin 1 characters in the Properties/ResourceBundle files • For other characters use the \u.io. getLocation(). If you find this article useful.props")..Properties props = new java.getCodeSource()../javadetails/java−0492.com/javadetails/.Properties().10 Accentuated characters in Properties/ResourceBundle file Current version of this HowTo : http://www.println(props).URL url = ClassLoader. notation manually.rgagnon.io./javadetails/java−0434.util. consider making a small donation to show your support for this Web site and its content.html public class LoadProps { public static void main(String args[]) throws Exception{ h.9 Load a properties file Current version of this HowTo : http://www.load(url.load(fis).. use the native2ascii tool (included with the SDK).println(props).util. props. } public void doit() throws Exception{ // properties in the classpath java.getProtectionDomain().toString()... } public void doitagain() throws Exception{ // properties in the startup directory java..io. } } If you find this article useful.out. System.

12. System.util..load(url.out.11 Have a multi−line value in a properties file Current version of this HowTo : http://www.Properties().html import java.java] public class Hello { public static void main(String args[]) throws Exception{ Hello h = new Hello().out.html You add a slash ("\") to continue the value on the next line. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 12.getSystemResource("props.com/javadetails/./javadetails/java−0503.com/javadetails/.URL url = ClassLoader.get("prop2")). consider making a small donation to show your support for this Web site and its content.util.*.12.net.Properties props = new java.openStream()). Take the following properties file : [props. } public void doit() throws Exception{ // properties in the classpath java.println("prop2 :\n " + props.11 Have a multi−line value in a properties file .util. System. } } The output >java Hello prop1 : first line of prop1 second line of prop1third line of prop1 prop2 : first line of prop2 second line of prop2 third line of prop2 If you find this article useful.rgagnon. java.println("prop1 :\n " + props.properties")..rgagnon.doit().properties] prop1=first line of prop1 \ second line of prop1\ third line of prop1 prop2=first line of prop2 \n \ second line of prop2 \n \ third line of prop2 A program to read the properties file : [Hello.get("prop1")).12 Use XML with Properties Current version of this HowTo : http://www./javadetails/java−0578. h. props.

loadFromXML(in). public static void main(String[] args){ new UsingReg().put("user"..dtd"> <properties> <comment>props updated</comment> <entry key="user">Bob</entry> <entry key="today">Thu Aug 09 22:45:11 EDT 2007</entry> </properties> 12.doit(). FileOutputStream out = new FileOutputStream("user.toString()).0" encoding="UTF−8"?> <!DOCTYPE properties SYSTEM "http://java.out). } } } The XML looks like <?xml version="1. p.com/javadetails/.Preferences.sun. p.import java. new Date().foo"."props updated"). "Bob").rgagnon.put("today".13 Use the Registry to store informations (Preferences API) .*. } public void doit() { try{ Properties p = new Properties(). FileInputStream in = new FileInputStream("user.props").4. class XMLProps { public static void main(String args[]) { new XMLProps(). 12.props").list(System.doit().com/dtd/properties. p.io.rgagnon. public class UsingReg { public static final String REALKEY= "com./javadetails/java−0421. p.13 Use the Registry to store informations (Preferences API) Current version of this HowTo : http://www. the Preferences class can use the Windows registry (on Unix. /* output : −− listing properties −− today=Thu Aug 09 22:45:11 EDT 2007 user=Bob */ } catch (Exception e) { e.storeToXML(out.printStackTrace().html With JDK1. a file is used) : import java. p.util.prefs.

/javadetails/java−0614. java.nextElement()).Collections.println(p).html Create a SortedProperties class which extend the regular Properties. With Unix (or Linux).rgagnon.hasMoreElements()){ keyList.foo p = Preferences. java.out. while(keysEnum.println(p). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 12. // read back from HKEY_CURRENT_USER System.Properties.out.userRoot().get(REALKEY.systemRoot(). Then override the keys() method to return the sorted keys instead.Vector.util. // read back from HKEY_LOCAL_MACHINE System. Vector keyList = new Vector(). "HKLM houston we have a problem")). p.put(REALKEY. "barbar").out. System. } Collections. "bar").14 Sort Properties when saving . import import import import java.} public void doit() { // write into HKCU\Software\Javasoft\Prefs\com.com/javadetails/.rgagnon. } } See also this How−to to access the Windows registry.keys(). 12.out.get(REALKEY.rgagnon.util.sort(keyList). */ @SuppressWarnings("unchecked") public synchronized Enumeration keys() { Enumeration keysEnum = super.put(REALKEY.println(p. p.util.util. a file is used and you may run into problems if you don't have write access in the default location for the Preferences storage. See this interesting article and these 2 bugs : 1 2 If you find this article useful. // write into HKLM\Software\Javasoft\Prefs\com. consider making a small donation to show your support for this Web site and its content.. called by the store method.14 Sort Properties when saving Current version of this HowTo : http://www. java. public class SortedProperties extends Properties { /** * Overrides. "HKCU houston we have a problem")). System.foo Preferences p = Preferences.Enumeration.println(p.add(keysEnum.

put("D".put("C".FileOutputStream("/temp/p.put("C". p. sp. "value C").elements().props"). sp.14 Sort Properties when saving . "value B"). p.store(fos.com 12. "regular props"). "value A").put("D". /* #sorted props #Thu Jul 31 22:34:06 EDT 2008 A=value A B=value B C=value C D=value D */ } } Written and compiled Réal Gagnon ©2007 real@rgagnon. /* #regular props #Thu Jul 31 22:21:51 EDT 2008 A=value A D=value D C=value C B=value B */ // same data but with sorted Properties SortedProperties sp = new SortedProperties().props"). sp. p. } /** * Demo */ public static void main(String[] args) throws Exception { // regular Properties Properties p = new Properties().com http://www. fos = new java.io.io. "value B"). sp. "value A"). sp.put("A".put("B".put("B". p. java. p.FileOutputStream("/temp/sp.return keyList.FileOutputStream fos = new java. "value D").rgagnon.store(fos. "sorted props"). "value C").io.put("A". "value D").

*.InetAddress. In Windows.net. is to launch an external utility and interpret the output. public class ListNetsEx { public static void main(String args[]) throws SocketException { Enumeration nets = NetworkInterface.IOException.6 java.util. } } JDK1. } static void displayInterfaceInformation(NetworkInterface netint) throws SocketException { System.list(nets)) displayInterfaceInformation(netint).getHardwareAddress())).getDisplayName()). Example for Windows import import import import java.out.5 or less One way.*.1 java−net 13.io. java.println("Display name: " + netint.net.getNetworkInterfaces().NetworkInterface import java.println("Hardware address: " + Arrays.. "ipconfig /all" will return all relevant network info for IP−bound adapters.io. 13 Networking .com/javadetails/.InputStream.2 Extract network card address Current version of this HowTo : http://www.html JDK1. in NT/2K/XP. java./javadetails/java−0369.out. "ifconfig" does something similar.toString(netint. java.rgagnon. System. Otherwise. for (NetworkInterface netint : Collections.net. import java.*. "arp −a" will return the MAC addresses of all adapters that have TCP/IP bound to them and have recently (default < 5 mins) resolved an IP address. In Linux.io.13 Networking 13.BufferedInputStream. import java.io. including the MAC address (displayed as "physical address"). without using JNI.

hasMoreTokens()) { String line = tokenizer. throw new IOException(e. } 13 Networking . try { localHost = InetAddress. // .trim().nextToken()... private final static String WIN_OSNAME = "Windows".util.printStackTrace().endsWith(localHost) && lastMacAddress != null) { return lastMacAddress.. } } private final static String winMacAddress(String ipConfigOutput) throws ParseException { String localHost = null. import java..name"). public final static String getMacAddress() throws IOException { String os = System. } catch(java.getRuntime().sun. // MAC OSX −−> else if(os. private final static String WIN_MACADDR_REG_EXP = "^[0−9A−F]{2}−[0−9A−F]{2}−[0−9A−F]{2}−[0−9A−F]{2}−[0−9A−F]{2}−[0−9A−F]{2}$".printStackTrace().net..getMessage(). // see if line contains IP address if (line. else { throw new IOException("OS not supported : " + os).. while(tokenizer. String lastMacAddress = null. throw new ParseException(ex.getMessage()).java.getRuntime().getHostAddress(). // Process p = Runtime. "\n").import java.getProperty("os. // // inspired by // http://forum. } // other OS left as an exercise ! // LINUX −−> else if (os. // ..StringTokenizer. } StringTokenizer tokenizer = new StringTokenizer(ipConfigOutput.text..UnknownHostException ex) { ex.startsWith("Linux")) { .startsWith("Mac OS X")) { . } } catch(ParseException e) { e. try { if (os.ParseException.com/thread. private final static String WIN_MACADDR_EXEC = "ipconfig /all".getLocalHost().exec("ifconfig").jspa?messageID=902023 // public final class NetworkUtils { private final static int MACADDR_LENGTH = 17. // Process p = Runtime.exec("ifconfig"). 0).startsWith(WIN_OSNAME)) { return winMacAddress(winIpConfigCommand()).

} } } 13.. } private final static boolean winIsMacAddress(String macAddressCandidate) { if (macAddressCandidate.out. } String outputText = buffer.matches(WIN_MACADDR_REG_EXP)) return false. 0). StringBuffer buffer= new StringBuffer().printStackTrace().// see if line contains MAC address int macAddressPosition = line. } private final static String winIpConfigCommand() throws IOException { Process p = Runtime. System.length() != MACADDR_LENGTH) return false. System.exec(WIN_MACADDR_EXEC).printStackTrace().append((char)c).getHostAddress()). return true.3 Get the workstation name/ip 13.trim().out. if(macAddressPosition <= 0) continue. if (c == −1) break. } public final static void main(String[] args) { try { System. throw ex. } } ParseException ex = new ParseException ("cannot read MAC address from [" + ipConfigOutput + "]".getInputStream()). for (.read().println(" OS : " + System. System. return outputText.indexOf(":").out. stdoutStream.getProperty("os.substring(macAddressPosition + 1). ex.3 Get the workstation name/ip .println(" IP/Localhost: " + InetAddress.) { int c = stdoutStream. } catch(Throwable t) { t.println(" MAC Address : " + getMacAddress()). if (winIsMacAddress(macAddressCandidate)) { lastMacAddress = macAddressCandidate.close().toString(). continue. InputStream stdoutStream = new BufferedInputStream(p. buffer.name")).println("MAC ADDRESS").getRuntime(). String macAddressCandidate = line.getLocalHost().out. if (!macAddressCandidate.

112 To list all the interfaces available on a workstation : [JDK1. public class IPAdress { public void getInterfaces (){ try { Enumeration e = NetworkInterface.hasMoreElements()){ InetAddress ip = (InetAddress) e2.net.io.println("Net interface: "+ni. } } 13.say().util.*.getHostName()).4] import import import import java. java..3 Get the workstation name/ip .142.Current version of this HowTo : http://www.getHostAddress()).println(i. java. // name System.out.*.out.println("IP address: "+ ip. while(e./javadetails/java−0390.getInetAddresses(). System.InetAddress i = java.rgagnon.out.getName()).} } } The output > java NetInfo realone/209.hasMoreElements()) { NetworkInterface ni = (NetworkInterface) e. System.72.out.printStackTrace().out.toString()). } } public static void main(String[] args) { IPAdress ip = new IPAdress().72.nio. System.nextElement().*.printStackTrace(). } } } catch (Exception e) { e.*. ip.142.getLocalHost().net. Enumeration e2 = ni.println(i).net.com/javadetails/.InetAddress.println(i.nextElement(). } public void say() { try { java. while (e2.html public class NetInfo { public static void main(String[] args) { new NetInfo().getInterfaces(). // IP address only } catch(Exception e){e.getNetworkInterfaces(). java. // name and IP address System.112 realone 209.

4 Once an application has performed network access (i.4 Find port number not in use Current version of this HowTo : http://www. Take a look at http://www.The output > java IPAdress Net interface: lo IP address: /127. and then get the value with System.0.4 Find port number not in use . parsing of xml document with external references.115.ttl (default: −1) Specified in java.147.html On Windows.1 Net interface: eth0 IP address: /194. 13.security to indicate the caching policy for successful 13.iana.4 or less] Pass it to your JVM as java −Dcomputername="%COMPUTERNAME%" .com/javadetails/.rgagnon. you have to restart the server since the the default setting JVM setting is to cache forever. There are 4 properties that can be used to override the default behaviour. "netstat −an" list the ports currently in use.254.68.69 Windows A "low−tech" way to get the computer name (can be useful if there is no network card) is to use the environment variable COMPUTERNAME (at least on modern Windows installation).getenv("COMPUTERNAME") To get the IP of a client from the server side.rgagnon.168. the DNS settings get cached so any subsequent operation will use the old settings even if the real settings have changed. [JDK1.com/javadetails/. etc). urlconnection./javadetails/java−0412.0. 13.5 Disable DNS caching Current version of this HowTo : http://www. To reset everything.. see this HowTo.getProperty("computername") [JDK1.org/assignments/port−numbers for a list of assigned numbers.5 or more] You can extract environment variable directly with System. networkaddress.../javadetails/java−0445.cache.20 Net interface: ppp0 IP address: /64.e..0.html JDK1.1 Net interface: eth1 IP address: /164.

A value of −1 indicates "cache forever".cache.cache.net. However. sun.net.sun.html As seen in this HowTo. but can be set as a command−line option. 13.security to indicate the caching policy for un−successful name lookups from the name service.6 Encode/Decode to/from Base64 .rgagnon. check the documentation at http://java.ttl.cache. However.cache. but can be set as a command−line option.inetaddr. networkaddress.tt It takes the same value and has the same meaning. A value of 0 indicates "never cache".ttl=60 networkaddress.negative. consider making a small donation to show your support for this Web site and its content.cache.cache.inetaddr.4 Net properties JDK1.Security.negative.cache. sun. the preferred way is to use the security property mentioned above.negative.ttl This is a sun private system property which corresponds to networkaddress. The value is specified as as integer to indicate the number of seconds to cache the successful lookup./javadetails/java−0598..inetaddr. But you can't set the value of networkaddress. You can set the required value in the java.com/javadetails/.name lookups from the name service. ref : J2SE 1.ttl (default: 10) Specified in java. the sun.6 Encode/Decode to/from Base64 Current version of this HowTo : http://www.misc.ttl=0 on the command line starting the JVM.net.ttl.setProperty("networkaddress.html#nct If you find this article useful.security. It takes the same value and has the same meaning. The value is specified as as integer to indicate the number of seconds to cache the failure for un−successful lookups. "0").security file located in %JRE%\lib\security networkaddress.ttl on the command line.BASE64Encoder/Decoder or creating your own Base64 handling are the best way to deal with Base64 encoding/decoding. So you can disable caching by adding −Dsun.com/javase/6/docs/technotes/guides/net/properties.cache. the preferred way is to use the security property mentioned above. Written and compiled by Réal Gagnon ©1998−2006 [ home ] 13.ttl" .6 The default value has changed for networkaddress.negative.ttl This is a sun private system property which corresponds to networkaddress.ttl=10 or set the value in your code with java. A value of −1 indicates "cache forever".

82.apache. System. "base64").decode(bais.internet. 82. 118. System. } public static byte[] decode(byte[] b) throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream(b). public class Codec { public static void main(String[] args) { try { String clearText = "Hello world". /* * output * realhowto base64 −> * [99.internet. 98. System. Download at http://commons.encode(test.write(b). byte res1[] = Base64Utils.close().out. 104. 71.getBytes()). int n = b64is. 104. byte[] res = new byte[n].println( java.toByteArray().println(new String(res1)). return baos. 86. return res. 118] * string −−> realhowto */ } } 13.org/codec/ import org.mail.toString(res1) + " string −−> " + new String(res2)).MimeUtility import javax. 104. System. InputStream b64is = MimeUtility. 100. Phonetic and URLs.Arrays. b64os. 104.codec. res.MimeUtility.apache.toString(res1)). 109. 109. 0. 98.out. Hex.7 Using javax.read(tmp). 13.binary. n).out.internet.out.io.arraycopy(tmp.encode(baos.util.commons. 118. 71.MimeUtility . OutputStream b64os = MimeUtility. byte res2[] = Base64Utils.mail.8 Using Apache Commons Codec Apache Commons Codec provides implementations of common encoders and decoders such as Base64.println(""). byte[] tmp = new byte[b. 86.decode(res1).Base64. 51.println(test + " base64 −> " + java. import java.*.length]. public class Base64Utils { public static byte[] encode(byte[] b) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream().util. 0.Arrays. } public static void main(String[] args) throws Exception { String test = "realhowto".mail.7 Using javax. 100. "Base64"). String encodedText. 118] * cmVhbGhvd3Rv * [99.13. System. 51. b64os.

javax.length == 0 ) { System.. } for( int i = 0.net/. import import import java.rgagnon. i < args. // // output : // Encoded: SGVsbG8gd29ybGQ= // Decoded:Hello world // } catch (Exception e) { e.sourceforge.com/javadetails/.println("Decoded:" + new String(Base64.out..getBytes())).out.length. 13.printStackTrace().getAttributes( hostName.naming.10 Lookup using MX record to validate mail server Current version of this HowTo : http://www.println( "Usage: MXLookup host [.. } } } 13.put("java.println( args[i] + " has " + doLookup( args[i] ) + " mail servers" ).*. env.encodeBase64(clearText.println(args[i] + " : " + e. } catch( Exception e ) { System. System.directory.err.initial".]" ).dns.factory.decodeBase64(encodedText. System.jndi. public class MXLookup { public static void main( String args[] ) { if( args.naming.out.DnsContextFactory"). i++ ) { try { System. 13.getMessage()). http://migbase64.html The best you can do to verify if an email address is real is to verify if there is a mail server registered to the domain name. javax.exit( 99 ).getBytes()))).out. new String[] { "MX" }). DirContext ictx = new InitialDirContext( env ).naming. System.println("Encoded: " + encodedText).sun.9 MiGBase64 . "com.Hashtable.// Base64 encodedText = new String(Base64. Attributes attrs = ictx./javadetails/java−0452.util.9 MiGBase64 • MiGBase64 is a very fast Base64 Codec written in Java.*. } } } static int doLookup( String hostName ) throws NamingException { Hashtable env = new Hashtable().

get( "MX" ). BUT (and the code below doesn't do this) they must be tried from lowest preference to highest to be absolutely correct. and the address is valid.com gets the message and when abc. Orbaker.com. it have typically been disabled on most mail servers. you create the SMTP envelope. if( attr == null ) return( 0 ).com MX 5 isp. } } The output is >java MXLookup rgagnon. Some recent servers don't even support this command as they are so frequently shut off.com realhowto. we know that the address is invalid. connect to the server.com rgagnon. The mail server at isp. their provider isp. but you don't put anything in it. Two (better method): Connect to the servers determined by your code snippet. more infos on that subject (thanks to him). There are other methods by which to validate an email address to a higher degree of than just the mail server. If abc. If an envelope cannot be built. there will be no errors for invalid addresses. If these are not checked in the proper order. you should get a 250 if the address is valid and a 550 if it isn't. it just accepts everything and relies on abc. return( attr.size() ).com agrees to set up a 'store and forward' scheme for their mail.9 MiGBase64 .com is not available. When it works. imagine that you connect to isp. If it is enabled. issue the HELO command and then send 'VRFY '.com has 1 mail servers realhowto. the message gets forwarded. To prevent bounces and other mail errors if their connection or server should be down.com : DNS name not found [response code 3] From T.com to sort out the bounces. then isp. Note that some servers (qmail) return 252 as a means of pleading the fifth. Others will return a failure even if the address exists but the command has been disables (although this is typically a 450 error). The MX records would look something like: MX 1 abc.com is again available.com Now.com and try to send a message.Attribute attr = attrs. Because this was abused by spammers. Once you have connected. The reason for connecting in order of preference: Imagine ABC company has an Internet conneciton and runs their own mail server for abc.com doesn't have the actual user list to know which addresses are valid. One: Use the VRFY command (see RFCs 821/2821). 13. This is the point at which most servers will give up the dirt on whether or not an address is valid.

charAt( 3 ) != '−' ) break.util.*.io. } return res. } private static void say( BufferedWriter wr.*. import import import import import java.DnsContextFactory"). } private static ArrayList getMX( String hostName ) throws NamingException { // Perform a DNS lookup for MX records in the domain Hashtable env = new Hashtable(). new String[] { "MX" }). DirContext ictx = new InitialDirContext( env ).sun. new String[] { "A" }).*.*. javax. Return them as an array list // NOTE: We SHOULD take the preference into account to be absolutely 13.size() == 0 )) { attrs = ictx. if( attr == null ) throw new NamingException ( "No match for name '" + hostName + "'" ). wr.jndi. Attribute attr = attrs. "com.*.parseInt( pfx ).naming. String text ) throws IOException { wr. Attributes attrs = ictx. try the machine itself if (( attr == null ) || ( attr. It is not possible to verify an address on a domain that uses a catch−all account as the catch account will receive the mail (it does.naming.net. javax. public class SMTP { private static int hear( BufferedReader in ) throws IOException { String line = null. while ( (line = in.factory.get( "A" ). int res = 0. } catch (Exception ex) { res = −1.write( text + "\r\n" ).naming. thus conclusively verifying a yahoo address is not possible. try { res = Integer. mean that someone will at least SEE the message). I suspect that hotmail is the same.directory. attr = attrs. however. java.flush(). } if ( line.initial".getAttributes ( hostName. 3 ). env.put("java. // if we don't have an MX record. return.readLine()) != null ) { String pfx = line.substring( 0.9 MiGBase64 .getAttributes( hostName. } // Huzzah! we have machines to try.dns.Yahoo appears to use a store and forward mechanism to its own internal servers. java.get( "MX" ).

while ( en. String f[] = x. if ( res != 250 ) throw new Exception( "Not ESMTP" ).getInputStream() ) ). // Now. This is why we REALLY ought // to take the preference into account. if ( res != 220 ) throw new Exception( "Invalid header" ). it's not valid if ( pos == −1 ) return false. for ( int mx = 0 .substring( 0.getOutputStream() ) ). say( wtr. 25 ). "MAIL res = hear( rdr if ( res != 250 sender address FROM: <tim@orbaker.size() .next(). (f[1]. it's a sure sign that it isn't if ( mxList. res. res = hear( rdr ). try { int res. BufferedWriter wtr = new BufferedWriter ( new OutputStreamWriter( skt. mx++ ) { boolean valid = false.size() == 0 ) return false.split( " " ).hasMore() ) { String x = (String) en.indexOf( '@' ).get( mx ). if ( f[1]. "EHLO orbaker. } public static boolean isAddressValid( String address ) { // Find the separator for the domain name int pos = address. try { mxList = getMX( domain ).add( f[1] )." ) ) f[1] = f[1]. NamingEnumeration en = attr. } // Just because we can send mail to the domain. } return res. // Isolate the domain/machine name and get a list of mail exchangers String domain = address. ArrayList mxList = null.// correct. res = hear( rdr ). 13. ArrayList res = new ArrayList(). do the SMTP validation. say( wtr. This is left as an exercise for anyone who cares. BufferedReader rdr = new BufferedReader ( new InputStreamReader( skt.substring( ++pos ). "RCPT TO: <" + address + ">" ). } catch (NamingException ex) { return false.9 MiGBase64 .endsWith( ". It *MAY* be possible for one MX to allow // a message [store and forwarder for example] and another [like // the actual mail server] to reject it.getAll(). // validate the say( wtr.length() − 1)). ) throw new Exception( "Sender rejected" ). but if we can't. ).com" ). doesn't mean that the // address is valid. Socket skt = new Socket( (String) mxList. // If the address does not contain an '@'. try each mail exchanger until we get // a positive acceptance. mx < mxList.com>" ).

close(). // Invalid address "nosuchaddress@yahoo. // be polite say( wtr.length . and later if (hasMX) { mailhost = f[1].Boerner has this comments about this HowTo : The method SMTP::getMX() in the second example throws an ArrayIndexOutOfBoundsException while getting the mailhost via the "A" attribute at: while ( en.me@nowhere.getID()). hear( rdr ). } catch (Exception ex) { // Do nothing but try next host } finally { if ( valid ) return true. if ( f[1]. } } S.com" // Failure of this method }. "QUIT" ). } public static void main( String args[] ) { String testData[] = { "tim@orbaker.9 MiGBase64 . hear( rdr ).out.next(). "RSET" ). ctr < testData.close().equals(attr.com". if ( res != 250 ) throw new Exception( "Address is not valid!" ). } return.hasMore() ) { String x = (String) en. rdr. } else { 13. say( wtr.split( " " ).println( testData[ ctr ] + " is valid? " + isAddressValid( testData[ ctr ] ) ).close(). ctr++ ) { System.net". wtr. I used something like: boolean hasMX = "MX". // Valid address "fail. so f. for ( int ctr = 0 .res = hear( rdr )." ) ) The "A" attribute returns only an address list.length is always 1. // Invalid domain name "arkham@bigmeanogre.spam".endsWith( ". String f[] = x. } } return false. skt. valid = true.

naming. } return res. DirContext ictx = new InitialDirContext( env ).sun. Return them as an array list // NOTE: We SHOULD take the preference into account to be absolutely // correct.put("java.directory. int res = 0.*. } private static ArrayList getMX( String hostName ) throws NamingException { // Perform a DNS lookup for MX records in the domain Hashtable env = new Hashtable().*. attr = attrs.readLine()) != null ) { String pfx = line. } catch (Exception ex) { res = −1. javax.hasMore() ) { 13. ArrayList res = new ArrayList().*. try { res = Integer.*. } if ( line. This is left as an exercise for anyone who cares.charAt( 3 ) != '−' ) break.DnsContextFactory").parseInt( pfx ). Attributes attrs = ictx.flush(). while ( en. new String[] { "A" }).mailhost = f[0]. } private static void say( BufferedWriter wr. "com.initial".9 MiGBase64 .substring( 0. 3 ). javax. return. new String[] { "MX" }).net.size() == 0 )) { attrs = ictx.factory.util. } Here my proposed fix : import import import import import java. // if we don't have an MX record. } // Huzzah! we have machines to try.io.get( "MX" ). NamingEnumeration en = attr.getAttributes( hostName.jndi. if( attr == null ) throw new NamingException ( "No match for name '" + hostName + "'" ). while ( (line = in.get( "A" ).naming.getAttributes ( hostName. java. public class SMTPMXLookup { private static int hear( BufferedReader in ) throws IOException { String line = null. Attribute attr = attrs.write( text + "\r\n" ).dns.naming. try the machine itself if (( attr == null ) || ( attr.*. String text ) throws IOException { wr. env.getAll(). java. wr.

} return res. mx &lt. else mailhost = f[1]. BufferedWriter wtr = new BufferedWriter ( new OutputStreamWriter( skt.length == 1) mailhost = f[0]. // Socket skt = new Socket( (String) mxList. // Now. mx++ ) { boolean valid = false. if ( res != 250 ) throw new Exception( "Not ESMTP" ).size() .getInputStream() ) ). res = hear( rdr ).indexOf( '@' ). 13. } // Just because we can send mail to the domain. do the SMTP validation. if ( res != 220 ) throw new Exception( "Invalid header" ). try each mail exchanger until we get // a positive acceptance.length() − 1)). // validate the sender address say( wtr. try { int res. "MAIL FROM: <tim@orbaker.9 MiGBase64 . This is why we REALLY ought // to take the preference into account. // THE fix ************* res.String mailhost. but if we can't. say( wtr. (f[1]. else if ( f[1]. try { mxList = getMX( domain ). for ( int mx = 0 .split( " " ). it's not valid if ( pos == −1 ) return false. // If the address does not contain an '@'. String f[] = x. BufferedReader rdr = new BufferedReader ( new InputStreamReader( skt.next().get( mx ). It *MAY* be possible for one MX to allow // a message [store and forwarder for example] and another [like // the actual mail server] to reject it. ArrayList mxList = null. res = hear( rdr ). "EHLO rgagnon.com" ). // THE fix ************* if (f. } catch (NamingException ex) { return false. doesn't mean that the // address is valid.getOutputStream() ) ).endsWith( ". it's a sure sign that it isn't if ( mxList.substring( ++pos ).com>" ). res = hear( rdr ).add( mailhost ). String x = (String) en.size() == 0 ) return false. 25 ). // Isolate the domain/machine name and get a list of mail exchangers String domain = address.substring( 0. mxList." ) ) mailhost = f[1]. } public static boolean isAddressValid( String address ) { // Find the separator for the domain name int pos = address.

} } return false. if ( res != 250 ) throw new Exception( "Address is not valid!" ). or system help reply.close(). say( wtr. is an anti spam attempt which denies service for the first time the triple of client.close().me@nowhere. say( wtr.out.if ( res != 250 ) throw new Exception( "Sender rejected" ). hear( rdr ).com".com" // Failure of this method }. // Invalid address "nosuchaddress@yahoo.printStackTrace(). Help message. wtr. sender and address reaches the smtp server. rdr. } public static void main( String args[] ) { String testData[] = { "real@rgagnon. "RSET" ). While using the code I noticed a problem with greylisting.println( testData[ ctr ] + " is valid? " + isAddressValid( testData[ ctr ] ) ). "RCPT TO: <" + address + ">" ).length . Donders.close(). } finally { if ( valid ) return true. Ready to start TLS. // Invalid domain name "arkham@bigmeanogre.spam". ctr++ ) { System. Greylisting will send back a temporary error (450) and therefore the address will be denied.net". } return. A list a possible SMTP Reply Codes: Code 211 214 220 Description System status. skt. res = hear( rdr ). "fail. ctr < testData. "QUIT" ). } catch (Exception ex) { // Do nothing but try next host ex.9 MiGBase64 . valid = true. 13. "you@acquisto. In this case it probably is better to accept the address as verified.net". because there is no better information available at that moment. hear( rdr ). } } A note sent by M. Greylisting. // be polite say( wtr. for ( int ctr = 0 . Domain service ready.

Encryption required for requested authentication mechanism. Authentication mechanism is too weak. Requested mail action not taken: mailbox unavailable.com/javadetails/. Command not implemented. Syntax error.io. queuing for node node started.*. Domain service not available. (ex. OK..rgagnon.221 250 251 252 253 354 355 421 432 450 451 452 453 454 458 459 500 501 502 503 504 521 530 534 538 550 551 552 553 554 Domain service closing transmission channel. Requested action not taken: mailbox name not allowed. OK.11 Send an email using the SMTP protocol Current version of this HowTo : http://www.net. User not local. will forward to forwardpath.. User not local. OK.g. please try forwardpath. no messages waiting for node node. Unable to queue messages for node node. messages pending messages for node node started. Requested action not taken: mailbox unavailable. info is not local). Cannot VRFY user (e. import java. Command not recognized: command. Command parameter not implemented. A password transition is needed. closing transmission channel.*. You have no mail. no parameters allowed. try to use the JavaMail API (see section Mail(Javamail)).html SMTP is the protocol used to send an email. Syntax error. mailbox busy) Requested action aborted: local error in processing. Encryption required for requested authentication mechanism. Start mail input./javadetails/java−0079. but will take message for this user and attempt delivery.. Node node not allowed: reason. public class SendElvisMail { 13. Bad sequence of commands. end with . completed. RFC0821 13. Encryption required for requested authentication mechanism.11 Send an email using the SMTP protocol . TLS not available due to temporary reason. Unless you have a good reason. Requested mail action aborted: exceeded storage allocation. Must issue a STARTTLS command first. Transaction failed. pending messages for node node started. import java. Requested mail action okay. Unable to process ATRN request now Requested action not taken: insufficient system storage. Octet−offset is the transaction offset. OK. Article on how SMTP works. Machine does not accept mail.

SendElvisMail mail. } catch (Exception e) { e. "HELO theWorld").write(s + "\n"). "\n.flush().11 Send an email using the SMTP protocol . send(in. } public void sendMail(String mailServer.sendMail(s[0].printStackTrace(). send(out. send(out. out. out.println(s). send(in.out.rock>").ca // SendElvisMail t = new SendElvisMail(). "RCPT TO: " + recipient). "Subject: In the ghetto"). "I'm alive.out. "From: Elvis Presley <Elvis. "QUIT"). s = in. "\n"). // warning : some mail server validate the sender address // in the MAIL FROm command.Presley@jailhouse.write(s + "\n"). System.out.readLine(). out.close(). // message body send(out. t. } 13. "DATA").printStackTrace().Presley@jailhouse. } } public void send(BufferedWriter out. send(in.qc.println(s). s. 25). String recipient) { try { Socket s = new Socket(mailServer. } catch (Exception e) { e. out. System. BufferedReader in = new BufferedReader (new InputStreamReader(s.flush(). out.\n"). put your real address here send(in. } } public void send(BufferedReader in. } catch (Exception e) { e. System. "8859_1")). String s) { try { out. "MAIL FROM: <Elvis. out. Help me!").getOutputStream(). BufferedWriter out = new BufferedWriter (new OutputStreamWriter(s.println(s). send(out. out.public static void main(String s[]) { // // Send fake mail from Elvis Presley // // SendElvisMail [mail server] [recipient address] // mail server can be hostname or IP address // // ex. BufferedWriter out. send(in. "8859_1")).getInputStream(). String s) { try { out. send (out.rock>").printStackTrace(). s[1]).company.com myFriend@somewhere.

out). } } catch (Exception e) { e. receive(in)./javadetails/java−0080.flush(). out.html import java.out. receive(in). String pass) throws IOException { Socket s = new Socket(server. 110).getOutputStream())). } private String receive(BufferedReader in) throws IOException { return in. s[2]). String user. BufferedReader in = new BufferedReader( new InputStreamReader(s. } 13. "PASS " + pass)."). String s) throws IOException { out.} } 13. receive(in).").12 Check if there is mail waiting . } else { System. BufferedWriter out = new BufferedWriter( new OutputStreamWriter(s.com/javadetails/.net. public class CheckMail { public static void main(String s[]) { // // CheckMail [mailServer] [user] [password] // try { CheckMail t = new CheckMail(). send(out. int i = t. } private int checkMyMail (String server.12 Check if there is mail waiting Current version of this HowTo : http://www. s[1].println("No mail waiting.checkMyMail(s[0].write(s+"\n"). import java.*. send(out.readLine(). } } private void send(BufferedWriter out.getInputStream())). return getNumberOfMessages(in. "USER " + user). if (i==0) { System.printStackTrace().rgagnon.io..*.out.println ("There " + (i==1?"is " :"are ") + i + " message" +(i==1?"":"s")+ " waiting.

getInputStream())). System.out. import java. out.println("Connect to " + arg[0] + ":110").*.13 Receive email Current version of this HowTo : http://www. arg[1]. arg[2]).println("No mail waiting. while((s = receive(in)) != null) { if (!(s.getOutputStream())). j <= i. int i = mail.get(in.*.println("*****").out.13 Receive email .check(in. j++) { String msg = mail. System.html import java. } // // If the mail was removed from the server // (see getMail()) then we must COMMIT with // the "QUIT" command : // send(out.println(msg). send(out. BufferedReader in = new BufferedReader( new InputStreamReader(s.out.out. DisplayMail mail = new DisplayMail().io. } else { for (int j=1. "QUIT"). out. 13. System. BufferedWriter out) throws IOException { int i = 0. 110). "LIST").equals(".com/javadetails/. BufferedWriter out = new BufferedWriter( new OutputStreamWriter(s. Socket s = new Socket(arg[0]. } } 13."))) { i++. mail. if (i==0) { System.").out. } else return i.println("*****"). } return 0.out)./javadetails/java−0081.rgagnon.. j). String s. public class DisplayMail { public static void main(String arg[]) { // // usage : // DisplayMail [mailServer] [user] [password] // (will not delete mail on the server) // try { // connect on port 110 (POP3) System.login(in. receive(in).public int getNumberOfMessages (BufferedReader in.net.

printStackTrace(). String user. receive(in). "RETR "+i). // receive(in). } // // To remove the mail on the server : // send(out. out. 13. } private void send(BufferedWriter out.// } } catch (Exception e) { e. String t = "". BufferedWriter out) throws IOException { int i = 0.readLine().flush(). send(out.println(s). // return t. } private String receive(BufferedReader in) throws IOException { String s = in. "HELO theWorld"). } private int check (BufferedReader in. "DELE "+i).13 Receive email . } } public String get (BufferedReader in. send(out. } public int getNumberOfMessages (BufferedReader in. String s) throws IOException { System. System. String pass) throws IOException { receive(in). "USER " + user). out. BufferedWriter out) throws IOException { return getNumberOfMessages(in. while (((s = in.out. receive(in). out). return s.println(s).readLine()) != null) )))) { t += s + "\n". } private void login (BufferedReader in. "PASS " + pass). BufferedWriter out.out. int i) throws IOException { String s = "". BufferedWriter out. receive(in). send(out.write(s+"\n"). send(out.

"8859_1")).equals(". String boundary = "DataSeparatorString". } public void sendMail(String mailServer. BufferedReader in = new BufferedReader (new InputStreamReader(s.*.getOutputStream()."))) { i++. 25). } } return 0.sendMail(s[0]. The attachment is encodded using the BASE64 algorithm. while((s = receive(in)) != null) { if (!(s. Elvis is sending a GIF of his old Gumby friend.rgagnon. "8859_1")). receive(in). } else { return i. public static void main(String s[]) { /* ** TestMailMIME [server] [recipient] */ TestMailMIME t = new TestMailMIME(). static DataOutputStream out.String s. try { Socket s = new Socket(mailServer.out. BufferedWriter out = new BufferedWriter (new OutputStreamWriter(s.io. static DataInputStream in.14 Send email with an attachment ./javadetails/java−0083. s[1]). we are sending as attachment this image : import java.com/javadetails/.gif".println("Send mail with attached file "). static Socket socket.*. */ String FileName = "gumby.. send(out. String recipient) { System. In this example. static PrintStream prout.html In this example. /* Name of file to be sent.14 Send email with an attachment Current version of this HowTo : http://www.getInputStream(). t. 13.net. } } 13. public class TestMailMIME { static int SMTPport = 25. "LIST"). import java.

BufferedWriter out. "QUIT"). out. out. "MAIL FROM: "). String s) { try { out. sendln(out.println(s). boundary=\"" + boundary +"\"").out. "RCPT TO: <" + recipient + ">" ). "MIME−Version: 1. "Content−Disposition: attachment. "From: Elvis Presley <Elvis. } catch (Exception e) { 13. repeat // sendln(in. "RCPT TO: <" + recipient2 + ">" ). "\r\n−−" + boundary). s = in. sendln (out.").// here you are supposed to send your username sendln(in.readLine().out. "\r\n−−" + boundary). "\r\n−−" + boundary ). sendln(out. sendln(out.". "I'm alive. name="+FileName). // System. sendln(in.write(s + "\r\n"). // thanks to P−Y Colle for the tip! sendln(in. // to have more than one recipient. "Content−Type:image/gif. out. String s) { try { out.. "RCPT TO: <" + recipient3 + ">" ). // send the GIF sendln(out. out. } catch (Exception e) { e. out. out.encode(FileName.Presley@jailhouse. "Content−Type: multipart/mixed. "\r\n\r\n−−" + boundary + "−−\r\n"). sendln (out. sendln(in. out). sendln(out. MIMEBase64.write(s + "\r\n"). } } public void sendln(BufferedWriter out. s.out.println(s). "HELO theWorld").close(). sendln(in. out. // etc. "DATA"). out. body "Content−Type: text/plain. sendln(out. System. // warning : some mail server validate the sender address // in the MAIL FROM command. sendln(out.0"). } } public void sendln(BufferedReader in.flush(). charset=\"us−ascii\"\r\n").printStackTrace(). out. put your real address here sendln(in. } catch (Exception e) { e. "Content−transfer−encoding: base64\r\n"). sendln(out. // sendln(in. // System.println(s).14 Send email with an attachment .filename=\""+FileName+"\"").printStackTrace(). sendln(out. Help me!\r\n\r\n"). // Send the sendln(out..rock>"). out. sendln(out. "Subject: remember me").flush().

The character "m" has the decimal value of 109 The character "e" has the decimal value of 101 The character "n" has the decimal value of 110 When converted to binary the string looks like this : m e n 01101101 01100101 01101110 These three "8−bits" are concatenated to make a 24 bit stream 011011010110010101101110 This 24 bit stream is then split up into 4 6−bit sections 011011 010110 010101 101110 We now have 4 values. To encode one or two then. With a text string. we use the special character "=" to pad until 4 base64 characters is reached. let's say "men" is encoded this is what happens : The text string is converted into its US−ASCII value.io. when represented in binary form.printStackTrace(). } } } And the MIMEBase64 class import java. These binary values are converted to decimal form 27 22 21 46 And the corresponding Base64 character are : b W V u The encoding is always on a three characters basis (to have a set of 4 Base64 characters). is 100110.*. encode "me" 01101101 01100101 0110110101100101 011011 010110 0101 111111 011011 010110 010100 b W U b W U so "bWU=" (AND to fill the missing bits) = ("=" is the padding character) is the base64 equivalent.e.14 Send email with an attachment . public class MIMEBase64 { /* Base64 uses a 65 character subset of US−ASCII. allowing 6 bits for each character so the character "m" with a Base64 value of 38. ex. 13.

"d"."K". buf[3] = (byte)( bytes[i+2] &0x3F)."u"."U". buf[2]= (byte)(((b[i+1] &0x0F)<< 2)|(b[i+2]>> 6)). "Q"."E". /* The above code can be written in more "optimized" way."D". BaseTable[buf[2]]). byte buf[] = new byte[4]."c". buf[3]= (byte)(b[i+2] &0x3F)."j"."1"."V". while ( i < k ) { buf[0] = (byte)(( bytes[i] &0xFC) >> 2)."T". send(out."8"."h"."Z"."v"."k"."p". "w". Tordera for the tip! buf[0]= (byte)(b[i] >> 2)."J"."l". // we are doing 3 bytes at a time 0. buf[2] = (byte)(((bytes[i+1] &0x0F) << 2) | ((bytes[i+2] &0xC0) >> 6)). int n = fin. send(out."S".read(bytes)."R"."x"."y"."t"."+". BufferedWriter out) { try { File f = new File(filename).length())]. */ if ((linelength += 4) >= 76) { 13."f". BaseTable[buf[0]])."N"."i". send(out."G"."7". // how 3 bytes groups? n % 3.encode "m" 01101101 011011 01 111111 011011 010000 b Q (AND to fill the missing bits) = = (two paddings are added) Finally. send(out."2"."r"."W"."b"."6". // read the entire file into the byte array byte bytes[] = new byte[(int)(f. buf[1] = (byte)(((bytes[i] &0x03) << 4) | ((bytes[i+1] &0xF0) >> 4))."P"."m"."z".14 Send email with an attachment . "g"."n".BaseTable[buf[0]]+BaseTable[buf[1]]+ BaseTable[buf[2]]+BaseTable[buf[3]]). buf[1]= (byte)(((b[i] &0x03) << 4)|(b[i+1]>> 4)). send(out."s"."H"."B"."5". Thanks to J."/" }."M"."o"."a". FileInputStream fin = new FileInputStream(filename). // current linelength 0. // index // do the 3−bytes groups .. public static void encode(String filename."4". MIME specifies that lines are 76 characters wide maximum."O".."X"."F". Harder to understand but more compact. int int int int int n3byt nrest k linelength i = = = = = // no bytes to encode!?! // array of base64 characters n / 3."I". BaseTable[buf[3]])."L"."C"."Y". BaseTable[buf[1]]). */ static String BaseTable[] = { "A"."9". if (n < 1) return. // the remaining bytes from the grouping n3byt * 3."0"."3"."q"."e".

} } public static void send(BufferedWriter out.txt". BaseTable[buf[0]]). "="). } out. String FileName2 = "gumby. send(out.. buf[1] = (byte)(((bytes[k] &0x03) << 4) | ((bytes[k+1] &0xF0) >> 4)).printStackTrace(). */ String FileName1 = "gumby. } catch (Exception e) { e. send(out.gif". if (nrest==2) { // 2 bytes left buf[0] = (byte)(( bytes[k] &0xFC) >> 2). "=").print(s)..flush(). BaseTable[buf[1]]). 13.. . } // deals with with the padding . BaseTable[buf[2]]). String s) { try { out. Claerman for the bug fix here! if (nrest==2) { send(out.write(s). linelength = 0. buf[1] = (byte)((bytes[k] &0x03) << 4). buf[2] = (byte)(( bytes[k+1] &0x0F) << 2). /* Name of files to be sent. } catch (Exception e) { e. } send(out.. // Thanks to R. } if (nrest > 0) { // send the padding if ((linelength += 4) >= 76) send(out.printStackTrace(). "\r\n").send(out. System. } else if (nrest==1) { // 1 byte left buf[0] = (byte)((bytes[k] &0xFC) >> 2)..out.. } i += 3.14 Send email with an attachment . } else { send(out. "\r\n"). } } } If Elvis want to send a GIF and a text file about his Gumby old friend then he would change his sendMail() for something like this .

"\r\n\r\n−−" + boundary + "−−\r\n"). out.getInputStream(). charset=\"us−ascii\"\r\n").encode(FileName2."). "MAIL FROM: <real@gagnon. out. "8859_1")).printStackTrace().com>"). "8859_1")). "Content−Type: text/plain. out.out. "Subject: remember me"). try { Socket s = new Socket(mailServer.". out. "Content−Disposition: attachment. sendln(out. // to send the file as an attachment instead of "inline" use : // sendln // (out. s. "Content−Type: text/plain. String boundary = "DataSeparatorString".filename=\""+FileName1+"\""). sendln(out. it is very short! NOTE: Check this related HowTo. sendln(out. sendln(out.Presley@jailhouse. out). "Content−Disposition: inline. boundary=\"" + boundary +"\""). name="+FileName1). "Content−Type: text/plain. out.0"). "\r\n" + "−−" + boundary ). sendln(out. "HELO world"). BufferedWriter out = new BufferedWriter (new OutputStreamWriter(s. // send the GIF sendln(out.. String recipient) { System. "Content−Type:image/gif. sendln(out.. sendln(in.rock<"). MIMEBase64. "\r\n−−" + boundary). sendln(in. // the text file sendln(out. } catch (Exception e) { e. sendln(out.14 Send email with an attachment .filename=\""+FileName2+"\""). "DATA"). Help me!\n\n"). // sendln // (out. out. 25). "QUIT"). // here you are supposed to send your username sendln(in.public void sendMail(String mailServer. sendln(in. Check out the Javascript. // done sendln(in. 13. sendln(out. sendln(in. "From: Elvis Presley <Elvis. sendln(out. out). sendln (out. sendln(out. sendln(out. "\r\n−−" + boundary). sendln(out. NOTE: A compact algorithm to encode string as Base64 can be found here.encode(FileName1.close().filename=\""+FileName2+"\""). } } .getOutputStream(). MIMEBase64. name="+FileName2). "RCPT TO: <" + recipient + ">" ). "Content−Transfer−Encoding: base64\r\n")."Content−Type: multipart/mixed. sendln (out.println("Send mail with attached file"). "I'm alive. "MIME−Version: 1. BufferedReader in = new BufferedReader (new InputStreamReader(s. name="+FileName2). "Content−transfer−encoding: base64\r\n")."Content−Disposition: attachment.

server. message. import java. "mymail.jar. props. null). "text/plain").mail.*. null).setSubject("Testing javamail plain").TO)).html The JavaMail API can found here.server.RecipientType. 13.getDefaultInstance(props.protocol". props. props. MimeMessage message = new MimeMessage(mailSession).host".connect().mail.internet.TO. props.getRecipients(Message. "mymail.setProperty("mail.*. It's a good idea to read the JavaMail FAQ. Transport transport = mailSession.jar and activation.*.RecipientType. message. Session mailSession = Session.setProperty("mail. props.password".*.mail.org").internet.transport. import javax.setProperty("mail.Properties.util..user".15 Send email with JavaMail Current version of this HowTo : http://www.com/javadetails/. transport.close().user".util.org"). } } HTML Email import javax. import javax. transport. message. You need 2 jars : mail. class SimpleHTMLMail { public static void main(String[] args) throws Exception{ Properties props = new Properties().setProperty("mail.host".13. "smtp"). message. ""). Transport transport = mailSession. class SimpleMail { public static void main(String[] args) throws Exception{ Properties props = new Properties().setProperty("mail. props.password".protocol". Simple email import javax.getTransport(). import java. transport.sendMessage(message.setProperty("mail./javadetails/java−0321. MimeMessage message = new MimeMessage(mailSession). new InternetAddress("elvis@presley. "emailuser").addRecipient(Message.transport. "").org")). "emailuser").rgagnon.getTransport(). props.setContent("This is a test".Properties. "smtp").15 Send email with JavaMail .setProperty("mail. props. Session mailSession = Session.getDefaultInstance(props.setProperty("mail.mail.

getRecipients(Message. message.getTransport(). props. Properties props = new Properties(). transport.TO.util.setDebug(debug). import java.org"). MimeBodyPart attachFilePart = new MimeBodyPart(). new InternetAddress("elvis@presley. message.transport.setProperty("mail.getName()).setFileName(fds.RecipientType.activation. javax.RecipientType. props. javax.mail. Session mailSession = Session.RecipientType.internet.setSubject("Testing javamail with attachment").sendMessage(message.setContent ("This is a test <b>HOWTO<b>".setProperty("mail.TO)). mp.getDefaultInstance(props.addBodyPart(attachFilePart).*.server.setContent("<h1>Check attachment</h1>". message.15 Send email with JavaMail . "emailuser").setProperty("mail. "smtp"). null).mail. props.close(). transport. } } Email with attachment import import import import javax. FileDataSource fds = new FileDataSource("SimpleMailWithAttachment. textPart. Multipart mp = new MimeMultipart(). class SimpleMailWithAttachment { public static void main(String[] args) throws Exception{ boolean debug = false.*.getRecipients(Message.activation.setProperty("mail.user". mailSession.addBodyPart(textPart).java").setContent(mp).org")). "text/html").message. "mymail.Properties. javax. ""). new InternetAddress("elvis@presley. props.connect(). MimeBodyPart textPart = new MimeBodyPart().setSubject("Testing javamail html").protocol".close().TO.setDataHandler(new DataHandler(fds)).RecipientType.addRecipient(Message. charset=ISO−8859−1"). message.sendMessage(message. attachFilePart. transport. message.connect().password". "text/html.TO)).org")).addRecipient(Message. MimeMessage message = new MimeMessage(mailSession). Transport transport = mailSession. attachFilePart.DataHandler. message. transport.host". } } 13. transport. message. transport. mp.FileDataSource.

com/javadetails/.*. public static void main(String[] args) throws Exception{ new SimpleMail(). The two don't share the same Authenticator as the JavaMail API works with Java 1. "text/plain").RecipientType. props.getDefaultInstance(props. which didn't have the java.getRecipients(Message. message.mail.net class of the same name.org")). message.connect().Properties. import java.smtp. public class SimpleMail { private static final String SMTP_HOST_NAME = "smtp.internet.util.org")). } private class SMTPAuthenticator extends javax. javax.16 Send email with authentication . "true").mail.TO. props. private static final String SMTP_AUTH_PWD = "mypwd". 13.getTransport(). // uncomment for debugging infos to stdout // mailSession. password).put("mail.sendMessage(message.Authenticator. javax. MimeMessage message = new MimeMessage(mailSession).TO)).addRecipient(Message.setFrom(new InternetAddress("me@myhost.myserver. } } } NOTE : The JavaMail Authenticator is found in the javax.rgagnon.put("mail. message. auth). SMTP_HOST_NAME). transport.close().put("mail. Session mailSession = Session. javax.mail./javadetails/java−0538.*. message.1.PasswordAuthentication. Transport transport = mailSession.com".mail.16 Send email with authentication Current version of this HowTo : http://www. String password = SMTP_AUTH_PWD.mail package and is different from the java. new InternetAddress("elvis@presley.protocol".setContent("This is a test".13.smtp.Authenticator { public PasswordAuthentication getPasswordAuthentication() { String username = SMTP_AUTH_USER.test().host".transport. private static final String SMTP_AUTH_USER = "myusername". transport.auth".setDebug(true).. "smtp").mail. Authenticator auth = new SMTPAuthenticator(). return new PasswordAuthentication(username.net variety. props. transport.html import import import import javax.RecipientType. } public void test() throws Exception{ Properties props = new Properties().

TO.setDebug(true).protocol".. message.setProperty("mail. mailSession. "smtp").TO)).*.connect().setProperty("mail..protocol". props. transport.com")). "myuser").setProperty("mail.user".17 Send HTML mail with images (Javamail) . import javax. Properties props = new Properties().getDefaultInstance(props.13. import java. "text/html"). } } One approach to include images in the mail body is to use the IMG tag and make the images available on a server."). import javax.transport. "myuser").setContent("<h1>Hello world</h1>".setProperty("mail. "mypwd"). mailSession..util.setFrom(new InternetAddress("me@sender.getDefaultInstance(props. 13.setSubject("HTML mail with images"). transport. props. message. import java.*. "mypwd"). message.com")).out. props.. Simply set the content type to "text/html". import javax. message.com"). Session mailSession = Session.setProperty("mail.setProperty("mail.html It's easy to send HTML mail with JavaMail. Transport transport = mailSession.mymailserver.*. props. "smtp.out. "smtp.Properties.mail./javadetails/java−0504. class SimpleMail { public static void main(String[] args) throws Exception{ System.RecipientType.println("Sending mail.mymailserver. Session mailSession = Session. null).com").println("Sending mail.mail.getRecipients(Message..internet.17 Send HTML mail with images (Javamail) Current version of this HowTo : http://www. transport.close().mail.host".setDebug(true).Properties. message. new InternetAddress("you@receiver.com/javadetails/.setProperty("mail.setProperty("mail. import javax. Transport transport = mailSession.transport. null).*. props. class SimpleMail1 { public static void main(String[] args) throws Exception{ System.user".password".rgagnon.host".getTransport().internet.password". MimeMessage message = new MimeMessage(mailSession).sendMessage(message.addRecipient(Message. props.RecipientType. props.mail.getTransport().util. Properties props = new Properties(). props. "smtp").").

String htmlText = "<H1>Hello</H1><img src=\"cid:image\">". message. message. Transport transport = mailSession. Session mailSession = Session.mail. null).MimeMessage message = new MimeMessage(mailSession).transport.TO)). To protect your privacy.*. class SimpleMail2 { public static void main(String[] args) throws Exception{ System.RecipientType.com")).com")).mymailserver. "smtp").addRecipient(Message.Properties.gif\">". mailSession. transport.. "mypwd"). spammers have used this mechanism as a sneaky way to record who visits their site (and mark your email as valid).connect(). import java. message.setProperty("mail.close().setDebug(true).println("Sending mail.setProperty("mail.setProperty("mail. Properties props = new Properties().sendMessage(message. messageBodyPart. import javax. "myuser"). message.setSubject("HTML mail with images").com").addRecipient(Message.setSubject("HTML mail with images").*. transport.getRecipients(Message.util.TO.setFrom(new InternetAddress("me@sender. // first part (the html) BodyPart messageBodyPart = new MimeBodyPart().setProperty("mail."). the BODY and the embedded image // MimeMultipart multipart = new MimeMultipart("related").mail. props.TO.RecipientType.getDefaultInstance(props.protocol".activation..com")). 13. "text/html"). MimeMessage message = new MimeMessage(mailSession).setContent(htmlText.setFrom(new InternetAddress("me@sender. new InternetAddress("you@receiver.out.host". props. message. import javax.com")). The HTML can reference the image in an attachment by using the protocol prefix cid: plus the content−id of the attachment. // // This HTML mail have to 2 part.user". props. import javax.rgagnon. new InternetAddress("you@receiver. "text/html").RecipientType.getTransport(). props. message.setContent ("<h1>This is a test</h1>" + "<img src=\"http://www. message. An alternative to placing absolute URLs to images in your HTML is to include the images as attachments to the email. many Web−based (and other) email clients don't display images in HTML emails. Unfortunately. message.17 Send HTML mail with images (Javamail) .password".com/images/jht. transport.*.internet. "smtp. } } The browser accesses these images just as if it were displaying an image in a Web page.

close(). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 13. message.TO)).net/ and http://quintanasoft. } } If you find this article useful.setHeader("Content−ID". DataSource fds = new FileDataSource ("C:\\images\\jht.html Set the Javamail DEBUG mode "on" : Session mailSession = Session.18 Debug a Javamail Program .sendMessage(message. messageBodyPart.setContent(multipart).// add it multipart. These mock−ups are designed to act a mail server but the actual email is not delivered to the mail recipient which can be useful in a testing stage.com/javadetails/.addBodyPart(messageBodyPart). // add it multipart. // put everything together message. you can detect if your firewall is blocking your connection. Use a Javamail server mock−up to act as "in−memory" mail server : See https://mock−javamail.getDefaultInstance(props.com/dumbster/. messageBodyPart. transport.gif").rgagnon.addBodyPart(messageBodyPart). null).getRecipients(Message./javadetails/java−0552. // second part (the image) messageBodyPart = new MimeBodyPart(). transport."<image>").dev.18 Debug a Javamail Program Current version of this HowTo : http://www.out. 13.connect(). consider making a small donation to show your support for this Web site and its content.java. Verify connectivity to the MailServer with Telnet : telnet mymailserver 25 for example. transport.RecipientType. This setting puts the Javamail classes in verbose mode to System.setDataHandler(new DataHandler(fds)). mailSession..setDebug(true).

smtps.*. Transport transport = mailSession. import java. "false").getRecipients(Message.put("mail. } public void test() throws Exception{ Properties props = new Properties().smtps.auth".html It's not uncommon that the outgoing mail needs to be encrypted using the SMTPS protocol. transport.com/javadetails/.addRecipient(Message. import javax. String SMTP_AUTH_USER = "myaccount@gmail.smtps. import javax.mail. int SMTP_HOST_PORT = 465.19 Send email with SMTPS (eg. props.connect (SMTP_HOST_NAME.TO)). SMTP_AUTH_PWD). SMTP_HOST_PORT.protocol".TO. String SMTP_AUTH_PWD = "mypwd". You need Javamail 1.getTransport().com".setContent("This is a test". } } The property props. message. MimeMessage message = new MimeMessage(mailSession).setSubject("Testing SMTP−SSL"). message. // props.getDefaultInstance(props). 13. transport.test().org")).rgagnon.*. props.close().internet.put("mail. "text/plain").sendMessage(message.RecipientType. SMTP_AUTH_USER. new InternetAddress("elvis@presley.gmail.smtps. Session mailSession = Session.Properties. "false").util.host". message. public class SimpleSSLMail { private private private private static static static static final final final final String SMTP_HOST_NAME = "smtp.quitwait". transport.transport. "smtps").RecipientType. message.mail.put("mail./javadetails/java−0570. It's the case for GMAIL for example. mailSession.. public static void main(String[] args) throws Exception{ new SimpleSSLMail().quitwait".4 to use the SMTPS protocol.13. SMTP_HOST_NAME). "true").put("mail. Google GMail) (Javamail) Current version of this HowTo : http://www. props.com".put("mail.setDebug(true). Google GMail) (Javamail) .19 Send email with SMTPS (eg.

InternetAddress from = new InternetAddress("from@me.1 Settings for well known mail providers .html This setting.49 . message. messageBodyPart.com (SMPTP − port 25) Google GMail Incoming Mail Server − pop.put("mail.null). The mail is sent but the exception is unwanted. // PLAIN TEXT BodyPart messageBodyPart = new MimeBodyPart().setText("Here is your plain text message"). // HTML TEXT messageBodyPart = new MimeBodyPart().getInstance(props.. message. If set to true (the default).ssl. The property quitwait means If set to false.host".setFrom(from).19. causes the transport to wait for the response to the QUIT command.com/products/javamail/javadocs/com/sun/mail/smtp/package−summary.is required to get rid of a strange SSL exception : javax.com (SMPTS SSL enabled.. InternetAddress to = new InternetAddress("to@you. message.addRecipient(Message..com/javadetails/.mail.quitwait. mail.sun.mail.RecipientType.yahoo. to). port 465) 13.MessagingException: Exception reading response.19.yahoo. "text/html").rgagnon.gmail. messageBodyPart. multipart.html Properties props = new Properties().com").setSubject("I am a multipart text/html email" ).net. nested exception is: javax. Session session = Session.addBodyPart(messageBodyPart).20 Mix plain text and HTML content in a mail Current version of this HowTo : http://www.1 Settings for well known mail providers Yahoo Incoming Mail Server − pop. is not required anymore! (july2007) 13.com (POP3 − port 110) Outgoing Mail Server − smtp.com")./javadetails/java−0471. port 995) Outgoing Mail Server − gmail. the QUIT command is sent and the connection is immediately closed. 13.setContent(htmlText.mail. Multipart multipart = new MimeMultipart().smtps.com (POP3S SSL enabled. String htmlText = "<H1>I am the html part</H1>". ref : http://java.TO. MimeMessage message = new MimeMessage(session)..SSLException: Unsupported record version Unknown−50..smtp. props. "MYMAILSERVER").

List atts = msg.println("Attachment : " + file.attachment.println(""). System.getFromName().auxilii. You read them with Javamail easily.*.out.com/javadetails/.multipart.addBodyPart(messageBodyPart).*./javadetails/java−0613.auxilii. Message msg = msgp. import com.parseMsg("c:/temp/test2. fromName = msg.println("").msgparser. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 13. 13.html When Outlook Express saves an email.msgparser. it uses the EML format which is a good thing because the format is a standard. import com.out.List.21 Read an Outlook MSG file .out. msgparser uses the Apache POI − POIFS library to parse the message files which use the OLE 2 Compound Document format. subject = msg.getAttachments(). System. System. message. String String String String fromEmail = msg.out.rgagnon. for (Attachment att : atts) { if (att instanceof FileAttachment) { FileAttachment file = (FileAttachment) att. consider making a small donation to show your support for this Web site and its content.getFromEmail(). System. But Outlook (not the Express but the one with Office) can only save an email with the MSG format which is Microsoft specific.out.out.setContent(multipart).21 Read an Outlook MSG file Current version of this HowTo : http://www.util. public class SimpleMsgParser { public static void main(String[] args) throws Exception{ MsgParser msgp = new MsgParser(). System.msg files and provides their content using Java objects. see this HowTo.getFilename()). 13. body = msg.println("Subject :" + subject)..msg"). System. import java.println(body).getSubject().com/msgparser/ msgparser is a small open source Java library that parses Outlook .send(message). If you find this article useful.22 msgparser http://auxilii.println("From :" + fromName + " <" + fromEmail + ">"). Transport.getBodyText().

25 Handle EML file with JavaMail Current version of this HowTo : http://www. Netscape etc.getSubject()).mail.dev. enabling developers to use JavaMail api to manage the mail stored in local repositories like Outlook Express.com").put("mail.com/javadetails/./javadetails/java−0458. "smtp. null).host". import import import import java. At the moment are supported navigation and reading from Outlook Express 5/6 mail (dbx format). MimeMessage message = new MimeMessage(mailSession. javax.apache. "smtp"). java. This kind of file can be read and parsed by JavaMail.net/ The jmbox project (read jambox) is a Local Store Provider for JavaMail.23 Apache POI HSMF .println("Subject : " + message. 13.out.getData().rgagnon.// you get the actual attachment with // byte date[] = file.*.23 Apache POI HSMF http://poi.dummydomain.put("mail. InputStream source = new FileInputStream(emlFile). source).java.html When saving an email to a file.24 jmbox https://jmbox. props.. Mozilla.*.protocol". public class ReadEmail { public static void main(String args[]) throws Exception{ display(new File("C:\\temp\\message. Session mailSession = Session.eml")). System. javax.*.org/hsmf/ HSMF is the POI Project's pure Java implementation of the Outlook MSG format.internet.getDefaultInstance(props.transport. 13.getProperties(). the resulting file has an eml extension (email files−−which are in RFC 822 format). 13.util. props. } } } } 13.*.mail. } public static void display(File emlFile) throws Exception{ Properties props = System.io.

URLConnection uc = u.26 Check if a file was modified on the server .3) with ESMTP id NAA07621 for . System.3/8.getFrom()[0]).0 (Windows.−!!T@1"! This is an example for HowTo Running the above HowTo gives this output : Subject : Example for HowTo From : real gagnon −−−−−−−−−−−−−− Body : This is an example for HowTo If you find this article useful.226. charset=us−ascii. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 13. "test. uc.175. format=flowed Content−Transfer−Encoding: 7bit X−UIDL: oP#!!c]^!!1. long timestamp = 0. consider making a small donation to show your support for this Web site and its content. try { u = new URL(getDocumentBase()./javadetails/java−0069.getContent()).net (tomts25. en−US.out.println("Body : " + message.com Subject: Example for HowTo Content−Type: text/plain..26 Check if a file was modified on the server Current version of this HowTo : http://www.com User−Agent: Mozilla/5.out.setUseCaches(false).openConnection().gif").9. 13.out. U.1 (ax) X−Accept−Language: en−us.bellnexxia. 01 Feb 2004 13:31:40 −0500 From: real gagnon Reply−To: real@rgagnon. rv:1.9. en MIME−Version: 1. } } A typical eml looks like this : X−Mozilla−Status: 0001 X−Mozilla−Status2: 00000000 Received: from tomts25−srv.bellnexxia.println("From : " + message.println("−−−−−−−−−−−−−−"). 1 Feb 2004 13:25:33 −0500 (EST) Date: Sun.com (8.rgagnon. Sun.html URL u =null.1.188]) by tactika.4) Gecko/20030624 Netscape/7.net [209.System.0 To: real@rgagnon. Windows NT 5. System.com/javadetails/.

printStackTrace().1] import java./javadetails/java−0059. import java.println(URLUtils. return (con.rgagnon. } } } Thanks to Steve B.exists("http://www.rgagnon.util.getResponseCode() == HttpURLConnection. 13.net.com/javadetails/.*. import java. public class URLUtils { public static void main(String s[]) { System.io./* ** use timestamp has a reference. con. */ timestamp = uc.27 Check if a page exists .println(URLUtils. System.html")).setInstanceFollowRedirects(false) HttpURLConnection con = (HttpURLConnection) new URL(URLName).printStackTrace().out.setRequestMethod("HEAD").. /* output : true false */ } public static boolean exists(String URLName){ try { HttpURLConnection. See also this HowTo.com/pagenotfound.27 Check if a page exists Current version of this HowTo : http://www.Properties.com/howto.getLastModified(). return false. // note : you may also need // HttpURLConnection. re−open an URLConnection ** to the same file to check if the timestamp is different ** with the getLastModified() method.setFollowRedirects(false).net. } catch (Exception e) { e.out. } catch (Exception e) { e.*. } } 13. import java.*.HTTP_OK). for the bug fix! The following is doing the same thing but this time we identify ourself to a proxy.io. import java.html [JDK1.openConnection().*.rgagnon.html")).exists("http://www.

28 Connect through a Proxy . con.misc. systemSettings. String encodedUserPwd = encoder. You can set the required properties when starting the JVM for a JAVA application from the command line: 13.com")).println (con.out.com/javadetails/./javadetails/java−0085.28 Connect through a Proxy Current version of this HowTo : http://www.openConnection().getResponseCode() == HttpURLConnection.local") .getProperties().out.BASE64Encoder(). // // it's not the greatest idea to use a sun.html You have to set the following properties : http. } catch (Exception e) { e.rgagnon.4/docs/guide/net/properties. systemSettings.printStackTrace().HTTP_OK).BASE64Encoder encoder = new sun. } } } 13. "80") .misc.encode("domain\\username:password".put("http.proxyHost (default: <none>) http.getResponseMessage()). URL u = new URL(URLName).".mycompany.out. return false.println(exists("http://www. HttpURLConnection con = (HttpURLConnection) u. systemSettings..html. "Basic " + encodedUserPwd).put("http. proxyPort are deprecated. NOTE: Those properties are documented here : http://java. con. you have to prefix them with "http.yahoo. System."proxy.getBytes()).println(exists("http://www. System.setRequestMethod("HEAD").rgagnon. } public static boolean exists(String URLName){ try { Properties systemSettings = System.getResponseCode() + " : " + con.com/j2se/1.proxyHost".proxyPort".* class // Sun strongly advises not to use them since they can // change or go away in a future release so beware.misc.put("proxySet". "true").setRequestProperty ("Proxy−Authorization".nonProxyHosts (default: <none>) NOTE: proxyHost. return (con.proxyHost specified) http.sun.proxyPort (default: 80 if http.public class URLUtils { public static void main(String s[]) { System.com")). // sun.

getProperties(). see this How−to. systemSettings. systemSettings. System. NOTE: For a base64 function. import java. You might need to identify yourself to the proxy server. uc. "80") . // PROXY Properties systemSettings = System. URLUtils..com"). import java.proxyHost".setRequestProperty("Proxy−Authorization".local") .put("http. byte [] b = new byte[1]. 13.28 Connect through a Proxy .getProperties(). One way is to use the HTTP property "Proxy−Authorization" with a username:password base64 encoded.println("**************").proxyPort".println("**************").paypal. systemSettings.com"). // sun. URL url=new URL("http://someserver/somepage").yahoo. FileOutputStream fo = null.misc.Properties. .dump("http://www.misc. URL u = new URL(URLName). URLConnection uc = url. uc.getBytes()))..* class // Sun strongly advises not to use them since they can // change or go away in a future release so beware. // // it's not the greatest idea to use a sun.com −Dhttp.connect(). String encoded = new String (Base64.proxyPort=80 MyJavaApp Or in your source : import java. The following example dumps the content of a URL but before we identify ourself to the proxy import java.setProperties(systemSettings). "Basic " + encoded).base64Encode(new String("username:password").net. "myProxyServer.proxyHost=myproxyserver.util..out.BASE64Encoder(). } public static void dump(String URLName){ try { DataInputStream di = null."proxy. "80").proxyPort".setProperties(systemSettings).Properties.put("http.put("http. System.BASE64Encoder encoder = new sun. .com"). public class URLUtils { public static void main(String s[]) { URLUtils. System.put("http.*.dump("https://www.util.openConnection().*. HttpURLConnection con = (HttpURLConnection) u.getProperties().io.openConnection (). Properties systemSettings = System. System. systemSettings.out..java −Dhttp. Properties systemSettings = System.misc.proxyHost".mydomain.

1)) { System.String encodedUserPwd = encoder. "80") . systemSettings.0. When no username/password are provided then popup is shown to ask for the credentials.encode("mydomain\\MYUSER:MYPASSWORD".proxyHost".print(new String(b)).toCharArray()).nonProxyHosts="*.com|*.put("http. while(−1 != di.getBytes()).out.read(b.setRequestProperty ("Proxy−Authorization". FileOutputStream fo = null.getInputStream()).getProperties(). di = new DataInputStream(con. "Basic " + encodedUserPwd).local|localhost" MyClass 13. each seperated by a |. The http. public static void dump(String URLName){ try { DataInputStream di = null.getInputStream()). // PROXY −−−−−−−−−− di = new DataInputStream(con. you may need to bypass the proxy server and go directly to the http server.openConnection().put("http.0."proxy. byte [] b = new byte[1]. con.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("mydomain\\username". } } } With JDK1."password". systemSettings.nonProxyHosts property indicates the hosts which should be connected too directly and not through the proxy server. The value can be a list of hosts.printStackTrace(). } } catch (Exception e) { e. java. }}). } } In intranet environment. URL u = new URL(URLName).1)) { System.proxyPort". the java.mycompany.read(b.mycompany.mydomain.Authenticator can be used to send the credentials when needed.out.print(new String(b)).2. and in addition a wildcard character (*) can be used for matching. } } catch (Exception e) { e.local") . HttpURLConnection con = (HttpURLConnection) u.28 Connect through a Proxy .printStackTrace(). Authenticator.net. // PROXY Properties systemSettings = System. while(−1 != di.exe −Dhttp.

} public static String userNamePasswordBase64 (String username.. 'q'. 'Z'. '1'. 'B'. '8'. 'R'. userNamePasswordBase64(uname. 'N'. args[2]))). 'z'.13.pword)). '/' 13. 'p'. 'm'. 'V'. 'u'. return conn. 'v'.connect (). 'U'. 'i'. 't'. 'Y'. 'M'. 'F'. '9'. 'L'.29 Identify yourself using HTTP Authentification .out.html import java. 'b'. while ((line = in. '+'. static char base64Array [] = { 'C'.readLine()) != null) { System. '2'. 'J'. String pword) throws IOException { URLConnection conn = url. } } public static InputStream openURLForInput (URL url. 'K'.rgagnon. 'Q'. 'y'. String password) { return "Basic " + base64Encode (username + ":" + password). 'x'.setDoInput (true). '6'. import java.getInputStream(). conn. 'c'. 'f'. String uname.setRequestProperty ("Authorization". } private final 'A'. 'k'.*. String line. 'r'. } } catch (IOException e) { e. 'I'.printStackTrace(). 'd'. '5'. 'e'./javadetails/java−0084. 'o'. 'l'. 'h'. 'S'. '7'. 'j'.29 Identify yourself using HTTP Authentification Current version of this HowTo : http://www. 'n'. 'P'.com/javadetails/. 'D'. 'H'. 'G'. 'X'.net. }. 'W'. 'w'. conn. 'E'. '3'. 'a'. 'T'. conn.io. '4'.openConnection(). '0'. 's'.println(line). args[1].*. 'O'. public class TestAuth { public static void main (String args[]){ /* ** args[0] is the URL protected ** args[1] is the username ** args[2] is the password */ try { BufferedReader in = new BufferedReader( new InputStreamReader (openURLForInput(new URL(args[0]). 'g'.

case 1: encodedString += base64Array [c3]. byte c3 = (byte)(((b2 & 0xf) << 2) | (b3 >> 6)).getBytes()). "Basic " + encodedUserPwd). } } { A better alternative is the Authenticator class. An alternative way to Base64 encoding is to use the Base64 class in the sun. encodedString += base64Array [c2].length) { byte b1 = bytes [i++].length) { b2 = 0. if (i >= bytes. switch (pad) { case 0: encodedString += base64Array [c3].BASE64Encoder(). int pad = 0. break. byte b2. encodedString += base64Array [c4].encode("domain\\username:password". break. b3 = 0. } } return encodedString. NOTE: a simple explanation about the base64 encoding principle is shown in this How−to. byte c2 = (byte)(((b1 & 0x3) << 4) | (b2 >> 4)). if (i >= bytes. break.setRequestProperty("Proxy−Authorization". pad = 1. case 2: encodedString += "==". encodedString += "=".* package. } byte c1 = (byte)(b1 >> 2). byte b3. 13.getBytes ().length) { b3 = 0.29 Identify yourself using HTTP Authentification . byte c4 = (byte)(b3 & 0x3f).BASE64Encoder encoder = new sun. byte bytes [] = string. sun. String encodedUserPwd = encoder. int i = 0. while (i < bytes. encodedString += base64Array [c1]. } else b3 = bytes [i++]. } else { b2 = bytes [i++].misc. con.private static String base64Encode (String string) String encodedString = "".misc. see this HowTo.misc. pad = 2.

Check this HowTo for a more official way to encode/decode to/from Base64. String encoded = "name=" + URLencoder.com/cgi−bin/aCGI. The CGI will process the result and produce a page to be displayed. BufferedReader in = new BufferedReader(new InputStreamReader(c.setDoOutput(true). Those classes can be missing in your JDK release.30 Talk to a CGI/Servlet . String aLine.pl?name=real).com/cgi−bin/aCGI. String theCGI = "http://www. while ((aLine = in.30 Talk to a CGI/Servlet Current version of this HowTo : http://www. Then InputStream is created to receive the result. URL CGIurl = new URL(theCGI).net. Here we calling a script called aCGI. First a connection is made to the CGI.rgagnon. There is two ways to send a request to a CGI..getOutputStream()). The POST method allows the programmer to manipulate the data received from the CGI.setRequestProperty("content−type". an OutputStream is open to send the parameters (if any). String theCGI = "http://www.server.writeBytes(encoded). String encoded = "name=" + URLencoder. c.close().println(aLine).flush(). you call the CGI using the showDocument method (Applet). c. A typical URL talking to CGI using the GET method would be: new URL("http://www.URLencoder class.openConnection(). out.com/cgi−bin/acgi. there is no difference talking to CGI or Servlet.server.pl". } 13. Parameters are encoded.server./javadetails/java−0082.getInputStream()). The GET method contains encoded parameters in the URL."application/x−www−form−urlencoded").setUseCaches(false). Once the URL is constructed. spaces are changed to "+" and special character to hexadecimal using a 3−letter escape sequence.html From the client point of view. getAppletContext(). out. URL cgiurl = new URL(thecgi + encoded).pl (a PERL script) passing the parameters name and site.Use of the sun. URLConnection c = CGIurl. out. c. DataOutputStream out = new DataOutputStream(c. 13.out.readLine()) != null) { // data from the CGI System.showDocument(cgiurl). Each parameter is delimited by the character "Habitually the encoding is done through the static method encode of the java.pl?".encode("Real Gagnon").encode("Real Gagnon").com/javadetails/.* package is "discouraged" by sun and not formally supported.

class CookiesInJava { static Hashtable theCookies = new Hashtable().io.rgagnon.hasMoreElements()) { String key = (String)keys. Enumeration keys = theCookies. */ public URLConnection writeCookies (URLConnection urlConn. import java. 13. for debugging * @param reset Clean the Hashtable or not */ public void readCookies(URLConnection urlConn.get(key). boolean printCookies.You can't do some output then some input and do again some output. * * @return The urlConn with the all the cookies in it. There is no "dialog" between the client and the server.util. String hdrKey.keys(). cookieString).31 Write/Read cookies using HTTP .html For a Java−Javascript solution. and insert them * to the Hashtable * The hashtable represents the Cookies. import java. boolean printCookies){ String cookieString = "". String hdrString. * @param printCookies Print or not the action taken.. /** * Send the Hashtable (theCookies) as cookies. return urlConn. You must do all the output and then the input.println("Wrote cookies:\n " + cookieString).net. } /** * Read cookies from a specified URLConnection.setRequestProperty("Cookie".out. 13. boolean reset){ if (reset) theCookies. ". int i=1.*. * * @param urlConn the connection to read from * @param printCookies Print the cookies or not.*. if (printCookies) System. String aCookie. The client make a request and the server send back the result and close the connection. if (keys. } urlConn.*. while (keys.clear(). and write them to * the specified URLconnection * * @param urlConn The connection to write the cookies to. cookieString += key + "=" + theCookies.com/javadetails/. import java.hasMoreElements()) cookieString += ". check this How−to./javadetails/java−0092.nextElement().31 Write/Read cookies using HTTP Current version of this HowTo : http://www.

substring(j + 1)).hasMoreElements()){ key = (String)keys. // you may want to add some logic to update // the stored Cookie instead.indexOf(".".while ((hdrKey = urlConn.containsKey(aCookie. while (keys.substring(0.println(urlConn. } /** * Add a specific cookie.substring(0.equals("Set−Cookie")) { hdrString = urlConn.get(key)). // aCookie = hdrString.").out. by hand. j))){ // if the Cookie do not already exist then when keep it.out. Enumeration keys = theCookies.substring(0. * searching for the: "Cookie" header * * This is Valid only after a writeCookies operation.nextToken().getHeaderFieldKey(i)) != null) { if (hdrKey.getHeaderField(i).indexOf(".")).out.nextElement(). j).println(" Val: " + aCookie.out. System. String key.aCookie.substring(0.println("All Cookies are:"). System. s.")).out.substring(0. System. s.println("Reading Key: " + aCookie. } } } } } i++. int j = aCookie.println(" " + key + "=" + theCookies. } } /** * Display the current cookies in the URLConnection. while (st.31 Write/Read cookies using HTTP . if (printCookies){ System. * * @param urlConn The URL to print the associates cookies in.out. aCookie = s. j)).hasMoreTokens()) { String s = st.getRequestProperty("Cookie")). StringTokenizer st = new StringTokenizer(hdrString. */ public void viewURLCookies(URLConnection urlConn) { System.print("Cookies in this URLConnection are:\n "). thanks to rwhelan theCookies. if (j != −1) { if (!theCookies.indexOf("=").substring(j + 1)). to the HastTable of the Cookies * * @param _key The Key/Name of the Cookie * @param _val The Calue of the Cookie 13. } } /** * Display all the cookies currently in the HashTable * */ public void viewAllCookies() { System.put (aCookie.keys().

byte [] b = new byte[1].net.rgagnon. String s){ aURL = u.io.println(" at " + aURL ). URLConnection urlConnection = url. urlConnection. } SuckURL(String u.openConnection().println(" " + _key + " = " + _val). if (printCookies){ System.put(_key.read(b.. System. // output fo = new FileOutputStream(aFile).println("Adding Cookie: ").out. b.1)) 13. aFile = s._val). di = new DataInputStream(urlConnection./javadetails/java−0060.connect(). } public void doit() { DataInputStream di = null.out. try { System. boolean printCookies){ if (!theCookies.32 Read a GIF or CLASS from an URL save it locally .out.html import java. // copy the actual file // (it would better to use a buffer bigger than this) while(−1 != di.containsKey(_key)){ theCookies. String aURL.rgagnon. import java.32 Read a GIF or CLASS from an URL save it locally Current version of this HowTo : http://www. "jht. public class SuckURL { String aFile.getInputStream()).com/images/". FileOutputStream fo = null. public static void main(String args[]) { // GIF JAVA How−to at Real's Home String url = "http://www.*.doit().gif").println("Sucking " + aFile). // input URL url = new URL(aURL + aFile). } } } } Thanks to Saar Machtiner for the bug fix 13.* @param printCookies Print or not the result */ public void addCookie(String _key.0. System.com/javadetails/. String _val.out.*. SuckURL b = new SuckURL(url.

println("Oups!!!").addProvider(new com. fo. System. in.net. } System.Provider()).write(b.33 Resolve a relative URL .fo. } } There is an issue with root certificate from Verisign (jdk142 or less.*.out./javadetails/java−0001. ". } } This example dumps a page using the HTTPS protocol : import java.protocol. BufferedReader in = new BufferedReader( new InputStreamReader( con.close().net.out. while ((inputLine = in.sun.sun. di. HttpURLConnection con = (HttpURLConnection) url.close(). baseURL.internal.thawte.println ( relativeURL.com").sun.html import java.net. String inputLine.com/javadetails/. // "com.com/"). /* output : 13.out. relativeURL = new URL ( baseURL.getInputStream()))..out.toExternalForm ()).pkgs".URL. public class ResolveRelativeURL { public static void main (String[] args) throws java. System.").*.println("done.rgagnon..exit(1).net. // System. you may want to review this note : http://sunsolve.MalformedURLException { URL relativeURL.handler. baseURL = new URL ("http://www. ex.do?assetkey=1−26−57436−1. import java.close()..protocol").html"). 13.setProperty("java.internal.openConnection().io.println(inputLine).ssl.printStackTrace().ssl. you have exception talking about "untrusted server").rgagnon.1). } catch (Exception ex) { System.33 Resolve a relative URL Current version of this HowTo : http://www.ssl.www.readLine()) != null) System. // Security.net. public class URLReader { public static void main(String[] args) throws Exception { // no longer necessary since JSSE is now included in // recent jdk release./javadetails/java−0297. URL url = new URL("https://www.0.com/search/document.

34 File size from URL .rgagnon. size = conn.html */ } } 13.length != 1) { System.out.out.com).."). URL ssl = new URL("https://www.rgagnon.34 File size from URL Current version of this HowTo : http://www. Before connecting with a secure URL.openConnection(). import java.http://www.io. if(args.35 Use the HTTPS protocol Current version of this HowTo : http://www.getInputStream()./javadetails/java−0308.close(). public class FileSizeFromURL { public static final void main(String[] args) { URL url.printStackTrace(). } } } 13.com/javadetails/. if(size <0) System. conn. conn = url.rgagnon. we must do this first : 13.com/javadetails/.*.net. both IE and NN have implemented https in their java.net.URL class so just use it exactly as you would for a regular http URL.secureserver.openStream(). return. } catch(Exception e) { e.html For Applets. URLConnection conn. InputStream is = ssl. take a look at the Sun's Secure Socket Extension (JSSE). else System..out.println("Usage: FileSizeFromURL ").println("Could not determine file size. int size.html import java.println(args[0] + "\nSize: " + size).*. For application. } try { url = new URL(args[0])./javadetails/java−0298.getContentLength().com/javadetails/java−0001.

MSIE 6.0.protocol"). One easy way to do this is to open a secured page (say https://mysecuredhost.0)" MyClass or in your program System. URL urlObject = new URL(google).protocol.internal.Provider())..4. "com. con.agent. Another way is to start the program with a modified System.setProperty ("http.net.com) with IE. However you may need to import the certificate from the host (that is the server that you are connecting to using the https: protocol). String google="http://www. "Mozilla/4.36 Fetch a page from Google Current version of this HowTo : http://www.agent=Mozilla/4.com/apis/ to learn how to interact with Google via the official API's. webData = new BufferedReader(new InputStreamReader(con. you can directly override the HTTP header.sun.html You can't directly fetch a page from Google because a check is made (by Google) to restrict access to "real" browser so a "403" HTTP code is returned to your Java program.ssl..0)" ).www.com/javadetails/. Note : You may want to take a look at http://www.security.handler. Windows NT 5.internal.setProperty ("java. String search= "What you want to search for".ssl. URLConnection con = urlObject.pkgs".0 (compatible. 13. MSIE 6.java. click on the SSL−symbol (bottom right) and exported the key into the file "c:\cacerts. the JSSE package is included so you don't have to add anything special..setRequestProperty ( "User−Agent".sun.0)"). Windows NT 5.ca/search?q=" + search + "e=UTF8".google. As seen above.0./javadetails/java−0399. Windows NT 5.agent".36 Fetch a page from Google .google.0 (compatible.openConnection(). A useful link for that is this JavaWorld's Tip Since JDK 1.0. System.getInputStream())).0 (compatible. Go in "%java_home%\bin" and type this: keytool −import −v −alias meincert −trustcacerts −file c:\ 13. >java "−Dhttp.Security.rgagnon. You need to fool Google by pretending to be a legitimate browser. "Mozilla/4.ssl. .addProvider(new com.property http.net. MSIE 6.ce".

Postlet is a Java applet used to enable websites to allow their users to send multiple files to a webserver with a few simple clicks. you can't do it with client−side code only.com/javadetails/.proxyPort (default: 80 if http. it's a servlet. You can set the required properties when starting the JVM for a JAVA application from the command line: java −Dhttp.oreilly. A simple way to use the HTML tag in a FORM <FORM METHOD=POST ENCTYPE="multipart/form−data" ACTION="../myuploadscript"> File to upload: <INPUT TYPE=FILE NAME="upfile">< <INPUT TYPE=SUBMIT VALUE="Submit"> </FORM> which looks like File to upload: The associated FORM target is a script on the server side that can handle HTTP file upload./javadetails/java−0543.proxyHost (default: <none>) http.html.com/j2se/1.37 Upload a file to a server . proxyPort are deprecated.rgagnon. 13.37 Upload a file to a server Current version of this HowTo : http://www. Postlet is useable with any server side scripting language that is capable of handling file uploads.servlet) On the client side.13.html You have to set the following properties : http. Typically in Java.4/docs/guide/net/properties.nonProxyHosts (default: <none>) NOTE: proxyHost.."./javadetails/java−0085..38 Connect through a Proxy Current version of this HowTo : http://www.sun.html To upload a file to a server you need something on the server side to accept the file. a java application can use Jakarta Commons HTTP client to initiate a file upload. The 2 most popular Java packages (server−side) to handle file upload are : • Jakarta Commons File Upload • O'reilly MultipartRequest (com.rgagnon.proxyPort=80 MyJavaApp Or in your source : 13.proxyHost=myproxyserver. NOTE: Those properties are documented here : http://java.proxyHost specified) http. you have to prefix them with "http.com/javadetails/.com −Dhttp.

uc..proxyHost".yahoo.BASE64Encoder(). } public static void dump(String URLName){ try { DataInputStream di = null."proxy. uc.openConnection (). systemSettings. NOTE: For a base64 function. 13. import java.paypal.misc.proxyHost". systemSettings. public class URLUtils { public static void main(String s[]) { URLUtils. .getBytes())).proxyPort".out.import java.base64Encode(new String("username:password").openConnection(). byte [] b = new byte[1].proxyPort".put("http.Properties.util.setProperties(systemSettings)....com"). // // it's not the greatest idea to use a sun. System. System. String encoded = new String (Base64.util. "80").connect(). URLUtils.getProperties(). One way is to use the HTTP property "Proxy−Authorization" with a username:password base64 encoded.mydomain.net.*.com").setRequestProperty ("Proxy−Authorization".out.io.com").misc. Properties systemSettings = System.* class // Sun strongly advises not to use them since they can // change or go away in a future release so beware. systemSettings. "Basic " + encoded).Properties. // PROXY Properties systemSettings = System. systemSettings. con. .getProperties().getProperties().getBytes()). The following example dumps the content of a URL but before we identify ourself to the proxy import java.println("**************").encode("mydomain\\MYUSER:MYPASSWORD". import java.put("http. System. see this How−to. URL u = new URL(URLName).BASE64Encoder encoder = new sun.*. FileOutputStream fo = null.dump("https://www.misc. URL url=new URL("http://someserver/somepage"). "80") . Properties systemSettings = System.dump("http://www. "myProxyServer.local") . // sun. String encodedUserPwd = encoder. System.setRequestProperty("Proxy−Authorization". HttpURLConnection con = (HttpURLConnection) u.println("**************").setProperties(systemSettings). "Basic " + encodedUserPwd).37 Upload a file to a server . You might need to identify yourself to the proxy server.put("http. URLConnection uc = url.put("http.

public static void dump(String URLName){ try { DataInputStream di = null.read(b.mycompany. HttpURLConnection con = (HttpURLConnection) u.getInputStream()).// PROXY −−−−−−−−−− di = new DataInputStream(con.mydomain.toCharArray()). and in addition a wildcard character (*) can be used for matching. the java.proxyPort". }}).com|*. } } } With JDK1.openConnection()."proxy. you may need to bypass the proxy server and go directly to the http server.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("mydomain\\username".1)) { System.Authenticator can be used to send the credentials when needed.nonProxyHosts="*. while(−1 != di. "80") .print(new String(b)). URL u = new URL(URLName).read(b.printStackTrace().proxyHost". while(−1 != di.put("http. } } In intranet environment.local") . } } catch (Exception e) { e.put("http. // PROXY Properties systemSettings = System. } } catch (Exception e) { e. byte [] b = new byte[1].nonProxyHosts property indicates the hosts which should be connected too directly and not through the proxy server.0.0. FileOutputStream fo = null."password".out. each seperated by a |.mycompany. Authenticator.printStackTrace().getProperties(). systemSettings. The http.print(new String(b)).getInputStream()).local|localhost" MyClass 13. When no username/password are provided then popup is shown to ask for the credentials. systemSettings. di = new DataInputStream(con. java.net.out.exe −Dhttp.1)) { System. The value can be a list of hosts.37 Upload a file to a server .2.

But we can emulate a ping by talking the "echo port".com/javadetails/.out.readLine().40 Ping a server Current version of this HowTo : http://www. the socket is still connected even though the Exception was raised. } catch ( java. However.accept(). import java.io. 13.net.out. t.html [JDK11] ServerSocket server = new ServerSocket(port).setSoTimeout(60000). Since READ operation blocks as long necessary it may be wise to use the setSoTimeout() method.getOutputStream()). DataInputStream dis = new DataInputStream(t.html It's not possible to really "ping" a machine to check if it's alive or not (it's a long story.InterruptedIOException e ) { System. } This is true for READ operation too..println("Dead or echo port not responding").39 Have timeout on socket connection . // timeout after 60 seconds server. an InterruptException is thrown.13. else System.println("Hello")./javadetails/java−0086.io.err. String str = dis. but to keep it short I will just say that the Socket class is not low−level enough for that operation). } catch (IOException e) { e. 7).com/javadetails/. try { Socket socket=server./javadetails/java−0093.*. if (str. ps.println( "Timed Out (60 sec)!" ).printStackTrace(). On a server. import java. the echo port is always port 7.rgagnon.equals("Hello")) System. Note that when the TIMEOUT expires.rgagnon. PrintStream ps = new PrintStream(t.39 Have timeout on socket connection Current version of this HowTo : http://www.getInputStream()).close().*.} } } } NOTE: To make this a more "complete PING". public class PseudoPing { public static void main(String args[]) { try { Socket t = new Socket(args[0]. We write a string to that port and the server will echo the string. you may want to check this How−to to display the response time.println("Alive!") . 13..

System.out. } catch (IOException e) { System. while (true) { byte b[] = new byte[100].printStackTrace().Since JDK1.mit.edu").getHostAddress()). } try { Socket s = new Socket(args[0].length != 1) { System.*.. System. return. } } } isReachable() will use ICMP ECHO REQUESTs if the privilege can be obtained.*.edu").41 Get the Date from server Current version of this HowTo : http://www. public class GetTime { public static void main(String args[]) { if (args.println("Usage: GetTime HOST").41 Get the Date from server .read(b).InetAddress. import java. } } catch (Exception e) { e.getHostName()).rgagnon.html This can be done by opening a socket to the port "daytime" (port 13) (on Unix or NT machine).net. import java.0. int i=is.net.com/javadetails/. But most Internet sites have disabled the service or blocked the requests (except some university web sites like the example above) .mit.out.getInputStream().io. } } 13.edu").13).isReachable(int) can be used to check if a server is reachable or not.io.*.println("Unable to reach web. InputStream is = s. java.out. if (i==−1) return.println("Reach: " + address.i)). 13. otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host.mit.err.println("Name: " + address.out.println("Unable to lookup web.println("Addr: " + address. System.*.getByName("web.out. import java. public class ReachableTest { public static void main(String args[]) { try { InetAddress address = InetAddress.print(new String(b. import java./javadetails/java−0094. } catch (UnknownHostException e) { System. System.isReachable(3000)).5.err.net.

Using a Servlet. Internet.html import java. import java. public class GetClientIP extends Applet { public void init() { try { InetAddress thisIp = InetAddress.42 Get the client IP address .class" HEIGHT=10 WIDTH=10> </APPLET> Check JAVA console for output /BODY Try it here NOTE: Netscape returns the IP address with the default security settings so it's not problem.getHostAddress()). System. giving 13.rgagnon. With IE5.getLocalHost(). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 13. Edit and select "Allow access to all IP address". you can explicitly set a delay before a reset is sent.43 Use the java. HttpServletResponse res) throws IOException { String IP = req.printStackTrace()..com/javadetails/.*.setSoLinger method Current version of this HowTo : http://www.io. Java Custom.net./javadetails/java−0095.html By using the setSoLinger() method. } If you find this article useful..Socket. import java. } catch(Exception e) { e.getRemoteAddr().println("IP:"+thisIp.net. you must go to the security TAB. } } } <HTML><HEAD></HEAD><BODY> <APPLET CODE="GetClientIP.applet.42 Get the client IP address Current version of this HowTo : http://www./javadetails/java−0293.*. consider making a small donation to show your support for this Web site and its content.out. this can be done with : public void service(HttpServletRequest req.*.rgagnon.} 13.com/javadetails/.

net.net. The Nagle's algorithm is described in RFC 896.Socket.setTcpNoDelay() is used to enable/disable TCP_NODELAY which disable/enable Nagle's algorithm. meaning a reset will be sent as soon as the java.net.Socket.getSoLinger() 13.accept().com/javadetails/. 13.Socket..Socket.getHostAddress() + ':' + aSock.html A client module connects to a server then a file is sent to the client. Note that if a linger time is set to zero. they can disable Nagle's algorithm (that is enable TCP_NODELAY)./javadetails/java−0294.. and acknowledgements to be received. You get the current "linger" setting with java.println ("Connection from : " + aSock.getTcpNoDelay() 13.46 Transfer a file via Socket Current version of this HowTo : http://www. Data will be sent earlier. You get the current "TCP_NODELAY" setting with java. Nagle's algorithm try to conserve bandwidth by minimizing the number of segments that are sent..Socket.out.html Socket aSock = myServerSocket.html java. The boolean flag activates or deactivates the SO_LINGER option.rgagnon. This exemple is very simple with no authentication and hard−coded filename! First a server module./javadetails/java−0295.net.com/javadetails/./javadetails/java−0542.net.net.44 Use the java.44 Use the java.Socket.setTcpNoDelay method . or you can specify a delay of zero.close() method is invoked.com/javadetails/.setSoLinger() method accepts as parameters a boolean and an int.45 Find out who is accessing my ServerSocket Current version of this HowTo : http://www.getPort()).getInetAddress().Socket. When applications wish to decrease network latency and increase performance.more time for data to be read or send. at the cost of an increase in bandwidth consumption. You can possibly increase performance with a delay of zero.setTcpNoDelay method Current version of this HowTo : http://www. The java. and the int controls the delay time (in seconds. 13. then any unsent packets are thrown away when the socket is closed otherwise the close() method blocks while waiting the specified number of seconds for the data to be sent. max 65535).net. System.rgagnon.rgagnon.

net.io.length−current)).out. bis. // sendfile File myFile = new File ("source. 0 .length).read(mybytearray..pdf").accept(). BufferedOutputStream bos = new BufferedOutputStream(fos).io."). System. public class FileServer { public static void main (String [] args ) throws IOException { // create socket ServerSocket servsock = new ServerSocket(13267).0. (mybytearray.length). } while(bytesRead > −1).*.mybytearray. if(bytesRead >= 0) current += bytesRead. // localhost for testing Socket sock = new Socket("127.net.println("Waiting.mybytearray. current = bytesRead. os.. Socket sock = servsock.0.out.1". // receive file byte [] mybytearray = new byte [filesize]. long end = System. import java. FileOutputStream fos = new FileOutputStream("source−copy.pdf").flush().currentTimeMillis(). BufferedInputStream bis = new BufferedInputStream(fis). bos.println("Sending. int bytesRead.currentTimeMillis().read(mybytearray. current.write(mybytearray.").println("Connecting.0. sock.read(mybytearray.net. public class FileClient{ public static void main (String [] args ) throws IOException { int filesize=6022386.setTcpNoDelay method . OutputStream os = sock. current). System. bytesRead = is.getOutputStream(). // thanks to A.44 Use the java.*. System. } } } The client module import java.").length). byte [] mybytearray = new byte [(int)myFile..mybytearray.write(mybytearray.0. Cádiz for the bug fix do { bytesRead = is. os.length()]. int current = 0.13267). FileInputStream fis = new FileInputStream(myFile).import java.close(). InputStream is = sock. System.*.0.out.out.println("Accepted connection : " + sock). 13.out..getInputStream().Socket. while (true) { System.*. // filesize temporary hardcoded long start = System.println(end−start). import java...

setTcpNoDelay method . sock.close().Socket.rgagnon.bos.net. } } Written and compiled Réal Gagnon ©2007 real@rgagnon.com http://www.close().com 13.44 Use the java.

equals(s)){ System.getInstance("SHA−1").rgagnon.security.sval)).println("You got it!").reset(). now deprecated. String s = "". return d. d. if (secret.out..security./javadetails/java−0400.in).println("the encrypted result : " + secret). d.2 Encrypt a password Current version of this HowTo : http://www.MessageDigest.StreamTokenizer Input=new java.getBytes()). // System.!"). boolean ok = true.1 java−security 14. try again.out.MessageDigest d =null.digest().. } } catch (Exception e){ e.printStackTrace(). d = java..14 Security 14.print("Input your secret password : "). java.print("Now try to enter a password : " ). String secret = new String(CryptoUtils.com/javadetails/. } } The output is : 14 Security ..out. } } public static byte[] encrypt(String x) throws Exception { java.encrypt(Input. public class CryptoUtils { public static void main(String arg[]) { try { // quick way to do input from the keyboard.html Message digests are secure one−way hash functions that take arbitrary−sized data and output a fixed−length hash value. System.out.nextToken(). while (ok) { System.println("Wrong. } else System.io.StreamTokenizer(System. ok = false.out. Input.update(x.nextToken().sval)). Input.encrypt(Input.. s = new String(CryptoUtils.io.

} sb. you may need to transform it into a hexadecimal string because the encrypted string may contains non−printable characters.BASE64Encoder encoder = new sun.encode(secret.parseInt(s.. i < b. String encoded=encoder. i++){ int v = b[i] &0xff.length. try again. sun.length * 2). // encoded is a string with printable characters. try again. int v = Integer. } public static byte[] hexStringToByteArray(String s) { byte[] b = new byte[s..length() / 2]. i++){ int index = i * 2. Or we can simply convert the byte array into an hexadecimal string: public class StringUtils { public static void main(String arg[]) { byte b[] = { 7.BASE64Encoder(). i++) { System.out.out.toUpperCase().misc. for (int i = 0.append(Integer. // 7.length.substring(index.println(byteArrayToHexString(b)). −1. } /* output : 7 42 −1 −127 */ } public static String byteArrayToHexString(byte[] b){ StringBuffer sb = new StringBuffer(b. 81 System. for (int i = 0.length.misc.. index + 2).println(b[i]). /* output : 072AFF81 */ b = hexStringToByteArray(byteArrayToHexString(b)). for (int i = 0. 14 Security .append('0'). i < b.! Now try to enter a password : howTo Wrong. if (v < 16) { sb. 16)..toString(). i < b. FF.Input your secret password : howto the encrypted result : ûóbf−m¦esd Now try to enter a password : Howto Wrong.getBytes()). One technique is to encode using Base64 the encrypted string. −127 }. } return sb.! Now try to enter a password : howto You got it! If you need to save the encrypted string into a file. 2A. 42.toHexString(v)).

} public static void main(String args[]) { try { System.toString( ( b[i] & 0xff ) + 0x100. } return b.close().out. } } 14.com/javadetails/. if (numRead > 0) { complete. } // see this How−to for a faster way to convert // a byte array to a HEX string public static String getMD5Checksum(String filename) throws Exception { byte[] b = createChecksum(filename).5. String result = "".substring( 1 ). MessageDigest complete = MessageDigest.. public class MD5Checksum { public static byte[] createChecksum(String filename) throws Exception { InputStream fis = new FileInputStream(filename). int numRead.length.MessageDigest.digest().*.security. byte[] buffer = new byte[1024].update(buffer. i < b. import java.3 Create a checksum Current version of this HowTo : http://www.17. do { numRead = fis.5. } return result.exe. 16).read(buffer). for (int i=0.getInstance("MD5"). fis.rgagnon.b[i] = (byte)v./javadetails/java−0416.MD5 14.println(getMD5Checksum("apache−tomcat−5.17. i++) { result += Integer.3 Create a checksum .17/bin // /apache−tomcat−5.io.apache.org/dist/ // tomcat/tomcat−5/v5. A user can compare a published MD5 sum with the checksum of a downloaded file. import java.html MD5 digests have been widely used in the software world to provide some assurance that a downloaded file has not been altered. numRead). } } while (numRead != −1). return complete.exe")). 0. // output : // 0bb2827c5eacf570b6064e24e0e6653b // ref : // http://www.5.

*.exit(new Checksum(). } } public int create(String filename){ try { byte[] chk = createChecksum(filename).exe } catch (Exception e) { e. InputStream is = new FileInputStream(f).create(args[1])). } } else { System.out.length].*.chk").io. } } } The next example is used to create a .exit(new Checksum().17.println("Usage : java Checksum create [filename]\n"+ " java Checksum check [filename]"). OutputStream os = new FileOutputStream(f). } } public int check(String filename){ int rc = 0. } else if (args[0].close(). try { byte[] chk1 = createChecksum(filename).printStackTrace(). } catch(Exception e) { e.5. File f = new File(filename + ". return 1. The same program is used to check if a file has been altered by looking at previously generated . File f = new File(filename + ".length == 2) { if (args[0].write(chk).3 Create a checksum .security.equals("check")) { System.check(args[1])). os. import java. public class Checksum { // // returns 0 error // 1 ok (create) // 1 same (check) // 2 different (check) // public static void main(String args[]) { if (args.// 0bb2827c5eacf570b6064e24e0e6653b *apache−tomcat−5. byte[] chk2 = new byte[chk1. return 0. os.chk").chk file and compared with current checksum of the given file.equals("create")) { System.printStackTrace(). import java.chk file which contains a MD5 checksum of a given file. 14.

} is. do { numRead = fis. int len = 0. while ((len = is. import java.close(). rc = 2. 0.close(). 14.getInstance("MD5").err.CRC32.printStackTrace(). } else { System.update(buffer.read(buffer).digest().read(chk2).*.out.println("Different!"). int numRead. numRead).update(bytes. byte[] buffer = new byte[1024]. public class ComputeCRC32 { public static long getChecksumValue(Checksum checksum. len).out. byte[] bytes = new byte[1024].util.util. if (numRead > 0) { complete.getValue().Checksum.is. } } public byte[] createChecksum(String filename) throws Exception{ InputStream fis = new FileInputStream(filename).io.zip. if (new String(chk2). import java.equals(new String(chk1))) { System. } public static void main(String[] args) { if (args. } } The java. } catch(Exception e) { e.close(). return rc.printStackTrace(). import java. return rc.println("Same!").zip package can be used to create a checksum.util.length != 1) { System. 0. String fname) { try { BufferedInputStream is = new BufferedInputStream( new FileInputStream(fname)).3 Create a checksum . } catch (IOException e) { e. return complete. } } while (numRead != −1). MessageDigest complete = MessageDigest.println("Usage: java ComputeCRC32 <file>"). rc = 1.read(bytes)) >= 0) { checksum. } is.zip. } return checksum. fis.

out.com/javadetails/. 2. 1..sun. System.5 Get username using NT Challenge (NTLM) Current version of this HowTo : http://www.name").System.5 public class Test { public static void main(String args[]) { com. On the server./javadetails/java−0048.4 Get the user name .out.4 Get the user name Current version of this HowTo : http://www. If both MD5 are identicals then the password is good.security../javadetails/java−0441.sun. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 14.auth. System. or in JDK1. } } MD5 checksum can be used to validate a password without passing the actual password. username = System. do the same and compare the MD5 sums. The client appends his password to the random string.module. If you find this article useful.println(NTSystem. The server sends a random string to the client. 3. args[0]).module.exit(1). } long cs = getChecksumValue(new CRC32().NTSystem NTSystem = new com. something like an ASP page can be used to detect the current NT user name if the client is configured correcty. See this related HowTo for a JSP hack! 14.getProperty("user.html In application : String username. consider making a small donation to show your support for this Web site and its content.getName()).rgagnon. 4.com/javadetails/.auth.rgagnon. If you have access to a server−side.println("crc32 " + args[0] + " : " + cs).security. } } In Applet there is no way unless you ask for it or use a signed applet. and returns an MD5 sum of the result to the server.NTSystem().html 14.

z. (byte)'L'.BASE64Encoder(). z. (byte)'P'. The browser client must support NT Challenge authentification mechanism (IE does). length = msg[off+9]*256 + msg[off+8]. z. Beware. z. offset = msg[off+19]*256 + msg[off+18].SC_UNAUTHORIZED). z. (byte)1. it is possible to use it to extract the Windows username. and "by hand". out.trim()). return. (byte)130.jsp] <%@ page import="sun. z. This is a quick HACK to extract the username! There is no security into this. we ask the browser to identify the current user.println(s + " ").. length = msg[off+1]*256 + msg[off]. (byte)'S'.println(s + " "). length).misc. s = new String(msg.BASE64Encoder" %> <p><h1>Network Windows USERNAME without any login (ie)</h1></p> <% String auth = request. z.Even if the application server do not support NTLM protocol.filter:glow(Color=#009966. offset. // z. return. z.Strength=1)'>"). "NTLM " + new sun. "NTLM"). z. offset.setStatus(response. z.. (byte)'T'. (byte)'M'. } if (auth. z. s = new String(msg.4 Get the user name . z. z. [username. } else if (msg[8] == 3) { off = 30. (byte)2.substring(5)). z.setHeader("WWW−Authenticate". z. response. z. z. length).misc. z. (byte)2. From the server. width:190. offset.encodeBuffer(msg1). byte z = 0. offset = msg[off+3]*256 + msg[off+2]. z. offset. (byte)2. s = new String(msg. z}.setHeader("WWW−Authenticate". } else return. length = msg[off+17]*256 + msg[off+16].misc. String s. //out. z. if (msg[8] == 1) { off = 18. offset = msg[off+11]*256 + msg[off+10].decodeBuffer(auth.getHeader("Authorization"). int off = 0. length). z.BASE64Decoder(). length. (byte)40. (byte)'S'." + " height:10. z.SC_UNAUTHORIZED). // response.startsWith("NTLM ")) { byte[] msg = new sun. z. response.setStatus(response. if (auth == null) { response. byte[] msg1 = {(byte)'N'. 14. z. we extract the response from the answer. //out. (byte)2.println("Hello <span style='position:relative.

jsp http://www.net/jaas/index.replaceAll("[^a−zA−Z\s]".html You can connect to the ActiveDirectory or use some API but an easy way is to use a connection to SQL Server.luigidragone.com/javadetails/. Sun provides support for NTLM."").com/networking/ntlm.2.html A separate thread is used to send to the console the backspace character to erase the last−typed character. whatever username the user put in will be passed to the "NTLM program". look: s. A comment from A. At that time.6 Check if the current user belongs a specific Windows group/role .2/changes. Either group or role is not valid. I removed everything is not a word or space./pbdetails/pb−0227. see http://java.innovation.out.com/javadetails/.6 Check if the current user belongs a specific Windows group/role Current version of this HowTo : http://www..4.html http://free.tagish.ch/java/ntlm. Since the user is not authenticated. so I did a silly workaround in the midtime.println(s + "</SPAN>"). If the security setting is at high.html Starting from jdk1. 14.com/j2se/1. You want to deeper into this subject. then a window will prompt user for input.. Current user is a member of group or role.rgagnon. Santana : It didn't work for Firefox. any user can pretend to be anybody else as long as he has his security level set as high. } %></BODY> NOTES: A comment from Weijun Ji : This technique only works if a user has its IE browser security setting set at middle/low (or if the server is trusted like in an intranet environment).html#networking For a complete solution see JCIFS (for Tomcat and others) at http://jcifs.4. you have no way to know if this user is a true user or not. Send the query : SELECT is_member('mydomain\g_dept') and the result can be 0 1 NULL Current user is not a member of group or role./javadetails/java−0375.. With this setting.org 14..7 Prompt for password from the console Current version of this HowTo : http://www. In this way. take a look at these sites : http://www. browser will grab login username automatically.rgagnon. 14.sun.samba.

This can be be very dangerous if the data is stored into a database and displayed to other users. System. if ((cons = System.8 Prevent XSS exploit .html There are two ways to deal with this issue.console()) != null & (passwd = cons.out.*.. "Password:")) != null) { .out. } } public synchronized void halt() { running = false.*.8 Prevent XSS exploit Current version of this HowTo : http://www.readLine(). consoleEraser.import java.com/javadetails/.print("\b ").print("\b")..html According to Wikipedia. 14. System.readPassword("[%s]".print("Password? "). Here a list of XSS test cases : http://ha. BufferedReader stdin = new BufferedReader(new InputStreamReader(System. public class PwdConsole { public static void main(String[] args) throws Exception { ConsoleEraser consoleEraser = new ConsoleEraser(). String pass = stdin.com/app?name=John then a malicious user can build a special URL like http://www...ckers. System. </script> to "inject" his own script into your web app.awt.com/app?name=<script> . char[] passwd..out. java.io.io.server.org/xss. public void run() { while (running) { System.out.halt(). } } Java SE6 provides a buiilt−in mechanism to input a password from the console. } } class ConsoleEraser extends Thread { private boolean running = true. } 14. import java. If your WebApp expects a URL like http://www.Console cons. XSS exploit is a type of computer security vulnerability found in web applications which allow code injection by malicious web users into the web pages viewed by other users./javadetails/java−0627.server.start().in)).println("Password: '" + pass + "'").rgagnon. consoleEraser.

public static String sanitize(String string) { return string .*?>.*?>".replaceAll("(?i)<. The idea is to sanitize a string before displaying it a user. The JSTL taglib provides the tag <c:out .com/jstl/core" prefix="c" %> <c:set var="test" scope="session"> <script> alert("hello") </script> </c:set> <h1>out with escapeXml=true</h1> <c:out value="${test}" escapeXml="true" /><br> <br /> This JSP will not display the script code and the browser execute it.sun. "") // case 2 .com/jstl/core" prefix="c" %> <c:set var="test" scope="session"> <script> alert("hello") 14. While you can call yourself the method to sanitize the received parameters.*?>.*?</.*?</script. <c:out value="${foo}" escapeXml="true" /> The substitutions are : This JSP will display the script code and the browser will not execute it. "") // case 1 .9 Sanitize the input by removing suspicious tags. . This is done by replacing supicious characters by the corresponding entity. > tag to display a string. you should consider installing this process into a Java EE filter so the container will automatically do it for you.*?>". <%@ taglib uri="http://java. This tag will sanitize a string by default. "").*?javascript:.sun..replaceAll("(?i)<script.replaceAll("(?i)<.9 Sanitize the input by removing suspicious tags. This regex function removes the obvious code to inject unwanted scripting.*?</.com/programming/java/simple−cross−site−scripting−xss−servlet−filter/.*?>. <%@ taglib uri="http://java.10 Sanitize the output by removing suspicious characters. // case 3 } • (?i) make it case insensitive • case 1 : <script> are removed • case 2 : javascript: call are removed • case 3 : remove on* attributes like onLoad or onClick Nothing beats good validation but then make sure to sanitize the value if it fails before redisplaying it.*?\\s+on. 14..14. See this page at http://greatwebguy.*?>".

dispose(). password = login.id) { username = login.11 Display a simple username/password Dialog from an Applet Current version of this HowTo : http://www. password).println ("The password for " + username + " is " + (userValid?"valid":"invalid")).com/javadetails/.out.*. import java.</script> </c:set> <h1>out with escapeXml=false</h1> <c:out value="${test}" escapeXml="false" /><br> <br /> 14.html").*. userValid = validateUser(username .println ("Cancel was pressed."_top").out.password.username.applet.printStackTrace(). return userValid. public class MyApplet extends java.getText().. MyLogin login = new MyLogin (new Frame("")).11 Display a simple username/password Dialog from an Applet . } else System.showDocument (new URL(getCodeBase()+"accessdenied./javadetails/java−0128.net. requestFocus(). System.java] import java.Applet { public String username = "". public String password = "". } } else { // here the username and password are OK } } public boolean login() { boolean userValid = false. login. [MyApplet.rgagnon. } catch (Exception e) {e."). if (login.awt.getText(). 14.html NOTE: This way to authenticate a user is NOT secured at all since the required information is embedded in the Applet. public void init() { if (!login()) { try { getAppletContext().

add( p ).setLayout(new FlowLayout())..can. add(new Label("User :")). add(username).awt.equals("java") &pwd. } void addOKCancelPanel() { Panel p = new Panel(). createFrame(). pack(). TextField password.add(ok = new Button("OK")). createButtons( p ). } public void actionPerformed(ActionEvent ae){ if(ae. Button ok.} private boolean validateUser(String usr.*. p.add(can = new Button("Cancel")). p. ok. can. setLayout(new FlowLayout()). import java.height/3). } 14.awt.11 Display a simple username/password Dialog from an Applet . } } [MyLogin. } void createFrame() { Dimension d = getToolkit(). setVisible(true). } void createButtons(Panel p) { p.d.width/4.addActionListener(this).. "Welcome".addActionListener(this). public class MyLogin extends Dialog implements ActionListener { boolean id = false. setLocation(d.setEchoChar('*'). password.getScreenSize(). setVisible(false). username = new TextField(15). addOKCancelPanel().java] import java.*. for testing purpose : // username = java password = avaj return (usr.equals("avaj")). add(password). MyLogin(Frame frame){ super(frame. true). add(new Label("Password :")). password = new TextField(15). String pwd) { // here you will code some logic to validate the username // password.getSource() == ok) { id = true. TextField username.event.

else if(ae.html] <HTML><HEAD><BODY> <TABLE><TR><TD> <APPLET CODE=MyApplet.class WIDTH=300 HEIGHT=300> </APPLET></TABLE> NOTE: View the java console for infos about the login process </BODY></HEAD> </HMTL> A simple "Access is denied" page : [accessdenied.html] <HTML> access is denied </HMTL> Written and compiled Réal Gagnon ©2007 real@rgagnon.rgagnon.com http://www. } } } the HTML to test it out : [login.getSource() == can) { id = false.com 14. setVisible(false).11 Display a simple username/password Dialog from an Applet .

Enumeration keys = UIManager./javadetails/java−0335.3 Change component default font Current version of this HowTo : http://www.plaf.swing. it's recommended to use import javax.util.new Font("Serif". consider making a small donation to show your support for this Web site and its content.ITALIC.sun.12)).swing.2 release.swing. f). while (keys. 15.com/javadetails/.get (key).swing.*. Swing UI default If you find this article useful. // java.. Then you will need to use the <OBJECT> (IE) or <EMBED> (Netscape) HTML tag instead of the regular <APPLET> tag..Font. IE or Netscape don't support directly Swing Applet.15 Swing 15./javadetails/java−0193. } } For a particuliar component UIManager. You must use the Java plugins.12)). // ex.1 java−swing 15.FontUIResource // ("Serif".font".FontUIResource) UIManager.hasMoreElements()) { Object key = keys.plaf.html NOTE: With the JDK1. // setUIFont (new javax.Font.getDefaults().FontUIResource f){ // // sets the default font for all Swing components.plaf. 15 Swing .rgagnon.nextElement().keys().put("Label.swing. instead of import com.html public static void setUIFont (javax.java. Object value = UIManager.com/javadetails/.put (key.*. if (value instanceof javax.2 * Read me * Current version of this HowTo : http://www.rgagnon.ITALIC.

printStackTrace()./javadetails/java−0206.setLookAndFeel( UIManager.windows (no change) com.sun.swing.com/javadetails/.swing.plaf. } Even with the new naming mecanism in JDK1.swing.sun. Swing will use the Metal LookAndFeel. some LookAndFeel packages are keeping the oldname.java.com/javadetails/.jar file..Written and compiled by Réal Gagnon ©1998−2005 [ home ] 15. you can't activate the Mac LookAndFeel in a Windows environment.rgagnon.html There is some restriction to the usage of LookAndFeel when there are some copyright involved./javadetails/java−0208.basic (new) javax.. 15.4 Repaint problem under the mouse cursor (JDK1.multi (new) These packages are located in the rt./javadetails/java−0207. To set the LookAndFeel to the current OS under which the JVM is running.html By default.java. 15. use this snippet : try { UIManager.5 Set the LookAndFeel Current version of this HowTo : http://www. 15.java.plaf. Simply switch the mouse cursor to the regular Windows mouse cursor to correct the problem.rgagnon.plaf. For example.sun.html You probably have installed a Microsoft Theme on your desktop. } catch (Exception e) { e.2) .4 Repaint problem under the mouse cursor (JDK1.getSystemLookAndFeelClassName()).swing.com/javadetails/.6 Use any LookAndFeel on any plateform Current version of this HowTo : http://www.swing. Windows Motif Mac Metal Basic Multi com.rgagnon.plaf.plaf.2.plaf..mac (no change) javax.2) Current version of this HowTo : http://www.swing.metal (new) javax.motif (no change) com.

15. // not−so−sure look and feel System.*.printStackTrace().name".awt.windows.version".8 Share ActionEvent handler Current version of this HowTo : http://www. } catch (Exception ex) { ex. import javax.rgagnon. to activate Windows LookAndFeel on a non−Windows environment java −Dos. JToolbar and JButtons on a JFrame are sharing common ActionEvent handlers.swing. "5.plaf. "Mac").The trick is to fool Swing by setting the property os.getProperties().WindowsLookAndFeel"). It's not bad idea to set the look and feel to a known good value and then try the not−so−sure value.1").rgagnon.setProperty("os. UIManager. System.html In this example. import java. NOTE: Current Swing release for Windows does not include the necessary classes for the Mac's LookAndFeel anymore.setProperties(p).name to a different value than real one to enable the use of "forbidden" LookAndFeel. From the command line.GTKLookAndFeel").7 Use a Timer . } 15.put("os.event./javadetails/java−0212.setProperty("os. System.7 Use a Timer Current version of this HowTo : http://www.name". try { // sure look and feel UIManager.com/javadetails/.sun.plaf.setLookAndFeel( "com../javadetails/java−0220.html See this How−to.swing. 15.java. a JMenu.java.sun. p..name=windows MySwingApp to activate Mac LookAndFeel on a non−Mac environment java −Dos.com/javadetails/. "Windows").gtk.swing.name=mac MySwingApp or you can do it in your source by doing something like: Properties p = System.setLookAndFeel("com.*.

"bebye"). mb.*.dispatchEvent(ae).addActionListener(openAction).300). JButton b2 = new JButton("Save").setVisible(true). public static void main(String argv[]) { new ShareAction().add(openAction). file. pack(). getContentPane(). b3. file. JButton b1 = new JButton("Open"). bar.add(quitAction). setJMenuBar(mb). } public Dimension getPreferredSize() { return new Dimension(300.add(quitAction). createButtons(). } ShareAction() { createMenu(). createToolBar().add(bar. saveAction = new SaveAction(). JButton b3 = new JButton("Quit"). // deal closing via the upper right "X" by redirecting to // quitAction addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { ActionEvent ae = new ActionEvent (quitAction. quitAction = new QuitAction().addActionListener(saveAction). } } ). public class OpenAction SaveAction QuitAction ShareAction extends JFrame { openAction = new OpenAction(). JFrame j = (JFrame)e. bar.add(saveAction).getSource().7 Use a Timer .add(openAction).addActionListener(quitAction).add(file). b2.awt. j.add(saveAction). 15. } private void createButtons() { JPanel j = new JPanel().ACTION_PERFORMED. bar. file. JMenu file = new JMenu("File"). } private void createToolBar() { JToolBar bar = new JToolBar(). } private void createMenu(){ JMenuBar mb = new JMenuBar(). ActionEvent. "North").import java. b1.

add(b1)..9 Get default values for Swing−based user interface Current version of this HowTo : http://www.rgagnon. } } class OpenAction extends AbstractAction { public OpenAction() { super("Open".9 Get default values for Swing−based user interface .println("Save action").out.Iterator.swing.Comparator.gif")). j. new ImageIcon("quit. // this TreeSet will hold the sorted properties 15. } public void actionPerformed(ActionEvent e) { System.props import import import import import java. java.UIManager. } } class QuitAction extends AbstractAction { public QuitAction() { super("Quit". public class UIDefaults { public static void main(String[] args) { try { Set defaults = UIManager. } public void actionPerformed(ActionEvent e) { System./javadetails/java−0507.html This little class will dump to stdout the default values used by Swing. java. j. } public void actionPerformed(ActionEvent e) { System. getContentPane().j. } } class SaveAction extends AbstractAction { public SaveAction() { super("Save". new ImageIcon("save.util.out. } } 15.util.util.entrySet(). You can redirect the result to a file with >java UIDefaults > swing. java.com/javadetails/. "East").add(b2).add(b3). System.util.TreeSet. new ImageIcon("open.println("Open action").out.println("Bye.exit(0).").gif")).util.add(j.getLookAndFeelDefaults().gif")). import javax.Map.Set. System.println("Quit action").out. java.

return ((String) ea. see this HowTo • Here a sample list for JavaUIDefaults If you find this article useful.Entry eb = (Map. you can click on it to trigger an action or use this area to display notification. A small icon is located at the bottom right of the Desktop. for (Iterator i = ts. 15.Entry ea = (Map.out.getKey() + " = " ).awt.com/javadetails/.compareTo(((String)eb.addAll(defaults)./javadetails/java−0612.getValue()).next(). Map. consider making a small donation to show your support for this Web site and its content. javax.out.TreeSet ts = new TreeSet(new Comparator() { public int compare(Object a. i.swing.getKey()).out.getKey())).10 Have a systray icon (Windows) . ts.*. System.print(entry.hasNext(). Use this small image to run this demo : import import import import java.rgagnon.printStackTrace().html JDK 1.Entry entry = (Map.awt.Entry) a. java. } }).*.Entry) i.event. } } } • For an example on how to change a default value see this HowTo • To change a value for a particuliar component. public class SysTrayDemo { protected static TrayIcon trayIcon.10 Have a systray icon (Windows) Current version of this HowTo : http://www.6 provides support for the Systray on the Windows plateform.Entry) b.awt. private static PopupMenu createTrayMenu() { ActionListener exitListener = new ActionListener() { public void actionPerformed(ActionEvent e) { System.println(entry.image. } } catch (Exception ex) { ex..iterator(). java.*. System.*. Object b) { Map. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 15.println("Bye from the tray").) { Map.

getImage("/temp/trayrealhowto. return menu. "Java System Tray Demo".jpg"). trayIcon.addActionListener(exitListener). "You can do it again if you want!".exit(0). } /** * Loading the image from the classpath * if in a folder in a jar.System.add(exitItem).getResource("trayrealhowto.jpg */ private static TrayIcon createTrayIconFromResource() throws java. execItem.INFORMATION_MESSAGE). /img/realhowto. PopupMenu menu = new PopupMenu(). } /** * Loading the image from a file */ private static TrayIcon createTrayIconFromFile() { Image image = Toolkit. PopupMenu popup = createTrayMenu().addActionListener(executeListener). 15. "Java System Tray Demo".setImageAutoSize(true). "User action". "Popup from the action on the systray!".IOException { ClassLoader cldr = SysTrayDemo.MessageType. popup). TrayIcon ti = new TrayIcon(image.displayMessage ("Done". MenuItem exitItem = new MenuItem("Exit").getDefaultToolkit().10 Have a systray icon (Windows) .getImage(imageURL). "Java System Tray Demo". exitItem. popup). JOptionPane.warningIcon"). Image image = iconToImage(icon). popup).getDefaultToolkit(). ti.. ti.getClassLoader(). return ti.URL imageURL = cldr.getIcon("OptionPane. MenuItem execItem = new MenuItem("Action. PopupMenu popup = createTrayMenu(). TrayIcon. menu.io.net. TrayIcon ti = new TrayIcon(image.jpg")."). } }.class.add(execItem). return ti. java.. } /** * using a built−in icon * we need to convert the icon to an Image */ private static TrayIcon createTrayIconFromBuiltInIcon() { Icon icon = UIManager. Image image = Toolkit. TrayIcon ti = new TrayIcon(image.setImageAutoSize(true).INFO). ActionListener executeListener = new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane. remember to add the folder! * ex. PopupMenu popup = createTrayMenu().showMessageDialog (null. } }. menu.

getLocalGraphicsEnvironment(). trayIcon. icon.exit(1).displayMessage("Ready".*. //trayIcon = createTrayIconFromResource(). } try { SystemTray sysTray = SystemTray. //trayIcon = createTrayIconFromBuiltInIcon(). } else { int w = icon.exit(1).out.getImage().html import java.getIconWidth().awt.isSupported()) { System.dispose().getIconHeight(). "Tray icon started and tready". h). g. 0).createGraphics()..out. 15. GraphicsDevice gd = ge.11 Close a JFrame under condition Current version of this HowTo : http://www. 0.createCompatibleImage(w. } catch (AWTException e) { System.event.MessageType. BufferedImage image = gc.ti. return ti.getDefaultConfiguration().println("Unable to add icon to the system tray"). GraphicsEnvironment ge = GraphicsEnvironment. import java. a file in the classpath (resource) or use a built−in icon in the JDK. } } public static void main(String[] args) throws Exception { if (!SystemTray. TrayIcon. g. public class CloseOrNot extends JFrame { 15. trayIcon = createTrayIconFromFile(). Graphics2D g = image. } static Image iconToImage(Icon icon) { if (icon instanceof ImageIcon) { return ((ImageIcon)icon).getDefaultScreenDevice().*. int h = icon.com/javadetails/.paintIcon(null.add(trayIcon).*.INFO). } } } This code can load the icon from a file. System. sysTray. GraphicsConfiguration gc = gd. return image.awt. System. import javax.getSystemTray().11 Close a JFrame under condition ./javadetails/java−0340.setImageAutoSize(true).rgagnon.println ("System tray not supported on this platform").swing.

consider making a small donation to show your support for this Web site and its content.showConfirmDialog (null.getMaximumWindowBounds()).JTextField field1. } public static void main(String args[]) { new CloseOrNot().add( field1 ).com/javadetails/./javadetails/java−0479.equals("yes")) { if (JOptionPane. panel."Are you sure ?")==JOptionPane.getExtendedState() | this.MAXIMIZED_BOTH). addWindowListener( new WindowAdapter() { public void windowOpened( WindowEvent e ){ field1.rgagnon. } public void windowClosing( WindowEvent e ){ if (field1. import javax.DO_NOTHING_ON_CLOSE). the task will not be covered by the maximized JFRAME.awt. getContentPane().setMaximizedBounds(env.12 Maximize a JFrame . panel = new JPanel().getText(). field1 = new JTextField( 10 ).YES_OPTION) { setVisible(false).swing.requestFocus().setExtendedState(this. this.12 Maximize a JFrame Current version of this HowTo : http://www. */ // this. } } } } ). public CloseOrNot() { super( "CloseOrNot Frame" ). } 15. panel. setVisible( true ). panel ). dispose().*.html import java.*. pack(). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 15.. JPanel panel. } } If you find this article useful.add( new JLabel("type yes to close the Frame ")). setDefaultCloseOperation(JFrame. /* The next line determines if the taskbar (win) is covered if unremarked. public class TestMaxJFrame extends JFrame { public TestMaxJFrame() { GraphicsEnvironment env = GraphicsEnvironment.add( "Center".getLocalGraphicsEnvironment().

import java.public static void main(String[] args) { JFrame.com/javadetails/. You can choose weither or not you want to catch errors.out into a JFrame Current version of this HowTo : http://www.shtml) <br> * The origional author was Real Gagnon (real.13 Capture System.swing.*.html import java. * For more details.earthweb. TestMaxJFrame t = new TestMaxJFrame(). boolean logFile. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 15.gagnon@tactika.13 Capture System. int height.println) * RedirectedFrame * <p> * This class was downloaded from: * Java CodeGuru (http://codeguru.. log * them to a file and more.setDefaultLookAndFeelDecorated(true). int closeOperation.*. 15. int width. /** * http://tanksoftware. String fileName.setVisible(true). improving its customizability * * In breif.io. consider making a small donation to show your support for this Web site and its content.com). import javax. read the constructor method description */ public class RedirectedFrame extends JFrame { // Class information public static final String PROGRAM_NAME = "Redirect Frame". public static final String AUTHOR = "Real Gagnon − edited by William Denniss". public static final String VERSION_NUMBER = "1./javadetails/java−0435. public static final String DATE_UPDATED = "13 April 2001".rgagnon. this class captures all output to the system and prints it in * a frame. * William Denniss has edited the code.*.java * A Java Swing class that captures output to the command line ** (eg.com/java/articles/382.1".out. } } If you find this article useful.awt.out into a JFrame .com/juk/developer/src/com/ * tanksoftware/util/RedirectedFrame. t. System. private private private private private private boolean catchErrors.

* nor logs to the file.height = height. PrintStream aPrintStream = new PrintStream( new FilteredStream( new ByteArrayOutputStream())). * all System.logFile = logFile. this.out messages and error messages (if requested) * are diverted to this frame and appended to the log file * (if requested) * * for example: * RedirectedFrame outputFrame = * new RedirectedFrame (false.getDefaultToolkit().getImage("myicon. 600. Toolkit tk = Toolkit. // catches error messages // set the default closing operation to the one given setDefaultCloseOperation(closeOperation).out messages if (catchErrors) System.out into a JFrame . int width. setSize(width. this. hidden by a controlling * class by(using the example) outputFrame.TextArea aTextArea = new TextArea(). setIconImage(im). c.logFile = logFile.setLayout(new BorderLayout()). /** Creates a new RedirectFrame. this. Image im = tk. boolean logFile.catchErrors = catchErrors. setTitle("Output Frame"). c.setOut(aPrintStream).width = width.DO_NOTHING_ON_CLOSE).add("Center" . aTextArea). 700. } 15.fileName = fileName. with the dimentions 700x600 and it doesn't * close this frame can be toggled to visible.setErr(aPrintStream). Container c = getContentPane(). System. JFrame. displayLog(). int closeOperation) { this. * From the moment it is created. // catches System.13 Capture System. null. this.height). * this will create a new RedirectedFrame that doesn't catch errors. false.gif"). this.setVisible(true|false) * @param catchErrors set this to true if you want the errors to * also be caught * @param logFile set this to true if you want the output logged * @param fileName the name of the file it is to be logged to * @param width the width of the frame * @param height the height of the frame * @param closeOperation the default close operation * (this must be one of the WindowConstants) */ public RedirectedFrame (boolean catchErrors. int height. this. String fileName.closeOperation = closeOperation.

setVisible(true). aTextArea.html You can't have a border directly on a JWindow or JFrame..close().html ((javax.width) / 2.getScreenSize(). int off.14 Remove the titlebar of JInternalFrame Current version of this HowTo : http://www. off . setLocation((dim.width − abounds.height) / 2). } public void write(byte b[]) throws IOException { String aString = new String(b).15 Have borders on a JWindow/JFrame Current version of this HowTo : http://www./javadetails/java−0333. int len) throws IOException { String aString = new String(b . aWriter. if (logFile) { FileWriter aWriter = new FileWriter(fileName.class FilteredStream extends FilterOutputStream { public FilteredStream(OutputStream aStream) { super(aStream).com/javadetails/.basic. } public void write(byte b[]. len).height − abounds.append(aString).setNorthPane(null). } } If you find this article useful. (dim.swing.rgagnon. Dimension dd = getSize(). requestFocus().rgagnon. You need to put a JPanel with the desired border using the default JWindow/JFrame LayouManager (a BorderLayout). aWriter.com/javadetails/. aTextArea.write(aString). Then the JPanel is extended giving the impression that its borders are the JWindow one. Rectangle abounds = getBounds(). } } } private void displayLog() { Dimension dim = getToolkit(). 15.plaf. consider making a small donation to show your support for this Web site and its content.BasicInternalFrameUI) myInternalFrame. true)..14 Remove the titlebar of JInternalFrame . Written and compiled by Réal Gagnon ©1998−2005 [ home ] 15.getUI())./javadetails/java−0204.append(aString). 15.

} catch (Exception e) { e.*. java.tactika. URL url = getClass().printStackTrace().*. javax.awt.*.16 Display HTML in a JScrollPane Current version of this HowTo : http://www. import import import import javax.awt. pan.html")..add(pan.import import import import javax. win. tp. try { URL url = new URL("http://www.*.add(js). JPanel pan = new JPanel().add(tp).com/javadetails/.pack().setBorder(new LineBorder(Color.html The JTextPane can display simple HTML page.*.awt.*. pan.16 Display HTML in a JScrollPane .swing. JFrame jf = new JFrame()..swing.setLayout(new FlowLayout()).add(new JButton("Hello")).setSize(200. jf. java. public class TestShowPage { public static void main(String args[]) { JTextPane tp = new JTextPane(). win.. win.200).border. .setVisible(true).500).*."Center").blue)). } } 15. pan.awt. js.html"). 15.getViewport().event.setSize(400.setPage(url). jf.swing.net./javadetails/java−0205. jf.rgagnon.*.setVisible(true). } } } If the HTML is a located into a jar. public class MyWindow{ public static void main(String s[]) { JWindow win = new JWindow().add(new JButton("World")).event.getContentPane(). jf. java. java. java. pan.getResource("contents.getContentPane().com/realhome/contents. JScrollPane js = new JScrollPane().

YES_NO_OPTION).setPage(new URL(url.17 Use a JOptionPane Current version of this HowTo : http://www..YES_NO_CANCEL_OPTION).awt../javadetails/java−0376. } 15.17 Use a JOptionPane . return result. JOptionPane. theMessage. import java. public class MessageBox { /* These are a list of STATIC MODAL dialogs int return codes of button pressed: −1 0 1 2 − − − − WINDOW CLOSED − the X PRESSED YES and OK NO CANCEL (thanks to flipside for the idea) */ public static int yesno(String theMessage){ int result = JOptionPane.getResource("contents. "alert".html"). tp. to set an anchor. . return result.. JOptionPane.showConfirmDialog((Component) null. import javax.. 15. .awt. "alert". . "alert".html import java.DEFAULT_OPTION).*. theMessage.*. "alert".swing. URL url = getClass().setPage(url). return result. theMessage..showConfirmDialog((Component) null. theMessage.*.com/javadetails/..tp.event. } public static int okcancel(String theMessage){ int result = JOptionPane.showConfirmDialog((Component) null. JOptionPane. you get the URL then add the "#anchor".rgagnon.. } public static int ok(String theMessage){ int result = JOptionPane. } public static int yesnocancel(String theMessage){ int result = JOptionPane. return result.toExternalForm() + "#section42")).OK_CANCEL_OPTION). JOptionPane.showConfirmDialog((Component) null.

println("ret : " + i ).awt. // default value button = new JRadioButton("English". one for english . System.out.yesnocancel("Are your sure ?"). java. public MessageBoxExample() { group = new ButtonGroup(). true). 15. String msg .add(button). button.*.").public static void main(String args[]){ int i = MessageBox. [JOptionPane_en. System. } } 15. Locale locale.html This example will show 2 radio buttons.properties] Yes=Yes No=No Cancel=Cancel SaveMsg=Do you want to save your data [JOptionPane_fr.out. public class MessageBoxExample extends JPanel implements ActionListener { JButton go. group.*. java.rgagnon. i = MessageBox.println("ret : " + i ).com/javadetails/.ok("Done.setActionCommand("en").properties] Yes=Oui No=Non Cancel=Annuler SaveMsg=Voulez−vous sauvegarder vos donnees Then import import import import javax. Press the button to display a localized JOptionPane according to the radio button selected. System. locale = Locale.out.18 Localize a JOptionPane dialog Current version of this HowTo : http://www. i = MessageBox. Create 2 properties files.swing. add(button).event.util. button..okcancel("Are your sure ?").out. java.*.println("ret : " + i ). ButtonGroup group. one for french.*.yesno("Are your sure ?").US. System. i = MessageBox./javadetails/java−0138.awt.18 Localize a JOptionPane dialog . one for english messages and buttons and the other one for french.addActionListener(this). AbstractButton button.println("ret : " + i ).

rb.showConfirmDialog(this. } public void actionPerformed(ActionEvent e) { int result. go = new JButton("Do it").add(panel.addActionListener(this). MessageBoxExample panel = new MessageBoxExample(). System. rb = ResourceBundle.18 Localize a JOptionPane dialog . if (e.getString("Cancel")). } public void setUILanguage() { ResourceBundle rb.getContentPane(). msg = rb.setVisible(true). frame.noButtonText". } } ). else locale = Locale.setSize(panel.put("OptionPane. add(button). locale = Locale.equals("en")) locale = Locale. go.put("OptionPane.put("OptionPane.add(button).getString("Yes")).getString("SaveMsg").cancelButtonText".button = new JRadioButton("Francais").getString("No")).addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0).getActionCommand(). } else { // the button action result = JOptionPane.yesButtonText". frame."Center"). } } 15.FRANCE. } } public Dimension getPreferredSize(){ return new Dimension(200.getSource() instanceof JRadioButton) { if (e.println(result).out. rb. locale).getPreferredSize()). rb. } public static void main(String s[]) { JFrame frame = new JFrame(""). frame. UIManager.setActionCommand("fr"). add(go).US.US. 200). button. setUILanguage().getBundle("JOptionPane".msg). UIManager. button. frame. group.addActionListener(this). UIManager.

The language is choosen based on the current Locale. "No". So you don't have to do anything to display the JFileChooser in the right language. } else { System.0.. "Confirmation". buttons.com/javadetails/. one for french (these files are incomplete but should be enough to get you started).19 Customize JOptionPane buttons .WARNING_MESSAGE./javadetails/java−0310. null."). } 15. "Yes to all".properties] 15. one for french.println(buttons[rc] + " was clicked")./javadetails/java−0299.out.html Modern Swing release have now built−in ready−to−use translations for the JFileChooser. as well as messages produced by the tools provided with the JRE. buttons[2]). if (rc==−1) { System.properties] Title=Real's JFileChooser lookInLabelText=Current filesOfTypeLabelText=File type upFolderToolTipText=go up [JFileChooser_fr.println("Dialog closed without clicking a button. These user interface elements are localized into the following languages: Sun Supported Locales This example will show 2 radio buttons.com/javadetails/. [JFileChooser_en. one for english .rgagnon.rgagnon. The user interface elements provided by the J2SE Runtime Environment 5. "Cancel"}. include Swing dialogs. Press the button to display a localized JFileChooser according to the radio button selected.15. Create 2 properties files. 0.showOptionDialog(null. JOptionPane.19 Customize JOptionPane buttons Current version of this HowTo : http://www. "Do you really want to delete this file [" + filename + "]?".html String[] buttons = {"Yes".. one for english.out.20 Localize a JFileChooser Current version of this HowTo : http://www. messages written by the runtime environment to the standard output and standard error streams. int rc = JOptionPane.

go.*.getString("lookInLabelText")). button. go = new JButton("Do it").US.event. rb = ResourceBundle.add(button).util. AbstractButton button.Title=JFileChooser de R\u00e9al lookInLabelText=Courant filesOfTypeLabelText=Type de fichier upFolderToolTipText=Remonte Then [LocalizeJFileChooser. protected JFileChooser z_chooser. true). button = new JRadioButton("Francais").put ("FileChooser. button. group. Locale locale.lookInLabelText". locale). public class LocalizeJFileChooser extends JPanel implements ActionListener { JButton go. String z_choosertitle. button. button.swing. add(button). UIManager.getString("Title"). ButtonGroup group.addActionListener(this). rb. java.filesOfTypeLabelText". 15.*. locale = Locale. locale = Locale.setActionCommand("en"). UIManager.add(button).setActionCommand("fr"). String msg . } public void setUILanguage() { ResourceBundle rb.awt. add(button).addActionListener(this).US.*. add(go). z_choosertitle = rb. // default value button = new JRadioButton("English".addActionListener(this).awt.java] import import import import javax. public LocalizeJFileChooser() { group = new ButtonGroup().19 Customize JOptionPane buttons . rb. java.*. java.getBundle("JFileChooser".put ("FileChooser. group.getString("filesOfTypeLabelText")).

homeFolderToolTipText FileChooser.File(".updateButtonToolTipText=Update FileChooser.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System. */ } public void actionPerformed(ActionEvent e) { int result. z_chooser.FRANCE. else locale = Locale.put ("FileChooser.getActionCommand().saveButtonToolTipText=Save FileChooser.helpButtonToolTipText=Help Almost all Swing widgets can be customize this way. } } 15.newFolderToolTipText FileChooser.exit(0).setDialogTitle(z_choosertitle).upFolderToolTipText".openButtonText=Open FileChooser.helpButtonText=Help FileChooser.getString("upFolderToolTipText")). z_chooser. if (e. You can examine the Swing sources to get these values or check http://www.setCurrentDirectory(new java.com/papers/plafdiff.detailsViewButtonToolTipText FileChooser.updateButtonText=Update FileChooser. } public static void main(String s[]) { JFrame frame = new JFrame("").listViewButtonToolTipTextlist FileChooser.UIManager.cancelButtonToolTipText=Cancel FileChooser. 200).showOpenDialog(this) != JFileChooser. /* do the same with : FileChooser.equals("en")) locale = Locale.19 Customize JOptionPane buttons .APPROVE_OPTION) return.html for a list of them. setUILanguage().io.saveButtonText=Save FileChooser.getSource() instanceof JRadioButton) { if (e. frame. } } public Dimension getPreferredSize(){ return new Dimension(200.")).openButtonToolTipText=Open FileChooser. } else { z_chooser = new JFileChooser().fileNameLabelText FileChooser.US.gargoylesoftware. rb.cancelButtonText=Cancel FileChooser. LocalizeJFileChooser panel = new LocalizeJFileChooser(). if (z_chooser.

swing./javadetails/java−0370. go.util. // // disable the "All files" option.getSelectedFile()). java. 200). } else { System.setAcceptAllFileFilterUsed(false). } public void actionPerformed(ActionEvent e) { int result. } } 15. add(go).*.getContentPane().addActionListener(this). // if (chooser.setCurrentDirectory(new java. 15. JFileChooser chooser.*..event.awt.getPreferredSize())."Center"). chooser.println("getSelectedFile() : " + chooser.setDialogTitle(choosertitle).out.showOpenDialog(this) == JFileChooser.println("No Selection ").setSize(panel.out. java. } } public Dimension getPreferredSize(){ return new Dimension(200. frame.com/javadetails/.rgagnon.io.DIRECTORIES_ONLY). } public static void main(String s[]) { JFrame frame = new JFrame(""). chooser. frame.out.add(panel. System.*.println("getCurrentDirectory(): " + chooser.). String choosertitle.*.setVisible(true).getCurrentDirectory()).html import import import import javax.setFileSelectionMode(JFileChooser.APPROVE_OPTION) { System.awt. public DemoJFileChooser() { go = new JButton("Do it"). frame.")).21 Select a directory with a JFileChooser Current version of this HowTo : http://www.21 Select a directory with a JFileChooser . chooser = new JFileChooser(). chooser. public class DemoJFileChooser extends JPanel implements ActionListener { JButton go. // chooser.File(". java.

frame.println("getCurrentDirectory(): " 15.event.*.util."Center").*.awt.getPreferredSize()).swing. public DemoJFileChooser() { go = new JButton("Do it")./javadetails/java−0569. if (rc == JFileChooser. } public void actionPerformed(ActionEvent e) { int result.addActionListener(this). java. JFileChooser chooser. chooser = new JFileChooser().")).setSize(panel. String choosertitle. go.awt.out. frame. import import import import javax. public class DemoJFileChooser extends JPanel implements ActionListener { JButton go.com/javadetails/. frame.showOpenDialog(this). } } ).add(panel.io.*.*.22 Disable the JFileChooser's "New folder" button .22 Disable the JFileChooser's "New folder" button Current version of this HowTo : http://www. chooser. frame. java. You need to iterate the JFileChooser components until the right one and disable it. consider making a small donation to show your support for this Web site and its content.APPROVE_OPTION) { System. chooser. // int rc = chooser.DemoJFileChooser panel = new DemoJFileChooser().setCurrentDirectory(new java. } } If you find this article useful.html No easy way to disable the "New Folder" button.getContentPane().setVisible(true). java.exit(0). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 15.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.rgagnon. disableNewFolderButton(chooser).File(". add(go)..setDialogTitle(choosertitle).

frame.setVisible(true). public class DemoJFileChooser extends JPanel implements ActionListener { 15..println("getSelectedFile() : " + chooser.getIcon("FileChooser.awt.newFolderIcon")) b.*. } public static void main(String s[]) { JFrame frame = new JFrame(""). i < len. DemoJFileChooser panel = new DemoJFileChooser().event.getIcon().addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System. java.awt. frame.swing. } } ). frame. for (int i = 0. 200).exit(0). java.*. } } public void disableNewFolderButton( Container c ) { int len = c./javadetails/java−0568.getPreferredSize()).getComponent(i).getComponentCount(). i++) { Component comp = c.getSelectedFile()). if (icon != null && icon == UIManager.*.com/javadetails/.getCurrentDirectory()). java.html import import import import javax.23 Validate a filename from a JFileChooser .23 Validate a filename from a JFileChooser Current version of this HowTo : http://www.out. frame.+ chooser.out. Icon icon = b. } else if (comp instanceof Container) { disableNewFolderButton((Container)comp). } else { System.getContentPane(). } } 15.util.setSize(panel.setEnabled(false). if (comp instanceof JButton) { JButton b = (JButton)comp.println("No Selection!")."Center").rgagnon. } } } public Dimension getPreferredSize(){ return new Dimension(200.*. System.add(panel.

15.setVisible(true).ERROR_MESSAGE).matches(regexp) // while(rc == JFileChooser.exit(0). frame.getSelectedFile(). } public void actionPerformed(ActionEvent e) { int result.showOpenDialog(this). } } public Dimension getPreferredSize(){ return new Dimension(200. // int rc = chooser.java")){ JOptionPane."Center").io.getContentPane().getCurrentDirectory()). } public static void main(String s[]) { JFrame frame = new JFrame("").java file is selected // // possible to perform complex validation // using a regular expression with . } } ).")).getName().println("getCurrentDirectory(): " + chooser. "Open Error".addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System. chooser = new JFileChooser(). DemoJFileChooser panel = new DemoJFileChooser().setDialogTitle(choosertitle). } else { System.out.File(".add(panel. JFileChooser chooser.JButton go.out.setCurrentDirectory(new java. frame.getSelectedFile() + " is not java source file. rc = chooser.addActionListener(this). String choosertitle.showMessageDialog(null. add(go). System. chooser.getSelectedFile()). public DemoJFileChooser() { go = new JButton("Do it").APPROVE_OPTION && !chooser.setSize(panel. chooser.println("getSelectedFile() : " + chooser.out. "The file " + chooser. frame. JOptionPane. // // loop until a .println("No Selection!").endsWith(".APPROVE_OPTION) { System.". go. frame. } if (rc == JFileChooser.getPreferredSize()). 200).23 Validate a filename from a JFileChooser .showOpenDialog(this).

SwingUtilities.event.awt.swing.event. java.awt.JLabel. java.awt. import import import import import import import import import java. javax.ActionListener.invokeLater(new Runnable(){ public void run(){ new JFrameWithNoMinMax(). getRootPane().} } 15. //addWindowListener(new WindowAdapter(){ // public void windowClosing(WindowEvent e) { // System. // } //})..JFrame. setUndecorated(true).JButton. javax.out. } private void createAndShowUI(){ setTitle("This JFRAME looks like JDialog").swing. } }).WindowAdapter. javax. setSize(new Dimension(500. java.100)).WindowEvent. setLocationRelativeTo(null).html Make a JFrame unresizable and with no min/max button. } } 15.swing.println("Window Closing"). The difference with JDialog is that a JFrame is shown on the taskbar (win) while a JDialog is not.swing. setDefaultCloseOperation(EXIT_ON_CLOSE).exit(0).swing.setWindowDecorationStyle(JRootPane. public class JFrameWithNoMinMax extends JFrame { public JFrameWithNoMinMax() { createAndShowUI(). javax.Dimension.awt. javax./javadetails/java−0582.PLAIN_DIALOG).event. // System. } public static void main(String[] args){ SwingUtilities.24 Make a JFrame looks like a JDialog .rgagnon.setVisible(true).24 Make a JFrame looks like a JDialog Current version of this HowTo : http://www. setResizable(false).com/javadetails/.JRootPane.

26 Apply special filter to a JtextField Current version of this HowTo : http://www.25 Based on JTextField content.setLayout(new FlowLayout()).. JTextField textfield. } public void disableIfEmpty(DocumentEvent e) { button.*.getLength() > 0).*. document.rgagnon. enable or disable a JButton Current version of this HowTo : http://www. document = textfield.com/javadetails/.getDocument().25 Based on JTextField content.html import import import import java. Document document. public void init() { getContentPane().awt.getDocument(). button = new JButton("foo").swing.add(button). public class DemoJButtonDisabled extends JApplet { JButton button.com/javadetails/. textfield = new JTextField(10).*./javadetails/java−0197.swing. } public void insertUpdate(DocumentEvent e){ disableIfEmpty(e). javax. getContentPane(). } } class JButtonStateController implements DocumentListener { private JButton button.html 15.setEnabled(false). } public void removeUpdate(DocumentEvent e){ disableIfEmpty(e). javax.event.setEnabled(e. JButtonStateController(JButton b) { button = b. enable or disable a JButton ..addDocumentListener (new JButtonStateController(button)).15.swing. } public void changedUpdate(DocumentEvent e) { disableIfEmpty(e). javax. button./javadetails/java−0196.rgagnon.*. } } 15.add(textfield). getContentPane().text.

enable or disable a JButton .") != −1) { return. AttributeSet attr) throws BadLocationException { if (str == null) return.equals(FLOAT) || (acceptedChars. public static final String NUMERIC = "0123456789".*. import javax.The following class will help a JTextField to filter numeric or alphanumeric characters. getLength()). acceptedChars += "−".indexOf(".length(). public static final String FLOAT = NUMERIC + ". } if (acceptedChars. } } public void insertString (int offset. else if (acceptedChars.". public class JTextFieldFilter extends PlainDocument { public static final String LOWERCASE = "abcdefghijklmnopqrstuvwxyz". } public void setNegativeAccepted(boolean negativeaccepted) { if (acceptedChars. if (acceptedChars.equals(FLOAT) || acceptedChars.indexOf(". protected boolean negativeAccepted = false.equals(NUMERIC) || acceptedChars.indexOf("−") != −1) { 15. import javax.") != −1) { if (getText(0.equals(UPPERCASE)) str = str. public static final String UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toLowerCase().equals(LOWERCASE)) str = str. String str.text.charAt(i))) == −1) return. public JTextFieldFilter() { this(ALPHA_NUMERIC). i <str. public static final String ALPHA = LOWERCASE + UPPERCASE.25 Based on JTextField content.swing.equals(ALPHA_NUMERIC)){ negativeAccepted = negativeaccepted. for (int i=0.equals(FLOAT + "−") &negativeAccepted)) { if (str.toUpperCase().valueOf(str.*.swing. protected String acceptedChars = null. } } } if (negativeAccepted &str. public static final String ALPHA_NUMERIC = ALPHA + NUMERIC. i++) { if (acceptedChars. } public JTextFieldFilter(String acceptedchars) { acceptedChars = acceptedchars.indexOf(str.

public void init() { getContentPane(). getContentPane().add(l3). } } super. getContentPane(). tf1b = new JTextField(10). tf2 = new JTextField(10). str. tf1 = new JTextField(10). getContentPane().setLayout(new FlowLayout()).l2. enable or disable a JButton . tf1. getContentPane().FLOAT)). // l3 = new JLabel("only 'abc123%$'"). tf2.if (str. getContentPane().setDocument (new JTextFieldFilter(JTextFieldFilter.add(l1).add(tf3).tf1b. tf1c.setDocument (new JTextFieldFilter(JTextFieldFilter.add(l2). // l1 = new JLabel("only numerics").14.add(tf1b). } } import java.setDocument(jtff). attr). JLabel l1.indexOf("−") != 0 || offset != 0 ) { return. tf3 = new JTextField(10).*. // l1b = new JLabel("only float").awt. You can provide an input mask like (###) 15.add(l1b).add(tf2).setDocument (new JTextFieldFilter("abc123%$")).tf3.FLOAT). tf3. getContentPane().add(l1c). } } With JDK.tf1c.setNegativeAccepted(true).add(tf1).l1c. // l1c = new JLabel("only float(can be negative)"). tf1b. jtff.add(tf1c). import javax. // l2 = new JLabel("only uppercase").*. getContentPane().swing.l1b.25 Based on JTextField content. you have the JFormattedTextField class.UPPERCASE)). JTextFieldFilter jtff = new JTextFieldFilter(JTextFieldFilter.NUMERIC)).l3. getContentPane().insertString(offset.setDocument (new JTextFieldFilter(JTextFieldFilter. public class TESTJTextFieldFilter extends JApplet{ JTextField tf1. getContentPane(). getContentPane().tf2. tf1c = new JTextField(10).

sun. boolean upper) { super().EXIT_ON_CLOSE). public class JTextFieldLimit extends PlainDocument { private int limit.27 Limit JTextField input to a maximum length Current version of this HowTo : http://www. } public void insertString (int offset. this.setDefaultCloseOperation(JFrame.PAGE_AXIS)).length()) <= limit) { if (toUppercase) str = str. attr). Container content = f. JTextFieldLimit(int limit) { super(). import import import import java.limit = limit. } JTextFieldLimit(int limit. JFormattedTextField ftf1 = new JFormattedTextField(mf1). public class FormattedSample { public static void main (String args[]) throws ParseException { JFrame f = new JFrame("JFormattedTextField Sample").*.swing. and it will not accept any input that doesn't follow that format. // optional uppercase conversion private boolean toUppercase = false.getContentPane(). content..27 Limit JTextField input to a maximum length .setPlaceholderCharacter('_'). JFormattedTextField ftf2 = new JFormattedTextField(mf2). } } 15. javax. content. } } 15. BoxLayout. // telephone number MaskFormatter mf2 = new MaskFormatter("(###) ###−####").add(ftf1). java. this.###−#### for a telephone number. 100). javax.setLayout(new BoxLayout(content.java.setSize(300.ParseException.add(ftf2).toUpperCase().com/javadetails/.html import com.rgagnon.*. super.text.swing./javadetails/java−0198. content. toUppercase = upper. // canadian Social Security Number MaskFormatter mf1 = new MaskFormatter("###−###−###"). f. f. mf1.awt.text. str.limit = limit. AttributeSet attr) throws BadLocationException { if (str == null) return. String str.text.swing. f.*. if ((getLength() + str.insertString(offset.setVisible(true).Container.

and request the focus for the previous component (if there is a validation error).setLayout(new FlowLayout()). textfield1 = new JTextField(15). This can be done with invokeLater method of the SwingUtilities class.getText(). } } 15. public void init() { getContentPane().html The problem is when the lostFocus occurs on a Component. getContentPane().28 Validate a value on the lostFocus event . import java.*. getContentPane().28 Validate a value on the lostFocus event Current version of this HowTo : http://www. import javax.swing. import java. We can't use Toolkit. 15.add(tf2). // label = new JLabel("must be 'a' or 'b' ").add(textfield1). import javax.swing. public void focusLost(FocusEvent e) { if (!e.awt.. textfield1.add(tf1).*. tf2.add(label1). JLabel label1. public class DemoLostFocus extends JApplet { JTextField tf1.getSystemEventQueue() directly to remove the gainedFocus event because of security restriction in Applet. getContentPane().addFocusListener( new FocusListener() { public void focusGained(FocusEvent e) {}.rgagnon.event. tf2 = new JTextField(5).setDocument (new JTextFieldLimit(10)).isTemporary() &isEnabled() ) { String content = tf1. the gainedFocus is already sent for the next component in the SystemEventQueue. tf1 = new JTextField(5).*. public void init() { getContentPane(). We must grab this event.} import java.com/javadetails/. // label1 = new JLabel("max 10 chars"). tf1.*.getDefaultToolkit().*.add(label).awt. JLabel label. getContentPane().setLayout(new FlowLayout()). public class DemoJTextFieldWithLimit extends JApplet{ JTextField textfield1./javadetails/java−0199.awt. getContentPane().

class VerifierTest extends JFrame { public VerifierTest () { JTextField tf.getWindow(). System. java. import import import import java.util. SwingUtilities.tf2. getContentPane().exit(0).grabFocus(). which can be used to do that. f. addWindowListener(new WindowCloser()). BorderLayout. } } JDK1.awt. // and will allow focus to change only if the required string // is typed.getDefaultToolkit().equals("a") &!content. } public static void main (String [] args) { Frame f = new VerifierTest ().28 Validate a value on the lostFocus event .*. } }} }).if (!content. java.show().add (tf2. javax. } public void run() { component. tf2 = new JTextField ("howto come here").add (tf. public FocusGrabber(JComponent component) { this. InputVerfier.awt.equals("b")) { Toolkit.NORTH). tf = new JTextField ("howto is required").*. tf. } } class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent e) { Window win = e.*. f. getContentPane().SOUTH).invokeLater(new FocusGrabber(tf1)).println("illegal value! " + content ).3 provides a new class. } } class FocusGrabber implements Runnable { private JComponent component.out.swing.pack(). BorderLayout. } } 15.setInputVerifier(new HowtoVerifier()).setVisible(false). System.event. win.component = component.*. // the first JTextField expects the string "howto" as input.beep().

use a small WindowAdapter to listen to the WindowOpened event.getText().invokeLater(new Runnable(){ public void run(){ input. JPanel panel.equals("howto")) { SwingUtilities.RED) ). } SwingUtilities. String pass = tf.. 15.setBorder( LineBorder.. This is not needed with the Appletviewer or in Application. .*. } } . return true.createBlackLineBorder() ). } }). class HowtoVerifier extends InputVerifier { public boolean verify(final JComponent input) { JTextField tf = (JTextField) input.29 Make sure that my jTextfield has the focus when a JFrame is created Current version of this HowTo : http://www..getText().29 Make sure that my jTextfield has the focus when a JFrame is created . import javax. if (!pass.*. public class MyFrame extends JFrame { JTextField field1. From there. simply request the focus for the JTextfield.setBorder( new LineBorder(Color.swing.swing.*.awt. import javax. you need to do it. } } It's not a bad idea to give a visual cue that the textfield is not validated.. return false. Here a bad textfield will show a red border.html In a JFrame. 15. import java.invokeLater(new Runnable(){ public void run(){ input.event. return pass. } }).awt.com/javadetails/. String pass = tf.border. a good one will be black. JTextField field2.rgagnon. but with some browsers (like Netscape).equals("howto").. import java.*./javadetails/java−0200.class HowtoVerifier extends InputVerifier { public boolean verify(JComponent input) { JTextField tf = (JTextField) input.

*..30 Stop the beep on JFormattedTextField .event. consider making a small donation to show your support for this Web site and its content.html When the user inputs an invalid value into JFormattedTextField.public MyFrame() { super( "This is my Frame" )..rgagnon. pack(). setVisible( true ).swing... panel = new JPanel().*. panel. public class MyFrameApplet extends JApplet { public void init() { MyFrame myFrame = new MyFrame().30 Stop the beep on JFormattedTextField Current version of this HowTo : http://www. } If you find this article useful. import javax.*.add( field2 ). field2 = new JTextField( 10 ). field1 = new JTextField( 10 ). To avoid this annoying beep. import java. class MyJFormattedTextField extends JFormattedTextField { .add( new JLabel("Field 2:")).add( field1 ). panel. } } ). panel ).awt. } } 15. panel./javadetails/java−0427.awt.add( new JLabel("Field 1:")). } } To try it : import java.add( "Center". Written and compiled by Réal Gagnon ©1998−2005 [ home ] 15. the default behavior is to emit a beep. protected void invalidEdit() {} . simply overload the invalidEdit() method.requestFocus().31 Right justified JTextfield content Current version of this HowTo : 15.com/javadetails/. panel. addWindowListener( new WindowAdapter() { public void windowOpened( WindowEvent e ){ field1.. getContentPane().

public class Test extends JApplet { JTextField textfield. getContentPane(). javax.awt. } } If you find this article useful. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 15.add (tf1.*.swing. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 15.invokeLater(new Runnable() { public void run() { myJTextField. If you find this article useful../javadetails/java−0493. // Right−justify the text textfield.util. *. public void init() { getContentPane()./javadetails/java−0546. 15.*.*.html SwingUtilities. tf1 = new JTextField ("you can select with the mouse").32 Set the focus on a particuliar JTextField .33 Make JTextField unselectable Current version of this HowTo : http://www. getContentPane(). consider making a small donation to show your support for this Web site and its content.http://www.event. textfield = new JTextField(10).rgagnon.html import import import import java.tf2.setLayout(new FlowLayout())./javadetails/java−0510.*.swing. import java..32 Set the focus on a particuliar JTextField Current version of this HowTo : http://www.com/javadetails/.awt.com/javadetails/.rgagnon.add(textfield).RIGHT). consider making a small donation to show your support for this Web site and its content. } })..setHorizontalAlignment(JTextField. tf2 = new JTextField ("you can't select with the mouse"). java.NORTH).com/javadetails/.awt.*. class UnselectableJTextField extends JFrame { public UnselectableJTextField () { JTextField tf1.html import javax. java.requestFocus().rgagnon. BorderLayout.

private ImageIcon _closedIcon. _openedIcon = opened. // getContentPane(). 2 icons (open and close). BorderLayout. } } } 15. } String getLink() { return _link. } ImageIcon getOpenedIcon() { return _openedIcon. } ImageIcon getClosedIcon() { return _closedIcon.pack(). _closedIcon = closed. } } 15. addWindowListener(new WindowCloser()). private ImageIcon _openedIcon. ImageIcon opened) { _title = title.html This How−to will show you how to build a Tree (like this one) using Swing. we define the class representing a node.*. RealSwingNode (String title.exit(0).setVisible(true).add (tf2. NOTE: This Tree Applet is different since it's plain JDK1.34 Use a JTree to navigate in a site Current version of this HowTo : http://www.0.SOUTH). ImageIcon closed.// disable mouse or keyboard selection to prevent "cut and paste" tf2. f. System. f.com/javadetails/. win. String link.2 Applet.swing. } class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent e) { Window win = e.34 Use a JTree to navigate in a site . First. private String _link.getWindow(). import javax. _link = link. } String getTitle() { return _title. public class RealSwingNode extends Object { private String _title.setVisible(false). } public String toString() { return _title./javadetails/java−0209. } public static void main (String [] args) { Frame f = new UnselectableJTextField ().rgagnon. This node contains a title (the label).. a URL.setHighlighter(null).

if (selected){ _label. boolean leaf.swing. else _label.getFont()).tree. } else { _label.*.setOpaque(true).34 Use a JTree to navigate in a site . } else if(value instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode node.getBackground()).setBackground(tree.setFont(tree. import javax. _label. Object value.setIcon(_userObject. node = (DefaultMutableTreeNode) value.setText(_userObject.getUserObject(). if (node. _label. _label.toString()). import java.setForeground(tree. import javax.*. boolean hasFocus) { RealSwingNode _userObject = null. int row. } } 15. boolean expanded.awt.*. public class RealSwingTreeIconRenderer extends Object implements TreeCellRenderer { JLabel _label. } else { _label. boolean selected. } return _label.getClosedIcon()).setIcon(_userObject.getTitle()).Then we define how the node would be shown in the Tree. This is done by implementing a Renderer class.setText(value.getUserObject() instanceof RealSwingNode) { _userObject = (RealSwingNode) node.getBackground()). } public Component getTreeCellRendererComponent (JTree tree. } } if(_userObject != null) { if (expanded) _label.setForeground(tree. _label. } if (value instanceof RealSwingNode) { _userObject = (RealSwingNode) value. _label.swing. _label.setBackground(tree.setIcon(null).getForeground()). RealSwingTreeIconRenderer() { _label = new JLabel().getOpenedIcon()).getForeground()).

util.*.printStackTrace(). try { UIManager.out.*. parentApplet.println(System. java.*. image2idx=0. imageValue. java.net. private String targetFrame.name")). java.*. javax.awt. java.swing. String strValue. private ImageIcon treeIcons[].getProperty("os.println("[RealSwingTree] Begin populateTree() " ). boolean rootDone=false. TreeSelectionModel tsm. javax. rootvalue=0. public RealSwingTree() { System. lnkValue. DefaultMutableTreeNode node = null.*. DefaultMutableTreeNode currentNode = null.awt. int token.The next step is building the JTree in a JPanel. image1idx=0. boolean itemDone=true. public class RealSwingTree extends JPanel implements TreeSelectionListener { private JApplet parentApplet.swing. } catch (Exception ex_ignored) { ex_ignored.io. try { initTreeIcons().event. Since this Tree is designed to be used in Applet. 15. java. value=0. import import import import import import import import javax. URL urlFile = new URL(parentApplet.tree.event. } public void initTree() { // build the tree from the datafile DefaultMutableTreeNode rootNode = null. private Font f. Reader r = new BufferedReader (new InputStreamReader(urlFile. private JTree tree.*.getParameter("targetframe"). RealSwingTreeIconRenderer rstir. StreamTokenizer st = new StreamTokenizer(r). We use a datafile to define the Tree nodes.getCodeBase(). System. targetFrame = parentApplet.openStream())).out.swing.getSystemLookAndFeelClassName()).setLookAndFeel( UIManager. RealSwingNode rsn = null. oldvalue=0.34 Use a JTree to navigate in a site .*. } } public void setParentApplet(JApplet j) { parentApplet = j. we must pass a JApplet reference to be able to read some parameters passed via the HTML PARAM tags.getParameter("datafile")).*.

} else { token = st. if (value >= oldvalue) { if (value==oldvalue) { // *** sibling if (currentNode. rsn = new RealSwingNode(strValue.st. else { DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)currentNode. image1idx = Integer.sval.add(node). node = new DefaultMutableTreeNode(rsn. token = st. } DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)currentNode. rootDone = true. rootNode = node. lnkValue = st.add(node).nextToken(). treeIcons[image2idx]).nval). 15.nextToken().sval). token = st. rsn = new RealSwingNode (strValue.nextToken().getParent(). image2idx = Integer.parseInt(st. } } currentNode = node.parseInt(st. } } else { // *** child currentNode.nextToken()) != StreamTokenizer.34 Use a JTree to navigate in a site .sval. st.add(node). oldvalue = value. } } else { // *** new branch. else dmtn. token = st.equals(rootNode)) rootNode.add(node).equals(rootNode)) rootNode.nextToken(). if (dmtn.nextToken(). st. must get back to the right level while (value < oldvalue) { currentNode = (DefaultMutableTreeNode)currentNode. node = new DefaultMutableTreeNode(rsn. dmtn.nextToken(). // // datafile structure <level> <label> <link> <image1> <image2> // while ((token = st.quoteChar('"'). strValue = st.eolIsSignificant(false). "". if (!rootDone) { // do the root first token = st.getParent().intValue(). null).add(node).sval.getParent().sval. lnkValue = st. strValue = st.sval). lnkValue. oldvalue−−. true). null.parseNumbers(). treeIcons[image1idx]. token = st. true).TT_EOF ) { // get level value = new Double(st.

} public void initTreeIcons() { String rootImage. ". Font f = new Font (parentApplet.addElement(s).parseInt(parentApplet.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION). i++) { try { URL imageURL = new URL (parentApplet.out. tsm = tree.. tree. rootImage = parentApplet. tree. } System. setBackground(bgcolor).getParameter("font"). Integer..size().printStackTrace().nextToken().getParameter("bgcolor").elementAt(i)).println("begin initImage()").setRootVisible(true). treeIcons[i] = new ImageIcon(imageURL).getParameter("images"). tree.").getParameter("point"))). Font.PLAIN. 16).intValue()). add(new JScrollPane(tree). System. for(int i=0. tsm.size()].elementAt(i)).setCellRenderer(rstir). String pathImages.getParameter("leaveimageslist").out.getCodeBase() + "/" + pathImages + "/" + (String)leaveImage.setRowHeight(0).} tree = new JTree(rootNode). } catch (Exception e) {e. rstir = new RealSwingTreeIconRenderer(). } treeIcons = new ImageIcon[leaveImage. i < leaveImage. leaveImagesList = parentApplet. System. tree. setFont(f)."Center").34 Use a JTree to navigate in a site . setLayout(new BorderLayout()).printStackTrace(). leaveImage. } catch(Exception e) { e.addTreeSelectionListener(this).out. while(leavesList.getParameter("rootimage").println("[RealSwingTree] End populatetree()"). tree.valueOf (parentApplet. Vector leaveImage = new Vector().getSelectionModel()." + (String)leaveImage. pathImages = parentApplet.println("Loading . } } 15. StringTokenizer leavesList = new StringTokenizer(leaveImagesList.setShowsRootHandles(true).hasMoreTokens()){ String s=leavesList. String leaveImagesList. Color bgcolor = new Color( Integer.

swing.getSelectionPath().getUserObject(). rst.getLastPathComponent().System.html" "2" "2" 1 "General" "" "0" "1" 2 "part 1" "java−g1.34 Use a JTree to navigate in a site .showDocument (newURL. rsn = (RealSwingNode)dmtn. rst.initTree().out.equals("")) { try { URL newURL = new URL (parentApplet.println("end initImage()"). parentApplet.out.println(" url: " + newURL.*.getLink()).setParentApplet(this).toString() + " target:" +targetFrame).getCodeBase() + rsn. } } Here a sample datafile. 400).getAppletContext(). if (!rsn. getContentPane().txt] 0 "Welcome | Bienvenue" "welcome.getLink().add(rst).out. RealSwingNode rsn.targetFrame). System. TreePath path = tree.getLink()).awt. [treedata. public class RealSwingTreeApplet extends JApplet { RealSwingTree rst. } } Let's make a simple Applet to try it out.*. if (path != null) { dmtn = (DefaultMutableTreeNode) path.println("Click! link: " + rsn. } } } } public Dimension getPreferredSize() { return new Dimension(250. import javax. The image number is the index of the image passed via the PARAM leaveimageslist. } public void valueChanged(TreeSelectionEvent tse) { DefaultMutableTreeNode dmtn. } catch (Exception e) { e.printStackTrace().html" 0 "Java How−to" "" "0" "1" 1 "What's new" "java−new. public void init() { rst = new RealSwingTree(). The structure is "[level] [label] [link] [image1] [image2]". System.html" "2" "2" 15. import java.

com/javadetails/.2" width="200" height="2000" code="RealSwingTreeApplet. java..txt"> <PARAM NAME="bgcolor" VALUE="FFFFFF"> <PARAM NAME="font" VALUE="Courier"> <PARAM NAME="point" VALUE="11"> <PARAM NAME="images" VALUE=". with Netscape. node1.jpg fpage. all PARAM tags are required. other params here .event.awt..com/products/plugin/1.jpg 15.*.35 Expand or collapse a JTree Current version of this HowTo : http://www.rgagnon.jpg"> </APPLET></BODY></HTML> The <APPLET> tag and Swing applet are ok with Appletviewer.*. node3. pluginspage="http://java. you need to execute the Applet under the Java plugin.jpg fopen.class" datafile="treedata...version=1.html import import import import import javax.Here the HTML used to test the Tree. public class SimpleTree extends JPanel { JTree tree.txt" bgcolor="FFFFFF" . So for example.class" NAME="RealTree" HEIGHT=2000 WIDTH=196> <PARAM NAME="datafile" VALUE="treedata.jpg.page. the HTML will be like this : <HTML><BODY> <EMBED type="application/x−java−applet.2/plugin−install. <HTML><BODY> <APPLET CODE="RealSwingTreeApplet.2 support for APPLET!! </NOEMBED> </EMBED> </BODY></HTML> Finally./javadetails/java−0210. you may want to grab these images used in this How−to . but in most browser. DefaultMutableTreeNode root.tree. Since there is almost no error checking.*. javax.sun.swing.html"> <NOEMBED> No JDK 1.gif"> <PARAM NAME="leaveimageslist" VALUE="fclose. java./images"> <PARAM NAME="targetframe" VALUE="_top"> <PARAM NAME="rootimage" VALUE="root.swing.util.*.gif fclose. you need to use the <EMBED> tag with Nets