Realhowto Java 201511
Realhowto Java 201511
Table of Contents
Real's HowTo PDF version (november 2015)..................................................................................................1
AWT.....................................................................................................................................................................3
java-awt....................................................................................................................................................3
Use the CardLayout manager...................................................................................................................3
Detect which card is visible with a CardLayout......................................................................................6
Use Popups..............................................................................................................................................6
Use a File Dialog.....................................................................................................................................9
Use TrueType font.................................................................................................................................10
Display available fonts...........................................................................................................................11
Font with 3D effect................................................................................................................................11
Use the System Clipboard......................................................................................................................12
Maximize a Frame.................................................................................................................................13
Center a Frame/Dialog...........................................................................................................................15
Close a Frame........................................................................................................................................16
Call events on a Frame from a Panel.....................................................................................................17
Set the small top-left icon on a Frame...................................................................................................19
Prevent a Frame to be resized................................................................................................................20
Embed an image into a Frame...............................................................................................................21
Display a message box...........................................................................................................................23
Display a Splash screen.........................................................................................................................25
Vibrate a Window..................................................................................................................................27
Limit TextField input to numeric value.................................................................................................30
Limit TextField input to a maximum length..........................................................................................31
React to the ENTER key in a Textfield.................................................................................................32
Make the ENTER key act like the TAB key..........................................................................................33
Reset all textfields in one shot...............................................................................................................34
Limit a TextField to Uppercase.............................................................................................................35
Have an ImageButton............................................................................................................................36
Reset a checkbox group.........................................................................................................................39
Set the listbox width..............................................................................................................................40
Align the column in a List.....................................................................................................................41
Have a srolling text display using a List................................................................................................41
Label dynamic resizing..........................................................................................................................42
Make a TextArea "word-wrap"..............................................................................................................44
Synchronize a TextArea versus a Choice..............................................................................................44
Display underlined text..........................................................................................................................45
Display vertical text...............................................................................................................................45
Have Label with many lines..................................................................................................................46
Have a Label with underlined text.........................................................................................................51
Have a Label acting as HTML HREF (URLLabel)...............................................................................52
Display a GIF in a Canvas.....................................................................................................................54
Embed an image into a Frame...............................................................................................................55
i
Real's HowTo PDF version
Table of Contents
AWT
Load several images from a single GIF.................................................................................................57
Load an Image from a JAR file..............................................................................................................58
Load an Image from a JAR file (again).................................................................................................59
Scale an Image.......................................................................................................................................60
Fade an image........................................................................................................................................62
Rotate an image......................................................................................................................................64
Create a scrollable canvas......................................................................................................................67
Use an Image as the Applet background................................................................................................70
Have a simple Image browser................................................................................................................72
Simulate a "mouse over" event to toggle an image...............................................................................75
Hide the mouse cursor...........................................................................................................................77
Make a color transparent........................................................................................................................77
Save an Image as a GIF or JPEG file.....................................................................................................79
Use the same background color as the browser.....................................................................................80
Do simple animation using Images........................................................................................................81
Do simple animation to show "work in progress".................................................................................82
Get the color of a specific pixel.............................................................................................................84
Do "rubber-band" drawing.....................................................................................................................85
Convert RGB value to Hex (to be used in HTML)................................................................................87
Draw a line or set a pixel in my own image..........................................................................................87
Draw dashed line....................................................................................................................................88
Draw a line with a thickness..................................................................................................................89
Draw a pie chart.....................................................................................................................................91
Draw faster rectangles............................................................................................................................94
Get a screen capture and save it as a JPEG............................................................................................95
Detect a double click versus a simple click...........................................................................................95
Detect the mouse button used when clicking.........................................................................................97
Exit an application from a menu (single exit point)..............................................................................98
Trigger a click on a Button....................................................................................................................99
Display a TIF.......................................................................................................................................100
Convert a multi-page TIF into single-page TIF...................................................................................102
Convert many single-page TIF into one multi-page TIF.....................................................................103
Convert an Image to a BufferedImage.................................................................................................104
Detect if a TIF is blank........................................................................................................................105
Convert TIF to PDF.............................................................................................................................108
Convert TIF to JPG..............................................................................................................................110
ii
Real's HowTo PDF version
Table of Contents
Date and Time
Get the number of days in a month......................................................................................................115
Validate a date......................................................................................................................................115
Determine the day of the week............................................................................................................117
Add/Substract Day/Month/Year to a Date...........................................................................................118
Get the correct TimeZone on DateFormat...........................................................................................119
Simply format a date as "YYYYMMDD"...........................................................................................120
Compare 2 dates...................................................................................................................................120
Parse a String to obtain a Date/GregorianCalendar object..................................................................121
Use System time to generate unique ID...............................................................................................122
Get the day name.................................................................................................................................122
Find the date format pattern.................................................................................................................123
Get a julian date...................................................................................................................................124
Calculate the age..................................................................................................................................127
Format a duration in milliseconds into a human-readable format.......................................................128
Get the atomic time..............................................................................................................................131
Get a date interval................................................................................................................................133
Determine if a given hour is between an interval................................................................................135
Set the computer clock (JNI)...............................................................................................................137
Get unique numerical id based on the system time..............................................................................138
Get the month (or day) name (localized).............................................................................................138
Detect a leap year.................................................................................................................................139
Environment....................................................................................................................................................141
java-env................................................................................................................................................141
Read environment variables from an application................................................................................141
Read environment variables (JDK1.5).................................................................................................145
Read environment variables (JNI).......................................................................................................146
Use a MAKE file.................................................................................................................................147
Detect the browser/JVM type..............................................................................................................148
Fix the "Wrong magic number" error message....................................................................................150
Use a precompiler "à la C" with Java..................................................................................................150
Determine what are the classes actually used......................................................................................152
Set the memory available to the JVM..................................................................................................153
Generate the Javadoc "en français"......................................................................................................153
Use JDK1.5 new features.....................................................................................................................154
Check the class version........................................................................................................................155
Get the system properties or the JVM uptime.....................................................................................156
Detect if running in a 64bit JVM.........................................................................................................157
Set the default JVM type......................................................................................................................158
Select a particular JRE from the command line...................................................................................159
Get the PID (pure Java solution)..........................................................................................................160
Get the PID (JNI solution)...................................................................................................................161
iii
Real's HowTo PDF version
Table of Contents
Environment
Set default value for Java property or JVM option (system wide)......................................................162
Detect if running in debug mode.........................................................................................................163
Configure Java deployment with properties........................................................................................163
Wrap a Java bean in a COM object (using Sun ActiveX bridge)........................................................167
Query the Windows Registry (reg.exe)...............................................................................................169
Query/Update the Windows Registry (hack).......................................................................................172
Quickly retrieve available Java JVM on a workstation (Windows)....................................................181
Detect if a Windows service is running (capture VBS return code)....................................................182
List currently running processes (Windows).......................................................................................184
Check if a program or process is running (Windows).........................................................................186
Check if a process is running (Windows) using WMIC......................................................................188
Windows registry vs Java JDK/JRE installation.................................................................................189
Get the current Java version from a BAT file......................................................................................190
Get the Windows "My Documents" path.............................................................................................192
Get the Windows Desktop path...........................................................................................................192
Get the Windows Special Folders........................................................................................................194
Create an Internet Shortcut..................................................................................................................195
Detect if running in remote session (Windows)..................................................................................197
Detect if running in a Citrix session (Windows).................................................................................198
Create a Taglet to document database access (Javadoc)......................................................................199
Generate the Javadoc "en français"......................................................................................................203
Document a package using Javadoc....................................................................................................204
Display a comment in a Javadoc..........................................................................................................205
Display XML in a Javadoc..................................................................................................................206
Add a copyright notice to a Javadoc....................................................................................................207
Use a Log file.......................................................................................................................................207
Trace the execution..............................................................................................................................210
Time the execution...............................................................................................................................212
Log information efficiently (with Log4J)............................................................................................213
Change the logging level on-the-fly (Log4J).......................................................................................214
Enable debug log level on OpenSource package(Apache Commons Logging)..................................215
Make a JAR executable.......................................................................................................................216
Application with multiples Jars...........................................................................................................218
Extract a file from a Jar........................................................................................................................218
Determine if running from JAR...........................................................................................................220
Get list of classes in package (in a Jar)................................................................................................221
Add version to Jar packaging...............................................................................................................223
Use ANT to Build a JAR with version/build number..........................................................................225
Include all jars in the classpath definition............................................................................................229
Detect browser type from an Applet....................................................................................................233
Detect if Java is enabled from HTML.................................................................................................234
See the Java Console Window Log (Java plugin)...............................................................................235
iv
Real's HowTo PDF version
Table of Contents
Internationalization........................................................................................................................................236
java-inter..............................................................................................................................................236
Load resources based upon client environment at startup...................................................................236
Load resources dynamically................................................................................................................239
Load resources via a resource file........................................................................................................243
Display "special character" using Unicode..........................................................................................247
Display chinese/japanese characters in an Applet...............................................................................248
Localize a JOptionPane dialog.............................................................................................................249
Validate/Convert a number using the current Locale()........................................................................251
Localize a JFileChooser.......................................................................................................................252
Disable localization..............................................................................................................................255
Generate the Javadoc "en français"......................................................................................................256
Sort an array with international characters..........................................................................................257
Accentuated characters in Properties/ResourceBundle file.................................................................259
Compare accentuated letters................................................................................................................259
Remove accent from letters (ex .é to e)...............................................................................................261
Output accentuated characters to the console......................................................................................265
Get the default character set of the JVM.............................................................................................266
Convert OEM (DOS) file to Ansi (Windows).....................................................................................267
Detect non-ASCII character in a String...............................................................................................268
Get the month (or day) name (localized).............................................................................................269
IO......................................................................................................................................................................271
java-io..................................................................................................................................................271
Redirect output(stdout/stderr) to a frame.............................................................................................271
Redirect printStackTrace() to a String.................................................................................................272
Redirect to NULL device.....................................................................................................................273
Print a text file using the javax.print API............................................................................................274
Print a String using the javax.print API...............................................................................................276
Print text to a printer easily..................................................................................................................278
Print without a Dialog..........................................................................................................................278
Initialize and write to a serial port.......................................................................................................279
Open or close a CD/DVD drive...........................................................................................................279
Get the volume label............................................................................................................................281
Detect the storage device type.............................................................................................................282
Turn on MQ Debug mode....................................................................................................................283
Get faster console output (System.out.println() replacement).............................................................283
Simple input from the keyboard..........................................................................................................285
Output french character to the console................................................................................................286
Clear the console and control attributes...............................................................................................288
Easy keyboard input (JDK1.5).............................................................................................................290
Force keyboard input in CAPS LOCK on...........................................................................................292
Automatic conversion of System.out output........................................................................................293
v
Real's HowTo PDF version
Table of Contents
IO
Execute an external program and capture the output...........................................................................294
Launch the application associated with a file extension......................................................................301
Launch an application from another application.................................................................................302
Start the default browser from an application......................................................................................304
Execute a Windows Shortcut (.lnk).....................................................................................................306
Create a file association with a Java program......................................................................................307
Capture the output from a VBS...........................................................................................................308
Get a return code from a VBS..............................................................................................................310
Execute a CMD file stored in a JAR....................................................................................................311
Open the default file explorer..............................................................................................................312
Read the content of a file.....................................................................................................................313
Read a text file from a Jar....................................................................................................................315
Read a text file from the internet.........................................................................................................318
Extract a file from a Jar........................................................................................................................318
Read a data file with floats...................................................................................................................320
Write to the end of a file......................................................................................................................321
Write "real" ascii file...........................................................................................................................322
Copy a file............................................................................................................................................323
Use a "log file".....................................................................................................................................326
Delete files with a certain extension....................................................................................................327
Insert a line in a file.............................................................................................................................328
Read a file into a variable in one shot..................................................................................................329
Serialize an object to a file...................................................................................................................330
Redirect stdout to a file........................................................................................................................332
Get the "last modified" date from a file...............................................................................................332
Get the file creation time......................................................................................................................332
Check if a file exists.............................................................................................................................333
Detect file (or folder) modification......................................................................................................333
File/directory polling to detect change................................................................................................337
Detect file (or folder) modification (Java 7)........................................................................................338
Get the current directory......................................................................................................................339
Get the "root" of an application...........................................................................................................340
Get the content of a directory with a Filter..........................................................................................340
Get the content of a directory with subdirectories...............................................................................343
Get directory content faster with many files........................................................................................345
Make a directory..................................................................................................................................347
Create a fixed-length file.....................................................................................................................347
Delete a non-empty directory...............................................................................................................347
Create a temporary file.........................................................................................................................348
Get the default character set of the JVM.............................................................................................349
Parse a pathname..................................................................................................................................350
Handle CSV files.................................................................................................................................350
vi
Real's HowTo PDF version
Table of Contents
IO
Convert OEM (DOS) file to Ansi (Windows).....................................................................................352
Close a stream in a try/catch block......................................................................................................353
Rename a file extension.......................................................................................................................354
Remove a file extension.......................................................................................................................356
Remove HTML tags from a file to extract only the TEXT.................................................................356
Get the Mime Type from a File...........................................................................................................359
Sort a directory listing (based on the last modified timestamp)..........................................................364
Sort files by the extension....................................................................................................................365
Filter a directory listing by date...........................................................................................................367
Convert wildcard to a regex expression...............................................................................................368
Shorten a long path..............................................................................................................................369
Force a valid Windows filename.........................................................................................................374
Check if filename is valid....................................................................................................................374
Dump a file to a HEX file....................................................................................................................375
List all files in the classpath or in a Jar................................................................................................377
Handle UTF8 file with BOM...............................................................................................................378
Touch a file..........................................................................................................................................381
Handle Excel files................................................................................................................................382
Create an Excel file (the easy way)......................................................................................................388
Detect if a XLS Excel file contains a macro (using POI)....................................................................389
Create or process PDF files..................................................................................................................390
iText - Create a PDF............................................................................................................................393
Split a PDF file (using iText)...............................................................................................................394
Concatenate PDF files (using iText)....................................................................................................395
Convert TIF to PDF.............................................................................................................................397
Convert HTML to PDF using iText.....................................................................................................399
Convert HTML to PDF using YAHP..................................................................................................401
Convert PNG/JPG/GIF to PDF using iText.........................................................................................403
Print a PDF...........................................................................................................................................404
Extract text from a PDF using Apache Tika........................................................................................405
Create a compressed (ZIP) file............................................................................................................405
Display compressed (ZIP) file content................................................................................................407
Expand the compressed (ZIP) file........................................................................................................408
Emit a beep..........................................................................................................................................409
Emit a tone...........................................................................................................................................409
Play an audio file from an application.................................................................................................411
Produce special sound effect................................................................................................................412
Use the Java Speech API (JSPAPI).....................................................................................................416
Play a Windows sound.........................................................................................................................418
vii
Real's HowTo PDF version
Table of Contents
JDBC................................................................................................................................................................420
java-jdbc...............................................................................................................................................420
Get JDBC driver for major database vendors......................................................................................420
Connect to a database via JDBC-ODBC.............................................................................................420
SELECT data from a table...................................................................................................................422
INSERT data into a table.....................................................................................................................423
MODIFY data in a table......................................................................................................................425
DELETE data in a table.......................................................................................................................425
Test for an empty ResultSet.................................................................................................................426
Get row count from SQL.....................................................................................................................426
Store and retrieve an object from a table.............................................................................................427
Retrieve an Image................................................................................................................................429
Insert an Image.....................................................................................................................................429
Call a stored procedure........................................................................................................................430
Stored procedure with Input/Output parms and a ResultSet................................................................430
Fix incomplete field returned by the ResultSet....................................................................................432
Transfer a ResultSet to a JTable..........................................................................................................432
Detect SQL error or warning...............................................................................................................432
Make DSN-less connection..................................................................................................................434
Select a CharSet when connecting to DBMS......................................................................................435
List tables in a database.......................................................................................................................435
Enable JDBC logging..........................................................................................................................437
Detect if a table exists..........................................................................................................................438
Convert a ResultSet in XML...............................................................................................................439
Display ResultSet data in an HTML Table in Servlet.........................................................................441
Escape special character in a LIKE clause..........................................................................................442
Log the SQL Statements......................................................................................................................442
Insert data in batch mode.....................................................................................................................444
Retrieve large ResultSet.......................................................................................................................446
Handle dates.........................................................................................................................................447
Get current date using JDBC...............................................................................................................449
Insert the current date...........................................................................................................................450
Read Excel worksheet..........................................................................................................................450
Handle Excel files................................................................................................................................452
Connect to an Oracle database with JDBC..........................................................................................459
Connect to Oracle using a connection pool.........................................................................................461
Retrieve the generated keys (JDBC Oracle)........................................................................................464
Debug Oracle JDBC connection..........................................................................................................465
Connect to an Oracle database using Kerberos....................................................................................467
Identify the connected program to an Oracle database........................................................................469
Use a CHAR field in the WHERE clause in a PreparedStatement......................................................470
viii
Real's HowTo PDF version
Table of Contents
JNI/JNA...........................................................................................................................................................473
java-jni.................................................................................................................................................473
Use native code through JNI (HelloWorld).........................................................................................473
Pass string to/from Java to/from C......................................................................................................473
Set the computer clock.........................................................................................................................475
Determine the signature of a method...................................................................................................476
Use arrays.............................................................................................................................................477
Load a DLL..........................................................................................................................................479
Use the MouseWheel...........................................................................................................................480
Throw an exception in JNI...................................................................................................................480
Throw my own exception in JNI.........................................................................................................481
JNI from a Package..............................................................................................................................482
Make a Window stay on top................................................................................................................482
Start JVM from C................................................................................................................................483
Retrieve environment variable (JNI)...................................................................................................484
Get the PID..........................................................................................................................................484
Clear the console, set color and cursor position (JNI).........................................................................485
Call Windows API (Open source solution).........................................................................................488
Detect if a program is running (JNA)..................................................................................................489
Close an external windows program using JNA..................................................................................490
Get Windows Special Folders (JNA)...................................................................................................492
Javascript interaction.....................................................................................................................................494
java-js...................................................................................................................................................494
* Read me *.........................................................................................................................................494
Wake-up a Java applet.........................................................................................................................494
Call a Java method from Javascript.....................................................................................................497
Call a Java method from Javascript using DOM.................................................................................499
Access Java variables from Javascript.................................................................................................499
Call Javascript from a Java applet.......................................................................................................500
Create dynamic HTML from a Java applet..........................................................................................503
Inter-Applets communication across frames.......................................................................................504
Inter-Applet communication across pages...........................................................................................506
Write HTML FORM values from a Java applet..................................................................................508
Detect if an Applet is ready.................................................................................................................509
Read/Write HTML field values from Java..........................................................................................510
Detect if Java is enabled......................................................................................................................512
Detect if Java 1.1 (with event delegation) is available........................................................................512
Access Cookies from a Java Applet.....................................................................................................513
Set Applet PARAM VALUE from Javascript.....................................................................................516
Pass an Array between Java and Javascript.........................................................................................517
Interaction without LiveConnect.........................................................................................................520
Directory listing on the Web server in a Java Applet..........................................................................525
ix
Real's HowTo PDF version
Table of Contents
Javascript interaction
Have a Java button close the browser window....................................................................................528
Detect if cookies are enabled...............................................................................................................528
Display a page after all Applets are loaded.........................................................................................529
Detect browser type from an Applet....................................................................................................530
Servlet/JSP.......................................................................................................................................................533
java-jsp.................................................................................................................................................533
Read me...............................................................................................................................................533
Get servlet parameters..........................................................................................................................533
Servlet with no args.............................................................................................................................534
Set a Cookie from a servlet..................................................................................................................535
Read a Cookie from a servlet...............................................................................................................535
Delete a Cookie from a servlet.............................................................................................................536
Ask a password from a Servlet............................................................................................................536
Talk to a Servlet/JSP from an Applet..................................................................................................537
Test for Cookies support......................................................................................................................538
Display ResultSet data in an HTML Table in Servlet.........................................................................539
Specify the filename to be used for a file sent by a Servlet.................................................................539
Pass information to another servlet/jsp................................................................................................540
Handle PDF output..............................................................................................................................540
Detect if a connection is secured.........................................................................................................541
In a Servlet, check if Form Field is present.........................................................................................541
Get the root dir of a web app...............................................................................................................541
Get Client IP from JSP.........................................................................................................................541
Binary output from a JSP.....................................................................................................................542
Use a connection cache from JSP........................................................................................................543
Read a web application property..........................................................................................................545
Use EJB from JSP................................................................................................................................545
Define a method in a JSP page............................................................................................................546
Precompile JSP page............................................................................................................................546
Get a list of directories from JSP.........................................................................................................547
Use and share a class in JSP pages......................................................................................................548
Get the root dir of a web app...............................................................................................................549
Launch an applet from a JSP...............................................................................................................550
Prevent caching of a JSP output...........................................................................................................550
Launch an external program, capture its output and display it in a JSP..............................................551
Call another EJB..................................................................................................................................553
Keep java files generated from JSP (BEA WLS)................................................................................553
Get the server version (BEA WLS).....................................................................................................553
Quickly create a Web application with BEA WLS.............................................................................554
Nicely display WEB.XML informations.............................................................................................554
Reverse the CLASSLOADER order (BEA)........................................................................................556
x
Real's HowTo PDF version
Table of Contents
Servlet/JSP
Detect change in JSP and recompile (BEA)........................................................................................557
Obtain a remote connection to a DataSource or EJB (Weblogic).......................................................557
Language..........................................................................................................................................................560
java-language.......................................................................................................................................560
*Read me*...........................................................................................................................................560
Obtain from where a Class is loaded...................................................................................................560
Get the class name in a static method..................................................................................................561
Get the current method name...............................................................................................................562
Call a method dynamically..................................................................................................................564
Detect if a package is available............................................................................................................566
Create an Object from a String............................................................................................................567
Get a variable value from the variable name.......................................................................................568
Make methods that have unspecified number of parameters...............................................................569
Create a java source dynamically, compile and call............................................................................570
Launch an application from another application.................................................................................573
Access the enclosing class from an inner class....................................................................................574
Access inner class from outside...........................................................................................................575
Use globally defined constants............................................................................................................576
Serialize an Object...............................................................................................................................577
Serialize an Object over a Socket........................................................................................................579
Easily remove my debugging code......................................................................................................579
Have a Singleton..................................................................................................................................580
Multiple expressions in for loops.........................................................................................................581
Handle the List conflict (java.awt.List/java.util.List)..........................................................................581
Use a generic toString().......................................................................................................................582
Use a Object.clone().............................................................................................................................584
Static field, constructor and exception.................................................................................................585
Use a Label break.................................................................................................................................586
Put printStackTrace() into a String......................................................................................................586
Iterate enum values..............................................................................................................................587
Get fields and values from an Object...................................................................................................588
Use a Hashtable....................................................................................................................................589
Scan the content of a hashtable............................................................................................................590
Sort an array.........................................................................................................................................590
Initialize multidimensional array.........................................................................................................592
Get array upperbound..........................................................................................................................593
Convert a String to an array or an array to a String.............................................................................593
Sort Collection in reverse order...........................................................................................................595
Resize an array.....................................................................................................................................596
Dump array content (JDK1.5)..............................................................................................................597
Initialize a static array..........................................................................................................................598
xi
Real's HowTo PDF version
Table of Contents
Language
Sort an Hashtable.................................................................................................................................599
Eliminate "[unchecked] unchecked call ..." compiler warning............................................................600
Sort on many fields..............................................................................................................................602
Optimize Collection usage...................................................................................................................605
Sort an HashMap..................................................................................................................................606
Get keys corresponding to a value from a Map...................................................................................608
Iterate a Collection and remove an item..............................................................................................609
Count distinct elements in a Vector.....................................................................................................611
Dump the content of a Collection (JDK 1.5).......................................................................................612
Initialize a Collection...........................................................................................................................614
Merge (or add) two arrays into one......................................................................................................616
Define an array (or Map, or ENUM) of functions...............................................................................617
Join a List as a String...........................................................................................................................620
Remove duplicates from a List............................................................................................................621
Convert a Map to a Properties (or vice versa).....................................................................................622
Use an INI file (properties)..................................................................................................................623
Load a properties file...........................................................................................................................625
Accentuated characters in Properties/ResourceBundle file.................................................................626
Have a multi-line value in a properties file..........................................................................................626
Use XML with Properties....................................................................................................................627
Use the Registry to store informations.................................................................................................628
Sort Properties when saving.................................................................................................................629
Resolve environment variable in a property value..............................................................................630
Networking......................................................................................................................................................633
java-net.................................................................................................................................................633
Extract network card address...............................................................................................................633
Get the workstation name/ip................................................................................................................636
Find a port number not in use..............................................................................................................638
Disable DNS caching...........................................................................................................................638
Examine the internal DNS cache.........................................................................................................639
Allow user:password in URL...............................................................................................................642
Encode/Decode to/from Base64..........................................................................................................642
Lookup using MX record to validate mail server................................................................................644
Send an email using the SMTP protocol.............................................................................................654
Check if there is mail waiting..............................................................................................................655
Receive email.......................................................................................................................................657
Send email with an attachment............................................................................................................659
Send email with JavaMail....................................................................................................................666
Send email with authentication (JavaMail)..........................................................................................668
HTML mail with images (JavaMail)...................................................................................................669
Debug a Javamail Program..................................................................................................................672
xii
Real's HowTo PDF version
Table of Contents
Networking
Send email with SMTPS (eg. Google GMail) (Javamail)...................................................................673
Mix plain text and HTML content in a mail........................................................................................675
Read an Outlook MSG file (OpenSource packages)...........................................................................676
Handle EML file with JavaMail..........................................................................................................679
Receive email (and attachment) using IMAP......................................................................................681
Receive email (and attachment) using POP3.......................................................................................684
Debug a HttpURLConnection problem...............................................................................................686
Check if a file was modified on the server..........................................................................................688
Check if a page exists..........................................................................................................................688
Connect through a Proxy.....................................................................................................................690
Identify yourself using HTTP Authentification...................................................................................694
Talk to a CGI/Servlet...........................................................................................................................696
Write/Read cookies using HTTP.........................................................................................................697
Read a text file from the internet.........................................................................................................700
Read a GIF or CLASS from an URL save it locally............................................................................700
Resolve a relative URL........................................................................................................................702
File Size from URL..............................................................................................................................702
Using HTTPS protocol........................................................................................................................703
Fix certificate problem in HTTPS........................................................................................................704
Fetch a page from Google....................................................................................................................706
Upload a file.........................................................................................................................................707
Remove HTML tags from a file to extract only the TEXT.................................................................707
Extract links from an HTML page.......................................................................................................710
Call a web service (generated with BEA ServiceGen)........................................................................712
Do basic authentication when calling a webservice............................................................................714
Have a simple HTTP server.................................................................................................................715
Handle JSON Object............................................................................................................................717
HttpUrlConnection with GZIP encoding.............................................................................................727
Connect through a Proxy.....................................................................................................................730
Have timeout on socket connection.....................................................................................................733
Ping a server.........................................................................................................................................734
Get the Date from server......................................................................................................................735
Use Socket's setSoLinger()..................................................................................................................735
Use Socket's setTcpNoDelay()............................................................................................................736
Find who is connecting to a ServerSocket...........................................................................................736
Transfer a file via Socket.....................................................................................................................737
Check if a document exists in a Sharepoint library.............................................................................739
Delete a document in a Sharepoint library...........................................................................................741
Get a document from a Sharepoint library...........................................................................................743
Put or store a document in a Sharepoint library...................................................................................745
Handle MS Exchange public folders...................................................................................................747
xiii
Real's HowTo PDF version
Table of Contents
Open Source....................................................................................................................................................750
java-os..................................................................................................................................................750
Call Windows API...............................................................................................................................750
Call COM object..................................................................................................................................750
Create entity-relation diagram.............................................................................................................751
Java Remote desktop tool....................................................................................................................752
Create entity-relation diagram.............................................................................................................753
Launch a java program as a Windows EXE file..................................................................................753
Tools to handle CSV files....................................................................................................................755
Tools to handle Excel files...................................................................................................................756
Browse a Queue (JMS/MQ).................................................................................................................763
Convert a .class to .java file (decompiler)...........................................................................................763
Deploy an application as only 1 jar......................................................................................................765
Read an Outlook MSG file..................................................................................................................765
File/directory polling to detect change................................................................................................769
Jansi/Jcurses - Clear the console and control attributes.......................................................................770
Disable Checkstyle from code.............................................................................................................773
Create or process PDF files..................................................................................................................774
iText - Create a PDF............................................................................................................................776
Split a PDF file (using iText)...............................................................................................................777
Concatenate PDF files (using iText)....................................................................................................779
Convert TIF to PDF.............................................................................................................................780
Convert HTML to PDF using iText.....................................................................................................782
Convert HTML to PDF using YAHP..................................................................................................784
Convert PNG/JPG/GIF to PDF using iText.........................................................................................786
Print a PDF...........................................................................................................................................787
Extract text from a PDF using Apache Tika........................................................................................788
Detect and remove blank page in pdf (iText)......................................................................................789
Security............................................................................................................................................................792
java-security.........................................................................................................................................792
Encrypt a password..............................................................................................................................792
Create a checksum...............................................................................................................................797
Get the username..................................................................................................................................801
Get the username using NTLM from a JSP.........................................................................................802
Check if the current user belongs a specific Windows group/role......................................................804
Allow user:password in URL...............................................................................................................804
Input password from the console.........................................................................................................805
Prevent XSS exploit.............................................................................................................................806
Display a simple username/password Dialog from an Applet.............................................................808
Solve "Application blocked by security settings" message with unsigned Applet..............................811
xiv
Real's HowTo PDF version
Table of Contents
String/Number.................................................................................................................................................814
java-stringnumber................................................................................................................................814
*Read me*...........................................................................................................................................814
Convert from type X to type Y............................................................................................................814
Strip certain characters from String.....................................................................................................817
Replace/remove character in a String..................................................................................................818
Replace every occurences of a string within a string...........................................................................819
"Tokenize" a string..............................................................................................................................821
Split a string using String.split()..........................................................................................................827
Optimize String operations..................................................................................................................830
Remove spaces from a String..............................................................................................................832
Test if a String starts with a digit or uppercase letter..........................................................................833
Get InputStream from a String.............................................................................................................833
Easy String padding.............................................................................................................................834
Replace \r\n with the <br> tag.............................................................................................................836
Remove accent from letters (ex .é to e)...............................................................................................836
Apply a mask to a string......................................................................................................................840
Format a String (JDK1.5)....................................................................................................................841
Replace a "\" by "\\".............................................................................................................................842
Substitute tokens in a String................................................................................................................843
Compare accentuated letters................................................................................................................843
Create a String with a fixed length......................................................................................................845
Unquote a String..................................................................................................................................846
Escape HTML special characters from a String..................................................................................846
Unescape HTML special characters from a String..............................................................................849
Detect non-ASCII character in a String...............................................................................................853
Remove HTML tags from a file to extract only the TEXT.................................................................854
Extract links from an HTML page.......................................................................................................857
Convert a byte array to a Hex string....................................................................................................859
Apply proper uppercase and lowercase on a String.............................................................................861
Encode/Decode to/from Base64..........................................................................................................862
Justify string with wordwrap...............................................................................................................864
Shorten a long path..............................................................................................................................865
Ellipse a long string.............................................................................................................................869
Display an ASCII banner.....................................................................................................................870
Convert from type X to type Y............................................................................................................871
Type conversion (JDK1.5)...................................................................................................................874
Round a double....................................................................................................................................875
Display numbers with commas............................................................................................................876
Display numbers in scientific notation................................................................................................877
Display numbers with leading zeroes..................................................................................................879
Get a random number...........................................................................................................................880
Convert an UNSIGNED byte to a JAVA integer................................................................................880
xv
Real's HowTo PDF version
Table of Contents
String/Number
Deal with the big-endian and little-endian order.................................................................................882
Pass an integer by reference.................................................................................................................882
Pass floats as string literals to a method..............................................................................................882
Get random numbers............................................................................................................................883
Convert number to words.....................................................................................................................884
Arithmetic with double........................................................................................................................893
Detect even/odd number......................................................................................................................894
Convert bytes to megabytes.................................................................................................................894
Validate a number................................................................................................................................895
Get a unique identifier.........................................................................................................................896
Validate/Convert a number using the current Locale()........................................................................897
Transform a fraction to a Double.........................................................................................................899
Get short ordinal representation of a number......................................................................................900
Swing................................................................................................................................................................902
java-swing............................................................................................................................................902
*Read me*...........................................................................................................................................902
Change default component font...........................................................................................................902
Repaint problem under the mouse cursor (JDK1.2)............................................................................903
Set the LookAndFeel...........................................................................................................................903
Use any LookAndFeel on any plateform.............................................................................................903
Use a Timer..........................................................................................................................................904
Share ActionEvent handler..................................................................................................................905
Get default values for Swing-based user interface..............................................................................907
Have a systray icon (Windows)...........................................................................................................908
Close a JFrame under condition...........................................................................................................910
Maximize a JFrame..............................................................................................................................911
Capture System.out into a JFrame.......................................................................................................912
Remove the titlebar of JInternalFrame................................................................................................915
Have borders on a JWindow/JFrame...................................................................................................915
Display HTML in a JScrollPane..........................................................................................................915
Use a JOptionPane...............................................................................................................................916
Localize a JOptionPane dialog.............................................................................................................918
Customize a JOptionPane dialog.........................................................................................................920
Localize a JFileChooser.......................................................................................................................920
Select a directory with a JFileChooser.................................................................................................924
Disable the JFileChooser's 'New folder' button...................................................................................925
Validate a filename from a JFileChooser.............................................................................................927
Make a JFrame looks like a JDialog....................................................................................................928
Make a JFrame always visible.............................................................................................................929
Show a JFrame on a specific screen in a dual monitor configuration.................................................930
Make a frame not visible in the taskbar...............................................................................................930
xvi
Real's HowTo PDF version
Table of Contents
Swing
Based on JTextField content, enable or disable a JButton...................................................................931
Apply special filter to a JtextField.......................................................................................................932
Limit JTextField input to a maximum length......................................................................................936
Validate a value on the lostFocus event...............................................................................................937
Force the focus on a JTextfield when a JFrame is created..................................................................939
Stop the beep on JFormattedTextField................................................................................................940
Right justified JTextfield content........................................................................................................941
Set the focus on a particuliar JTextField..............................................................................................941
Make JTextField unselectable..............................................................................................................942
Disable copy paste functionality on JTextField...................................................................................942
Use a JTree to navigate in a site...........................................................................................................944
Expand or collapse a JTree..................................................................................................................951
Have a popup attached to a JTree........................................................................................................954
Traverse a JTree...................................................................................................................................956
Dotted Lines in a JTree........................................................................................................................958
Explore directories with a JTree..........................................................................................................958
Prevent JTree collapsing......................................................................................................................960
Single selection in a JTree...................................................................................................................960
Reduce JTree children indentation.......................................................................................................961
Use + or - for JTree Icons....................................................................................................................961
Change JTable header color.................................................................................................................963
Detect doubleclick on a JTable............................................................................................................964
Read a data file into a JTable...............................................................................................................966
Disable row selection in a JTable........................................................................................................969
Detect a data file modification and reload a JTable.............................................................................969
Hide a column in JTable......................................................................................................................971
Scroll a JTable to the last row..............................................................................................................973
Transfer a ResultSet to a JTable..........................................................................................................973
Have on a JScrollPane/JTable an horizontal JScrollbar......................................................................974
Make a JList select an item on doubleclick or the ENTER key..........................................................974
Make a JList like a scrolling text display.............................................................................................976
Have images in a JList.........................................................................................................................977
Add a row and clear a JList..................................................................................................................980
Sort a JList...........................................................................................................................................981
Double click on a JList........................................................................................................................982
Have a PopUp on a JList......................................................................................................................984
Make a JLabel selectable via the mouse..............................................................................................985
Change JLabel background color.........................................................................................................986
Bold/UnBold a JLabel.........................................................................................................................986
Multi-line JLabel..................................................................................................................................987
Underline in Swing..............................................................................................................................987
Update a JLabel....................................................................................................................................988
xvii
Real's HowTo PDF version
Table of Contents
Swing
Display a blinking JLabel....................................................................................................................988
Set the cursor position in a JTextArea.................................................................................................990
Have Multi-line string in a JToolTip...................................................................................................990
Change Tooltip color...........................................................................................................................991
Change a JTooltip font.........................................................................................................................991
Keep a JTooltip visible........................................................................................................................992
Display icon associated with an executable.........................................................................................993
Have items in JMenubar at rightmost position....................................................................................995
Have an JButton with an Image...........................................................................................................996
Trigger a click on a Button..................................................................................................................997
Thread..............................................................................................................................................................999
java-thread............................................................................................................................................999
Pipe the output of a thread to the input of another one........................................................................999
Pipe the output of a thread to the input of other threads....................................................................1001
Wait the for the completion of one thread.........................................................................................1004
Control a thread from outside............................................................................................................1005
Create a Timer object.........................................................................................................................1005
Pause the execution............................................................................................................................1007
Execute a method at regular interval.................................................................................................1007
Execute a process at regular interval.................................................................................................1009
Handle concurrent read/write.............................................................................................................1010
Communicate between threads using a Queue..................................................................................1012
Get a unique identifier.......................................................................................................................1017
Varia...............................................................................................................................................................1020
java-varia............................................................................................................................................1020
Use System time to generate unique ID.............................................................................................1020
Get a unique identifier.......................................................................................................................1020
Get the hard disk serial number or Motherboard Serial number.......................................................1022
Sort an array 1....................................................................................................................................1024
Sort an array 2....................................................................................................................................1026
Do a selection sort..............................................................................................................................1029
Validate a Social Security Number (canadian)..................................................................................1029
Validate a Credit Card Number.........................................................................................................1031
Obtain from where a Class is loaded.................................................................................................1035
Get the class name with or without the package................................................................................1036
See the generated bytecode................................................................................................................1037
Self-replicating programs...................................................................................................................1040
A curiosity..........................................................................................................................................1041
Common Bugs...................................................................................................................................1043
Number of the beast! :-).....................................................................................................................1044
xviii
Real's HowTo PDF version
Table of Contents
Varia
Use Java scripting engine (JDK 1.6)..................................................................................................1044
Pass or retrieve values from a scripting engine (JDK 1.6)................................................................1045
Preventing multiple instances of an application................................................................................1048
Trap JVM shutdown..........................................................................................................................1052
Minimize all programs on Windows to show the Desktop................................................................1052
Display a progress indicator in the console.......................................................................................1053
XML...............................................................................................................................................................1055
java-xml.............................................................................................................................................1055
Read me.............................................................................................................................................1055
Display XML using plain HTML......................................................................................................1056
Transform XML into HTML using XSLT.........................................................................................1057
Parse using SAX or DOM..................................................................................................................1059
Parse an XML string..........................................................................................................................1061
Create an XML document with DOM...............................................................................................1063
Attach a stylesheet to an XML file....................................................................................................1064
Create an XML file and attach an XSL.............................................................................................1065
Nicely display WEB.XML informations...........................................................................................1068
Serialize an object using XML..........................................................................................................1070
Convert flat file to XML using SAX.................................................................................................1071
Convert flat file to XML using DOM................................................................................................1073
Convert a ResultSet in XML.............................................................................................................1076
Parse with XPath................................................................................................................................1078
Strip extra spaces in a XML string....................................................................................................1082
Create an XML file and attach an XSL.............................................................................................1083
Use XML with Properties..................................................................................................................1087
Change a particular node in XML.....................................................................................................1088
Validate XML using a DTD..............................................................................................................1089
Validate XML using a XSD (XML schema).....................................................................................1093
Sanitize XML String..........................................................................................................................1099
Produce HTML entities when using XSLT.......................................................................................1100
Transform XML into CSV using XSLT............................................................................................1100
Create a RSS feed (part 1).................................................................................................................1102
Create a RSS feed (part 2).................................................................................................................1108
Parse a RSS XML file........................................................................................................................1115
Add a Live bookmark........................................................................................................................1117
Validate a RSS feed...........................................................................................................................1117
Attach a CSS to RSS feed..................................................................................................................1118
Handle JSON Object..........................................................................................................................1119
xix
Real's HowTo PDF version (november 2015).
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 [email protected]
Contributions via PayPal are accepted in any amount using a credit card or checking account.
DISCLAIMER
A CardLayout object is a layout manager for a container. It treats each component in the container as a card.
Only one card is visible at a time, and the container acts as a stack of cards.
In this HowTo, when a button is clicked the corresponding card is made visible.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.LayoutManager;
import java.awt.Panel;
AWT 3
Real's HowTo PDF version
setBackground(co);
setLayout(la);
}
and then
import java.applet.Applet;
import java.awt.Button;
import java.awt.CardLayout;
import java.awt.Choice;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
c2.addItem("Option C");
p2.add(c2);
// Add cards
p0.add("First card", p1);
p0.add("2nd card", p2);
p0.add("3rd card", p3);
if (c[i].isVisible()) {
t2.setText("" + (i+1));
break;
}
else
i ++;
}
}
}
}
<HTML>
<TABLE><TR><TD>
<APPLET CODE=CardLayoutDemo.class WIDTH=300 HEIGHT=300>
</APPLET>
</HMTL>
Try it here.
Component getComponentShowing(Container c) {
Component[] comps = c.getComponents();
int i = 0;
while(i < comps.length && !comps[i].isVisible())
++i;
return (i == comps.length) ? null : comps[i];
}
Use Popups
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java-0238.html
[JDK1.1]
import java.awt.*;
import java.awt.event.*;
import java.util.Hashtable;
public PopupTest() {
/*
** regular menu
*/
Menu m = new Menu("file");
MenuItem item = new MenuItem("file-1");
item.addActionListener(this);
m.add(item);
item = new MenuItem("file-2");
m.add(item);
MenuBar mb = new MenuBar();
mb.add(m);
setMenuBar(mb);
setSize(100, 100);
setLayout(new BorderLayout());
/*
** label with a popup
*/
Label l = new Label("label");
addPopup(l, "label");
add(l, "North");
/*
** panel with popup
*/
Panel p = new Panel();
p.setBackground(new Color(0).red);
addPopup(p, "Panel");
add(p, "Center");
/*
** button with popup
*/
Button b = new Button("button");
addPopup(b, "button");
add(b, "South");
addWindowListener
(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
setVisible(true);
}
Use Popups 7
Real's HowTo PDF version
/*
** initialize a Popup for a particular Component
*/
setHash(c, pm);
c.add(pm);
c.addMouseListener(this);
}
Use Popups 8
Real's HowTo PDF version
popupTable.put(c, p);
}
PopupMenu getHash(Component c) {
/*
** return a Popup associated with a particular Component
*/
return (PopupMenu)(popupTable.get(c));
}
On the Win platform, the setFilenameFilter method don't work. We must use the setFile method instead to set
a filter.
import java.awt.*;
public class UseFileDialog {
System.out.println
("Saving : "
+ ufd.saveFile(new Frame(), "Save...", ".\\", "*.java"));
System.exit(0);
}
}
return fd.getFile();
by
return fd.getDirectory() +
System.getProperty("file.separator") + fd.getFile();
fd.setFilenameFilter(new FilenameFilter(){
public boolean accept(File dir, String name){
return (name.endsWith(".jpg") || name.endsWith(".gif"));
}
});
[JDK1.4]
The names of the most common fonts supported by Java are TimesRoman, Courier, and Helvetica. To add
fonts, simply edit the properties.font file located in the lib of your JDK installation.
On a Windows system, to check what are the fonts available, go in the Font applet in the Parameters folder.
Choose a font and doubleclick on it. Check the name of the font. For example, on my system, I have a font
called Kaufmann, the real name is "Kaufmann BT". To be able to use this font, I add the following line in the
properties.font file in the section called # for backword compatibility.
NOTE: The three common fonts are the only ones guaranteed to be supported across all systems. To be able to use other fonts, you must modify the
properties.font file and these new fonts are not cross-plateform compatibles.
[JDK1.5]
@todo
[JDK1.1]
import java.awt.*;
public class FontList {
public static void main(String args[]) {
String[] fontNames = Toolkit.getDefaultToolkit().getFontList();
int j = fontNames.length;
for (int i = 0 ; i < j ;i++ ) {
System.out.println(fontNames[i]);
}
}
}
[JDK1.2]
import java.awt.*;
public class FontList {
public static void main(String args[]) {
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
String fontNames[] = ge.getAvailableFontFamilyNames();
int j = fontNames.length;
for (int i = 0 ; i < j ;i++ ) {
System.out.println(fontNames[i]);
}
}
}
import java.awt.*;
import java.applet.*;
}
}
<HTML>
<TABLE><TR><TD>
<APPLET CODE=SimpleApplet.class WIDTH=410 HEIGHT=500>
</APPLET>
</HMTL>
try it here
import java.awt.datatransfer.*;
import java.awt.*;
if (sm != null) {
try {
sm.checkSystemClipboardAccess();
}
catch (Exception e) {e.printStackTrace();}
}
Toolkit tk = Toolkit.getDefaultToolkit();
StringSelection st =
new StringSelection("Hello world from Java");
Clipboard cp = tk.getSystemClipboard();
cp.setContents(st, this);
}
NOTE: You can only use text (no graphic) with this functionality provided by the current JDK (1.4).
Maximize a Frame
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java-0222.html
JDK1.4
import java.awt.*;
...
GraphicsDevice device;
Frame frame = new Frame();
device =
GraphicsEnvironment.
getLocalGraphicsEnvironment().
getDefaultScreenDevice();
if ( device.isFullScreenSupported() ) {
device.setFullScreenWindow(frame);
}
else {
The "full-screen" Frame is in exclusive mode. In this mode you can change the resolution
import java.awt.*;
class ScreenRes {
public static void main(String args[]) {
new ScreenRes().doit();
}
}
else {
System.err.println("Change display mode not supported");
}
}
else {
System.err.println("Full screen not supported");
}
}
}
device.setFullScreenWindow(null);
SWING jdk1.3
Maximize a Frame 14
Real's HowTo PDF version
Center a Frame/Dialog
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java-0223.html
New with JDK1.4, JDialog has method to position a JDialog relative to a parent. For a JWindow or a JFrame
with no parent, then
f.setSize(100,100);
f.setLocationRelativeTo(NULL);
Center a Frame/Dialog 15
Real's HowTo PDF version
Close a Frame
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java-0225.html
[JDK1.0.2]
[JDK1.1 Method 1]
[JDK1.1 Method 2]
[JDK1.1 Method 3]
Close a Frame 16
Real's HowTo PDF version
(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
}
}
For a Dialog or a Window, a System.exit(0) may not be appropriate, call the dispose() method instead.
A component on a Panel can easily call events on the parent Frame. This way, we can put all the logic in one
place. In this example, a Frame contains 1 button and a Panel with 2 buttons on it. 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.
[TestEventPanel.java]
import java.awt.*;
import java.awt.event.*;
TestEventPanel(){
super();
setLayout(new FlowLayout());
setBackground(new Color(0).black);
b1 = new Button("call event on the frame");
add(b1);
b2 = new Button("close the parent frame");
add(b2);
}
}
The Frame after adding the Panel, will act as an ActionListener for events for the 2 Panel buttons.
[TestEventFrame.java]
import java.awt.*;
import java.awt.event.*;
TestEventFrame(String title){
super(title);
setLayout(new FlowLayout());
p1 = new TestEventPanel();
void createFrame() {
Dimension d = getToolkit().getScreenSize();
setLocation(d.width/4,d.height/3);
setSize(400,100);
setVisible(true);
}
if (ae.getSource()==p1.b1) {
System.out.println(ae.getActionCommand());
ActionEvent new_ae =
new ActionEvent (b1,
ActionEvent.ACTION_PERFORMED,
"Panel b1 is calling the dummy button");
b1.dispatchEvent (new_ae);
}
if (ae.getSource()==b1) {
if (ae.getSource()==p1.b2) {
System.out.println(ae.getActionCommand());
processEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
}
and finally
[Java0268.java]
import java.awt.*;
Try it here.
There is a bug in JDK1.0.2 for Windows, so you are stuck with the JAVA coffee cup.
In JDK1.1, this is fixed. You have to use a GIF file (not ICO file!). The GIF dimension should be 16x16. With
1.5, you can use a PNG or JPG file.
frame.setIconImage(Toolkit.getDefaultToolkit().getImage("myIcon.gif"));
frame.setIconImage
(Toolkit.getDefaultToolkit()
.getImage(getClass().
getResource("images/myIcon.gif")));
or
frame.setIconImage(
new ImageIcon(
YourApp.class.getResource("logo.png")
).getImage()
);
import java.awt.*;
import java.awt.event.*;
this.setResizable(false);
this.setSize(200,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.
import java.awt.*;
import java.awt.event.*;
NOTE: These How-to may not work with the Microsoft JVM. It's a feature...
import java.awt.*;
import java.awt.event.*;
ImageFrame() {
super("");
try {
MediaTracker mt = new MediaTracker (this);
// for Applet, change the method to retrieve the image
// and of course use your own image!
image = Toolkit.getDefaultToolkit().getImage("images/jht.gif");
mt.addImage(image, 0);
mt.waitForID(0);
}
catch (Exception e) {
e.printStackTrace();
}
setLayout(new FlowLayout());
add(new TextField(10));
add(new Button("hello"));
add(new List(20));
add(new TextArea(20,20));
// Label may not look too good ...
add(new Label("Hello"));
setSize(500, 500);
addWindowListener
(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
// change this for an Applet
System.out.println("Bye.");
System.exit(0);
}
}
);
}
int x = 0, y = 0;
while(y < getSize().height) {
x = 0;
while(x< getSize().width) {
g.drawImage(image, x, y, this);
x= x + image.getWidth(null);
}
y = y + image.getHeight(null);
}
}
else {
g.clearRect(0, 0, getSize().width, getSize().height);
}
}
The result :
With plain AWT, this simple class can be used as a Message Box.
import java.awt.*;
import java.awt.event.*;
/*
* @param frame parent frame
* @param msg message to be displayed
* @param okcan true : ok cancel buttons, false : ok button only
*/
MsgBox(Frame frame, String msg, boolean okcan){
super(frame, "Message", true);
setLayout(new BorderLayout());
add("Center",new Label(msg));
addOKCancelPanel(okcan);
createFrame();
pack();
setVisible(true);
}
void createOKButton(Panel p) {
p.add(ok = new Button("OK"));
ok.addActionListener(this);
}
void createCancelButton(Panel p) {
p.add(can = new Button("Cancel"));
can.addActionListener(this);
}
void createFrame() {
Dimension d = getToolkit().getScreenSize();
setLocation(d.width/3,d.height/3);
if (message.isOk)
System.out.println("Ok pressed");
if (!message.isOk)
System.out.println("Cancel pressed");
message.dispose();
}
}
This Splash class display a window containing a specified image while a parent Frame is doing its
initialization. When the parent is activated, the Splash window is destroyed.
[JDK1.1]
import java.awt.*;
import java.awt.event.*;
this.imgName = imgName;
tk = Toolkit.getDefaultToolkit();
splashImage = loadSplashImage();
showSplashScreen();
f.addWindowListener(new WindowListener());
}
public Image loadSplashImage() {
MediaTracker tracker = new MediaTracker(this);
Image result;
result = tk.getImage(imgName);
tracker.addImage(result, 0);
try {
tracker.waitForAll();
}
catch (Exception e) {
e.printStackTrace();
}
imgWidth = result.getWidth(this);
imgHeight = result.getHeight(this);
return (result);
}
The following example use this image (jht.gif) as the splash image.
import java.awt.*;
import java.awt.event.*;
Vibrate a Window
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java-0622.html
import java.awt.*;
Vibrate a Window 27
Real's HowTo PDF version
private FrameUtils() { }
FrameUtils.vibrate(myFrame);
To make it more Swing-oriented, you change the method signature for a JFrame instead.
Here an example.
We display a small window. When a file is added or deleted, the window is shaking for a brief moment and
display the event. By default, the folder c:/temp is used but you can specify another one on the command line.
First get the code to detect a file modfication in a folder (in this HowTo, you need the DirWatcher and
DirFilterWatcher classes). Plus the following classes.
import java.awt.*;
import java.awt.event.*;
public DirWatchWindow() {
setTitle("DirWatchWindow");
setSize(600, 100);
setLayout(new BorderLayout());
folder = new Label("");
info = new Label("");
add(folder, BorderLayout.NORTH);
Vibrate a Window 28
Real's HowTo PDF version
add(info, BorderLayout.SOUTH);
setVisible(true);
addWindowListener
(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
}
import java.util.*;
import java.io.*;
if (args.length > 0) {
folderToWatch = args[0];
}
Vibrate a Window 29
Real's HowTo PDF version
to specify your own folder. This demo is watching for files with the extension txt only.
[JDK1.0.2]
[JDK1.1]
import java.awt.TextField ;
import java.awt.event.KeyAdapter ;
import java.awt.event.KeyEvent ;
this.addKeyListener(new KeyAdapter()
{
public void keyTyped (KeyEvent e)
{
char c = e.getKeyChar() ;
if (! ((c==KeyEvent.VK_BACK_SPACE) || (c==KeyEvent.VK_DELETE)
|| (c== KeyEvent.VK_ENTER) || (c == KeyEvent.VK_TAB)
|| (Character.isDigit(c))))
{
e.consume() ;
}
}
});
}
[JDK11]
import java.awt.*;
import java.awt.event.*;
addKeyListener(this);
}
public TextFieldWithLimit (int col,int maxLength) {
this("",col,maxLength);
}
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
Toolkit.getDefaultToolkit().beep();
System.out.println("ENTER pressed");
}
}
}
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
First create a TextField that listen to the Enter and react like a Tab key [JDK11]
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
resetTextFields(this);
}
<HTML><HEAD></HEAD><BODY>
<APPLET CODE="FirstApplet.class"
NAME="myApplet"
HEIGHT=200 WIDTH=200>
</APPLET></BODY></HTML>
[JDK1.1]
import java.awt.*;
import java.awt.event.*;
public UpperTF() {
setLayout(new FlowLayout());
TextField tf = new TextField(10);
add(tf);
tf.addKeyListener(
new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (Character.isLetter(e.getKeyChar()))
e.setModifiers(Event.SHIFT_MASK);
}
});
pack();
addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
}
Have an ImageButton
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java-0245.html
This implementation of an ImageButton requires JDK1.1 and is a good example of the new Event
architecture. This ImageButton needs 2 GIF images representing the normal and pressed state ( ).
Also a method to disable the button by using a special filter is given.
[ImageButton.java]
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.net.*;
Have an ImageButton 36
Real's HowTo PDF version
try {
UPimage = getToolkit().getImage(up);
DOWNimage = getToolkit().getImage(down);
tracker = new MediaTracker(this);
tracker.addImage(UPimage,0);
tracker.addImage(DOWNimage,1);
tracker.waitForAll();
}
catch (InterruptedException e) {
e.printStackTrace();
}
disabledimage=createImage(new FilteredImageSource
(UPimage.getSource(),new ImageButtonDisableFilter()));
w=UPimage.getWidth(this);
h=UPimage.getHeight(this);
}
Have an ImageButton 37
Real's HowTo PDF version
down=true;
repaint();
}
}
public void mouseReleased(MouseEvent e) {
Point p = e.getPoint();
if (down) {
down=false;
repaint();
}
if ((p.x < w)&&(p.y < h)&&(p.x > 0)&&(p.y > 0)&&(clicked==true)) {
ActionEvent ae =
new ActionEvent(e.getComponent(),0,"click");
if (actionListener != null) {
actionListener.actionPerformed(ae);
}
}
clicked=false;
}
}
public class ImageButtonMouseMotionListener extends
MouseMotionAdapter {
public void mouseDragged(MouseEvent e) {
Point p = e.getPoint();
if ((p.x < w)&&(p.y < h)&&(p.x > 0)&&(p.y > 0)&&(clicked==true)) {
if (down==false) {
down=true;
repaint();
}
}
else {
if (down==true) {
down=false;
repaint();
}
}
}
}
Have an ImageButton 38
Real's HowTo PDF version
}
}
}
[TestImageButton.java]
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.net.*;
import java.applet.*;
import java.awt.*;
The width can be specified via the preferredSize method. This class lets you specify a font (fixed pitch) and
calculate the appropriate width in pixels.
ml = new List();
my.setFont(new Font("Courier", Font.BOLD, 10));
When inserting a line, we simply pad spaces as needed. Here the first column is 20 characters wide, the
second 10 and the last one the remaining.
In real life, the preferred way would be to extend the java.awt.List and override the addItem method.
A srolling text display can be used to log informations or events. In this snippet, we are using a List
component to display the data. We are keeping only the last 10 events. It's a good idea to limit the amount of
data kept in the List , in fact we have no choice because the maximum capacity is about 32k (Win).
import java.awt.*;
import java.awt.event.*;
With a Layout Manager, you have to validate() the layout to redraw the components invalidated.
this.validate();
While this method works in Netscape or the Appletviewer, on IE4/5 there is no resizing. You may want to try
this instead (thanks to Dan for the tip):
This example how to change a Label or a String drawn with the drawString method by clicking on a button.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
MyPanel() { super(); }
import java.awt.*;
import java.awt.event.*;
setVisible(true);
}
import java.applet.*;
import java.awt.*;
import java.applet.*;
import java.awt.*;
[JDK1.4]
import java.awt.geom.AffineTransform;
import java.awt.Graphics2D;
// clockwise 90 degrees
AffineTransform at = new AffineTransform();
// thanks to M.C. Henle for the bug fix!
at.setToRotation(-Math.PI/2.0, width/2.0, height/2.0);
g2d.setTransform(at);
g2d.drawString("Vertical text", x, y);
}
The Label component included in the AWT do not support "\n" in its definition. The following class
implements a multi-line Label. Lines are separated byt the token "\n". Lines can be left, right or center
justified. Plus, there is a possibility to have a border around the label.
import java.awt.*;
import java.util.*;
public MultiLineLabel() {
this("", 0);
}
super.paint(g);
Dimension d = getSize();
if ( (offGraphics == null) ||
(d.width != offDimension.width) ||
(d.height != offDimension.height)
) {
offDimension = d;
offImage = createImage(d.width, d.height);
offGraphics = offImage.getGraphics();
}
offGraphics.setColor(getBackground());
offGraphics.fillRect
(x, y, getSize().width - 1,
getSize().height - 1);
if (border) {
offGraphics.setColor(borderColor);
offGraphics.drawRect
(x, y, getSize().width - 1, getSize().height - 1);
}
int j = line_ascent +
(d.height - num_lines * line_height) / 2;
for (int k = 0; k < num_lines; ) {
int i;
switch (alignment) {
case 0:
i = 0;
break;
case 2:
i = d.width - line_widths[k];
break;
default:
i = (d.width - line_widths[k]) / 2;
break;
}
i += leftRightMargin;
offGraphics.setColor(getForeground());
offGraphics.drawString(lines[k], i + x, j + y);
k++;
j += line_height;
}
g.drawImage(offImage,0,0,this);
}
f.validate();
}
}
[UnderlinedLabel.java]
import java.awt.*;
[TestUnderlinedLabel.java]
import java.applet.*;
import java.awt.*;
[testapplet.html]
<HTML><HEAD></HEAD><BODY>
<APPLET CODE="TestUnderlinedLabel.class"
NAME="myApplet"
HEIGHT=200 WIDTH=200>
</APPLET></BODY></HTML>
[URLLabel.java]
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
public URLLabel
(Applet applet , String url, String text, String target){
super(text);
setForeground(unvisitedURL);
try {
this.applet = applet;
this.url = new URL(url);
this.target = target;
addMouseListener( new Clicked() );
}
catch (Exception e) {
e.printStackTrace();
}
}
[TestURLLabel.java]
import java.applet.*;
import java.awt.*;
add(ull3);
URLLabel ull4 = new URLLabel(this,
"http://www.rgagnon.com/javadetails/java-0002.html",
"Java How-to 0002");
add(ull4);
validate();
}
}
[testapplet.html]
<HTML><HEAD></HEAD><BODY>
<APPLET CODE="TestURLLabel.class"
NAME="myApplet"
HEIGHT=200 WIDTH=200>
</APPLET></BODY></HTML>
Try it here.
import java.awt.*;
import java.awt.image.*;
if (argv.length <1) {
System.out.println
("usage: ImageCanvas.class [image file name]");
System.exit(0);
}
Frame frame = new Frame(argv[0]);
frame.setLayout(new BorderLayout());
frame.add("Center", new ImageCanvas(argv[0]));
frame.resize(400,400);
frame.show();
}
}
import java.awt.*;
import java.awt.event.*;
ImageFrame() {
super("");
try {
MediaTracker mt = new MediaTracker (this);
// for Applet, change the method to retrieve the image
// and of course use your own image!
image = Toolkit.getDefaultToolkit().getImage("images/jht.gif");
mt.addImage(image, 0);
mt.waitForID(0);
}
catch (Exception e) {
e.printStackTrace();
}
setLayout(new FlowLayout());
add(new TextField(10));
add(new Button("hello"));
add(new List(20));
add(new TextArea(20,20));
// Label may not look too good ...
add(new Label("Hello"));
setSize(500, 500);
addWindowListener
(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
// change this for an Applet
System.out.println("Bye.");
System.exit(0);
}
}
);
}
The result :
It's a good idea to combine small GIFs into a single big one to speed up the loading process. In the following
snippet, I assume that all images are the same height and width. You may want to get this GIF ( ) if you
want to try the example on your workstation!
import java.applet.*;
import java.awt.*;
import java.io.*;
import java.net.*;
[JDK1.1 application]
catch (Exception e) {
e.printStackTrace();
}
try {
MediaTracker m = new MediaTracker(this);
InputStream is = getClass().getResourceAsStream("image.gif");
//
// if your image is in a subdir in the jar then
// InputStream is = getClass().getResourceAsStream("img/image.gif");
// for example
//
BufferedInputStream bis = new BufferedInputStream(is);
// a buffer large enough for our image
//
// can be
// byte[] byBuf = = new byte[is.available()];
// is.read(byBuf); or something like that...
byte[] byBuf = = new byte[10000];
Remember that it is always possible to the Java built-in icons so that you don't have to include your own
standard icons.
Scale an Image
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java-0243.html
import java.awt.image.*;
import java.awt.*;
import java.net.*;
Scale an Image 60
Real's HowTo PDF version
resizedImage = createImage(prod);
media.addImage(resizedImage,1);
media.waitForID(1);
}
catch(InterruptedException e) {}
}
Try it here.
The following exampe takes a JPG file as input , rescale it to the passed parameters and writes the result in the
specified output file.
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
Scale an Image 61
Real's HowTo PDF version
}
}
}
Example :
Input:
Ouput:
Fade an image
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java-0249.html
import java.applet.*;
import java.awt.*;
import java.awt.image.*;
import java.net.*;
Fade an image 62
Real's HowTo PDF version
f.setLevel(level);
fis = new FilteredImageSource(img.getSource(), f) ;
Fade an image 63
Real's HowTo PDF version
sleep(delay);
fadeApplet.fadeIt();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
public AlphaFilter() {
canFilterIndexColorModel = true;
}
Try it here.
Rotate an image
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java-0248.html
The following snippet rotates an image (90 degrees). The applet assumes the dimension 32x32 for the image.
import java.applet.Applet;
import java.awt.*;
import java.awt.image.*;
import java.net.*;
Rotate an image 64
Real's HowTo PDF version
The next example will rotate a picture 5 degrees at a time. We are using the Java2D package (and Swing).
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
Rotate an image 65
Real's HowTo PDF version
}
catch (Exception e) {
e.printStackTrace();
}
}
Rotate an image 66
Real's HowTo PDF version
import java.applet.*;
import java.awt.*;
myCanvas() { super(); }
public void paint(Graphics g) {
if (!initDone)
initpaint(g);
else
g.drawImage(buffImage, 0, 0, this);
}
import java.applet.*;
import java.awt.*;
// constructor
// visible h w
// real h w
// background foreground
ScrollCanvas
(int vw1, int vh1, int rw1, int rh1, Color b1, Color f1) {
super();
vw = vw1; vh = vh1;
rh = rh1; rw = rw1;
b = b1; f = f1;
int ScrollIncrement = 10;
setLayout(new BorderLayout());
c = new myCanvas(vw, vh, rw, rh, b ,f);
add("West", c);
sv = new Scrollbar
(Scrollbar.VERTICAL,0, ScrollIncrement, 0, rh);
add("East", sv);
sh = new Scrollbar
(Scrollbar.HORIZONTAL, 0, ScrollIncrement, 0, rw);
add("South", sh);
}
myCanvas
(int vw1, int vh1, int rw1, int rh1, Color b1, Color f1) {
super();
vw = vw1; vh = vh1;
rh = rh1; rw = rw1;
b = b1; f = f1;
initDone = false;
repaint();
}
else
g.drawImage(buffImage, x, y, this);
}
import java.applet.Applet;
import java.net.*;
// TILE BACKGROUND
// in the HTML use :
<HTML>
<TABLE><TR><TD>
<APPLET CODE=Tile.class WIDTH=150 HEIGHT=150>
<PARAM NAME="bgImage" VALUE="images/jht.gif">
</APPLET>
</HMTL>
Try it here.
[imagelist.txt]
jht.gif|JAVA How-to
jsht.gif|Javascript How-to
pht.gif|Powerbuilder How-to
[application version]
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public AFrame() {
setTitle("Image selection, double click to display");
setLayout(new GridLayout(1,2));
setSize(800,600);
lbx = new List();
can = new MyCanvas();
add(lbx); add(can);
initLbx();
// action on listbox double click
lbx.addActionListener(this);
// to close the Frame
addWindowListener
(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
setVisible(true);
}
[applet version]
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public APanel(Applet a) {
parent = a;
setLayout(new GridLayout(1,2));
lbx = new List();
can = new MyCanvas();
add(lbx); add(can);
initLbx();
// action on listbox double click
lbx.addActionListener(this);
setBackground(new Color(0).white);
}
Use a special Canvas to preload 2 GIFs, and using a MouseListener simply toggle the image.
[JDK1.1]
import java.awt.*;
import java.awt.event.*;
import java.net.*;
img1 = Toolkit.getDefaultToolkit().getImage(n1);
img2 = Toolkit.getDefaultToolkit().getImage(n2);
tracker.addImage(img1,0);
tracker.addImage(img2,1);
tracker.waitForAll();
addMouseListener(this);
}
catch (Exception e) {
e.printStackTrace();
}
}
To use such Canvas, try something like this. This example needs our Gumby GIFs ( and ).
import java.applet.*;
import java.awt.*;
import java.net.*;
try {
tgc = new ToggleGifCanvas
(new URL(getDocumentBase(),"images/gumby.gif"),
new URL(getDocumentBase(),"images/gumby2.gif"));
add(tgc);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Try it here.
Here we have an Image with a blue background like and we want to display it in an Applet with a white
background. All we have to do is to look for the blue color with the "Alpha bits" set to opaque and make them
transparent.
[Transparency.java]
import java.awt.*;
import java.awt.image.*;
// the color we are looking for... Alpha bits are set to opaque
public int markerRGB = color.getRGB() | 0xFF000000;
[app.java]
import java.awt.image.*;
import java.awt.*;
import java.net.*;
[x.html]
<HTML><HEAD></HEAD><BODY>
<APPLET CODE="app.class"
NAME="myApplet"
HEIGHT=200 WIDTH=200>
</APPLET>
</BODY></HTML>
With JDK1.2, Sun introduces a new package called JIMI (available for download at their Web site. With this
package, it's easy to convert a Java Image to a JPEG image file.
double w = 200.0;
double h = 200.0;
BufferedImage image = new BufferedImage(
(int)w,(int)h,BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D)image.getGraphics();
g.drawLine(0,0,w,h);
try {
File f = new File("myimage.jpg");
JimiRasterImage jrf = Jimi.createRasterImage(image.getSource());
Jimi.putImage("image/jpeg",jrf,new FileOutputStream(f));
}
catch (JimiException je) {
je.printStackTrace();}
// [JDK1.2]
// img is a Java Image
//
BufferedImage bimg = null;
int w = img.getWidth(null);
int h = img.getHeight(null);
int [] pixels = new int[w * h];
PixelGrabber pg = new PixelGrabber(img,0,0,w,h,pixels,0,w);
try {
pg.grabPixels();
}
catch(InterruptedException ie) {
ie.printStackTrace();
}
// Encode as a JPEG
FileOutputStream fos = new FileOutputStream("out.jpg");
JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(fos);
jpeg.encode(bimg);
fos.close();
Since JDK1.4.2, javax.imageio.ImageIO lets you save and restore Images to disk in a platform independent
format. "png" and "jpeg" format are supported. With ImageIO, instead of Image you use BufferedImage
which is a subclass of Image.
import java.io.*;
import javax.imageio.*;
import java.awt.image.*;
import java.applet.*;
import java.awt.*;
import java.awt.image.*;
import java.net.*;
Try it here.
Like the previous How-to, using a Thread, we switch between 2 GIFs, for example ( and ).
Click the button to simulate some work, click again to terminate the "work in progress"
[JDK1.1]
import java.applet.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.net.*;
implements ActionListener{
Image [] img;
int index = 0;
int maxImg;
boolean working = false;
Button b;
MediaTracker tracker;
this.animationApplet = a;
this.delay = delay;
}
From here, individual pixel can be accessed via the pixels array.
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage
...
int c = image.getRGB(x,y);
int red = (c & 0x00ff0000) >> 16;
int green = (c & 0x0000ff00) >> 8;
int blue = c & 0x000000ff;
// and the Java Color is ...
Color color = new Color(red,green,blue);
Do "rubber-band" drawing
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java-0251.html
import java.applet.*;
import java.awt.*;
import java.util.Vector;
Do "rubber-band" drawing 85
Real's HowTo PDF version
}
}
}
Do "rubber-band" drawing 86
Real's HowTo PDF version
import java.awt.*;
public class Color2Hex {
public static void main( String[] args ) {
if (args.length != 3) {
System.out.println("Color2Hex r g b");
}
else {
int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
int k = Integer.parseInt(args[2]);
import java.awt.image.*;
import java.awt.*;
import java.applet.*;
double xincdash=(x2-x1)/(linelength/(dashlength));
double yincdash=(y2-y1)/(linelength/(dashlength));
int counter=0;
for (double i=0;i<linelength-dashlength;i+=dashlength+spacelength){
g.drawLine((int) (x1+xincdashspace*counter),
(int) (y1+yincdashspace*counter),
(int) (x1+xincdashspace*counter+xincdash),
(int) (y1+yincdashspace*counter+yincdash));
counter++;
}
if ((dashlength+spacelength)*counter<=linelength)
g.drawLine((int) (x1+xincdashspace*counter),
(int) (y1+yincdashspace*counter),
x2,y2);
}
import java.awt.*;
import java.applet.*;
drawThickLine
(g, getSize().width/2, 0, getSize().width/2, getSize().height, 8,
new Color(0).green);
drawThickLine
(g, 0, getSize().height/2, getSize().width, getSize().height/2, 12,
new Color(0).blue);
}
Using JDK1.2
On a Component
Using JDK1.3
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public MyPanel(){}
import java.util.*;
import java.awt.*;
import java.applet.Applet;
colors.put("green", Color.green);
colors.put("red", Color.red);
colors.put("blue", Color.blue);
colors.put("yellow", Color.yellow);
colors.put("magenta", Color.magenta);
colors.put("cyan", Color.cyan);
colors.put("orange", Color.orange);
colors.put("pink", Color.pink);
colors.put("white", Color.white);
colors.put("black", Color.black);
// "value-color,value-color,..."
StringTokenizer t = new StringTokenizer(at, ",");
String s;
int i;
while (t.hasMoreTokens()) {
s = t.nextToken();
i = s.indexOf('-');
value = Float.valueOf(s.substring(0, i)).floatValue();
c.addSlice(value, (Color)colors.get(s.substring(i + 1)));
}
resize(c.getMinimumSize().width, c.getMinimumSize().height);
add("Center", c);
}
}
if(gfxBuff == null) {
gfxBuff = createImage(d.width, d.height);
offGraphics = gfxBuff.getGraphics();
offGraphics.setColor(getBackground());
// do the 3d effect
for(int x = depth; x >= 1; x--) {
startAngle = -45;
for(int i = 0; i < numSlices; i++) {
offGraphics.setColor(color[i].darker());
angle = Math.round(360 * (value[i] / total));
offGraphics.fillArc(0, x, radius, (int)(radius / aspectFudge),
startAngle, (int)angle);
startAngle += angle;
}
}
[JavaPie.hmtl]
<HTML>
<TABLE><TR><TD>
<APPLET CODE=Graph.class WIDTH=150 HEIGHT=150>
<PARAM NAME="depth" VALUE="30">
<PARAM NAME="width" VALUE="120">
<PARAM NAME="values" VALUE="1-red,5-green,7-blue">
</APPLET>
<TD>
<TABLE>
<TR><TD>item 1<TD BGCOLOR="#FF0000">
Try it here
It seems that drawRoundRect(.) is 1,5 faster then drawRect(..) , because one of them is completely native.
import java.awt.*;
import java.awt.event.*;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
class ScreenCapture {
public static void main(String args[]) throws
AWTException, IOException {
// capture the whole screen
BufferedImage screencapture = new Robot().createScreenCapture(
new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()) );
// Save as JPEG
File file = new File("screencapture.jpg");
ImageIO.write(screencapture, "jpg", file);
// Save as PNG
// File file = new File("screencapture.png");
// ImageIO.write(screencapture, "png", file);
}
}
[JDK1.02]
import java.applet.*;
import java.awt.*;
[JDK11]
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
[JDK11]
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
}
}
}
import java.awt.*;
import java.awt.event.*;
ExitFromMenu() {
super("");
MenuBar mb = new MenuBar();
mb.add(m);
MenuItem m1 = m.add(new MenuItem("Exit",
new MenuShortcut(KeyEvent.VK_X)));
m1.setActionCommand("Exit");
m.addActionListener(this);
setMenuBar(mb);
addWindowListener
(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
// unique exit point
System.out.println("Bye.");
System.exit(0);
}
}
);
add(new Label
("You can quit by clicking on the 'X'"),"South");
add(new Label
("You can quit by clicking on the menu item 'Exit'"),"Center");
add(new Label
("You can quit with the MenuShortcut 'ctrl-x'"),"North");
setSize(300, 300);
show();
}
if (what.equals("Exit"))
In this example, when we click on a Button, we trigger the action attached to the another Button.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
b1.addActionListener(this);
b2.addActionListener(this);
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
b1.addActionListener(this);
b2.addActionListener(this);
}
Display a TIF
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java-0605.html
The regular JDK can only deal with JPG, GIF, BMP or PNG file with the package ImageIO, see this HowTo.
To deal with TIF file, you must use the JAI (Java Advanced Imaging) package.
This example will display a given TIF file. It will also display other types (JPG,...) by detecting the type.
import javax.media.jai.PlanarImage;
import com.sun.media.jai.codec.ByteArraySeekableStream;
import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.SeekableStream;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.awt.Image;
import java.awt.image.RenderedImage;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
http://java.sun.com/javase/technologies/desktop/media/jai/
https://jai.dev.java.net/#Downloads
Tagged Image File Format (abbreviated TIFF) is a file format for mainly storing images, including
photographs and line art. 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, rather than have each company promulgate its
own proprietary format.
This HowTo takes a multi-page TIF (from a FAX) and convert it into many single-pages TIF.
http://java.sun.com/products/java-media/jai/index.jsp
>
import java.io.*;
import com.sun.media.jai.codec.FileSeekableStream;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.TIFFEncodeParam;
import java.awt.image.RenderedImage;
import javax.media.jai.RenderedOp;
import javax.media.jai.JAI;
import java.awt.image.renderable.ParameterBlock;
You may want to consider to use an external utility to do this kind on conversion. A nice one is irfanview
(win), a (free) multi-purpose graphic utility.
http://www.irfanview.com/
irfanview is an amazing software when it comes to transform a graphic format to another one. You can use it
from a command line or from a GUI.
See also : Convert many single-page TIF into one multi-page TIF
This HowTo takes a list of single-page TIF and convert them into one multi-page TIF.
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.awt.image.BufferedImage;
import javax.media.jai.NullOpImage;
import javax.media.jai.OpImage;
import javax.media.jai.PlanarImage;
import com.sun.media.jai.codec.ImageEncoder;
import com.sun.media.jai.codec.SeekableStream;
import com.sun.media.jai.codec.FileSeekableStream;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.TIFFEncodeParam;
System.out.println("Done.");
}
}
http://www.rgagnon.com/javadetails/../javadetails/java-0601.html
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
You need to do something to transform an Image to BufferedImage. But since BufferedImage extends Image,
so there isn't a back-conversion, it's not needed.
import javax.media.jai.PlanarImage;
import com.sun.media.jai.codec.ByteArraySeekableStream;
import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.SeekableStream;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.PixelGrabber;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
/**
* This utility loads a given TIF and try to detect if it's
* blank or not.
*
* We create in-memory image and then calculate the standard
* deviation of the color information. If a certain value is not
* reached then we assume that the image is mainly uniform and
* probably blank. The threshold value is an estimate. Depending
* the source of the TIF this value can be higher. For example,
* TIF from a FAX machine or a scanner can be dirty, with hair/dust presence,
* but with no content.
*
* jai_core.jar and jai_codec.jar are required.
* http://java.sun.com/products/java-media/jai/index.jsp
*
* @author http://www.rgagnon.com/howto.html
*/
/**
* Creates an Image from a byte array
* @param data
* @return Image
* @throws Exception
*/
public static Image load(byte[] data) throws Exception {
Image image = null;
SeekableStream stream = new ByteArraySeekableStream(data);
String[] names = ImageCodec.getDecoderNames(stream);
ImageDecoder dec =
/**
* Converts an Image to a BufferedImage
* @param im une Image
* @return BufferedImage
*/
public static BufferedImage imageToBufferedImage(Image im) {
BufferedImage bi = new BufferedImage
(im.getWidth(null),im.getHeight(null),BufferedImage.TYPE_INT_RGB);
Graphics bg = bi.getGraphics();
bg.drawImage(im, 0, 0, null);
bg.dispose();
return bi;
}
/**
* Check if an Image is blank or not
* Computes the standard deviation based on the color information
* @param bi bufferedimage
* @return true it's blank
*/
public static boolean isBlank(BufferedImage bi) throws Exception {
long count = 0;
long total = 0;
double totalVariance = 0;
double stdDev = 0;
int height = bi.getHeight();
int width = bi.getWidth();
/**
* Accept on the command line the path to a TIF file
*
* Returns an errorlevel based on the analysis
* 0 - blank
* 1 - not blank
* 2 - IO error
*
* @param args path vers complet vers un PROPS
*/
public static void main(String[] args) {
try {
if (args.length==0) {
System.out.println("Missing parameter.");
System.exit(FAILURE);
}
String path = args[0];
FileInputStream in = new FileInputStream(path);
FileChannel channel = in.getChannel();
ByteBuffer buffer = ByteBuffer.allocate((int)channel.size());
channel.read(buffer);
Image image = load(buffer.array());
BufferedImage bufferedImage = imageToBufferedImage(image);
boolean isBlank = BlankDetection.isBlank(bufferedImage);
This HowTo is based on the iText package. You need a recent version (ex. 2.*)
This a command line utility. You pass one or many tif files as argument and corresponding PDF are produced.
Multipage TIF are supported. TIF are resized to fit a letter-page dimension.
import java.io.FileOutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.RandomAccessFileOrArray;
import com.lowagie.text.pdf.codec.TiffImage;
++pages;
}
}
catch (Throwable e) {
System.out.println("Exception " + tiff + " page "
+ (c + 1) + " " + e.getMessage());
}
}
ra.close();
document.close();
}
catch (Throwable e) {
e.printStackTrace();
}
System.out.println("done");
}
}
}
http://java.sun.com/javase/technologies/desktop/media/jai/
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.awt.image.RenderedImage;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.media.jai.codec.SeekableStream;
import com.sun.media.jai.codec.FileSeekableStream;
import com.sun.media.jai.codec.TIFFDecodeParam;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.ImageCodec;
The getYear() method returns the number of years elapsed after the year 1900. So for year 2000,
mydate.getYear() will return 100. So 100 + 1900 = 2000.
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.text.SimpleDateFormat;
One technique is to compute by hand the number of milliseconds between two dates and then convert the
result in days.
import java.util.*;
/*
testing
*/
public static void main(String[] args) {
java.text.SimpleDateFormat sdf =
new java.text.SimpleDateFormat("yyyyMMdd");
Calendar first = Calendar.getInstance();
first.set(2008, Calendar.AUGUST, 1);
Calendar second = Calendar.getInstance();
System.out.println
(daysBetween(first.getTime(),second.getTime())
+ " day(s) between "
+ sdf.format(first.getTime()) + " and "
+ sdf.format(second.getTime()));
/*
* output :
* 21 day(s) between 20080801 and 20080822
*/
}
}
NOTE: The daysBetween() method works only on Dates set at midnight. 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.
Another way would be to compute the julian day number of both dates and then do the substraction. See this
HowTo. Thanks to P. Hill for the tip.
The package java.util.concurrent.TimeUnit; provides a class to make conversion between milliseconds and
days easier.
import java.util.*;
import java.util.concurrent.TimeUnit;
/*
testing
*/
public static void main(String[] args) {
java.text.SimpleDateFormat sdf =
new java.text.SimpleDateFormat("yyyyMMdd");
Calendar augustfirst2008 = Calendar.getInstance();
augustfirst2008.set(2008, Calendar.AUGUST, 1); // 2008-08-01
Calendar today = Calendar.getInstance(); // today
System.out.println
(getDifference(augustfirst2008,today,TimeUnit.DAYS)
+ " day(s) between "
+ sdf.format(augustfirst2008.getTime()) + " and "
+ sdf.format(today.getTime()));
}
/*
* output :
* 921 day(s) between 20080801 and 20110208
*/
}
Actually, the Calendar class provides a method to that very simply. For a given Calendar or
GregorianCalendar object :
calObject.getActualMaximum(calobject.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. There is almost
always a more efficient way to accomplish this (in most cases, you can simply return getMaximum()).
GregorianCalendar overrides this function with a more efficient implementation. So it looks like it's a lot
more efficient to call getActualMaximum from a GregorianCalendar object than a Calendar object. (Thanks to P.
Harris for the tip)
gregCalObject.getActualMaximum(gregCalObject.DAY_OF_MONTH)
Validate a date
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java-0099.html
Using DateFormat
import java.text.*;
DateFormat.getDateInstance
(DateFormat.SHORT); // YYYY-MM-DD
df.setLenient(false); // this is important!
df.parse(date);
}
catch (ParseException e) {
return false;
}
catch (IllegalArgumentException e) {
return false;
}
return true;
}
Using SimpleDateFormat
package com.rgagnon.howto;
import java.text.*;
Using GregorianCalendar
import java.util.*;
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.YEAR, Calendar.MONTH,
Calendar.DATE).
add() adds or substracts values to the specified Calendar field, the next larger field is modified when the result
makes the Calendar "rolls over".
import java.util.Calendar;
import java.text.SimpleDateFormat;
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. The operation only affects the specified field while add() adjusts other Calendar
fields.
See the following example, roll() makes january rolls to december in the same year while add() substract the
YEAR field for the correct result.
import java.util.Calendar;
import java.text.SimpleDateFormat;
There is a bug in the DateFormat/SimpleDateFormat classes. We must set the TimeZone manually.
The format "YYYYMMDD" can be useful when sorting records or comparing 2 dates.
import java.util.Calendar;
import java.text.SimpleDateFormat;
Compare 2 dates
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java-0104.html
import java.util.*;
import java.util.*;
import java.text.*;
System.out.print(sdf.format(c1.getTime()));
if (c1.before(c2)) {
System.out.print(" is before ");
}
if (c1.after(c2)) {
System.out.print(" is after ");
}
if (c1.equals(c2)) {
System.out.print(" same as ");
}
System.out.println(sdf.format(c2.getTime()));
}
}
import java.util.Date;
import java.util.Locale;
import java.util.Calendar;
import java.text.SimpleDateFormat;
SimpleDateFormat sdf =
new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("Calendar : "
+ sdf.format(parseTimestamp(timestampToParse).getTime()));
/*
output :
Timestamp : 24-Feb-1998 17:39:35
Calendar : 1998-02-24 17:39:35
*/
}
Since the granulaty of a PC can be as high as 55ms (down to 10ms), you can't use the System time to generate
a unique ID because of the risk of getting duplicated IDs. This can be solved by using the following technique
to make sure that the number returned is unique (in a single JVM).
import java.util.*;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
An alternate way :
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.*;
import java.util.*;
public class Dtest {
public static void main(String args[]) {
SimpleDateFormat df = (SimpleDateFormat)
DateFormat.getDateInstance(DateFormat.SHORT);
System.out.println("The short date format is " + df.toPattern());
Locale loc = Locale.ITALY;
df = (SimpleDateFormat)
DateFormat.getDateInstance(DateFormat.SHORT, loc);
System.out.println("The short date format is " + df.toPattern());
}
}
A Julian date is the number of elapsed days since the beginning of a cycle of 7,980 years invented by Joseph
Scaliger in 1583. 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.
The starting point for the first Julian cycle began on January 1, 4713 B.C. and will end on January 22, 3268
(3268-01-22 G). The following day will begin the first day of the second Julian date period (or 7,980 year
cycle).
import java.util.Calendar;
public class JulianDate {
/**
* Returns the Julian day number that begins at noon of
* this day, Positive year signifies A.D., negative year B.C.
* Remember that the year after 1 B.C. was 1 A.D.
*
* ref :
* Numerical Recipes in C, 2nd ed., Cambridge University Press 1992
*/
// Gregorian Calendar adopted Oct. 15, 1582 (2299161)
public static int JGREG= 15 + 31*(10+12*1582);
public static double HALFSECOND = 0.5;
/**
* Converts a Julian day to a calendar date
* ref :
* Numerical Recipes in C, 2nd ed., Cambridge University Press 1992
*/
public static int[] fromJulian(double injulian) {
int jalpha,ja,jb,jc,jd,je,year,month,day;
double julian = injulian + HALFSECOND / 86400.0;
ja = (int) julian
if (ja>= JGREG) {
jalpha = (int) (((ja - 1867216) - 0.25) / 36524.25);
ja = ja + 1 + jalpha - jalpha / 4;
}
jb = ja + 1524;
jc = (int) (6680.0 + ((jb - 2439870) - 122.1) / 365.25);
jd = 365 * jc + jc / 4;
je = (int) ((jb - jd) / 30.6001);
day = jb - jd - (int) (30.6001 * je);
month = je - 1;
if (month > 12) month = month - 12;
year = jc - 4715;
if (month > 2) year--;
if (year <= 0) year--;
today.get(Calendar.DATE)});
System.out.println("Julian date for today : " + todayJulian);
results = fromJulian(todayJulian);
System.out.println
("... back to calendar : " + results[0] + " " + results[1]
+ " " + results[2]);
// THIRD TEST
double date1 = toJulian(new int[]{2005,1,1});
double date2 = toJulian(new int[]{2005,1,31});
System.out.println("Between 2005-01-01 and 2005-01-31 : "
+ (date2 - date1) + " days");
/*
expected output :
Julian date for May 23, 1968 : 2440000.0
... back to calendar 1968 5 23
Julian date for today : 2453487.0
... back to calendar 2005 4 26
Between 2005-01-01 and 2005-01-31 : 30.0 days
*/
}
}
There is a lot of variation around the idea of a "Julian date". You can have the Modified Julian Date (JD) or
the Truncated Julian Date (TJD). The main difference is the starting for counting the days.
Before Y2K, many applications (especially mainframe systems) were storing dates in a format called "the
Julian format". This format is a 5 digit number, consisting of a 2 digit year and a 3 digit day-of-year number.
For example, 17-July-1998 is stored as 98221, since 17-July is the 221th day of the year. 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.
A variation of this idea is to used the first four digits for the year and 3 digits for day-of-year, 17-July-1998
will be represented by 1998221.
This is a very simple format which can be manipulated easily from Java.
import java.util.Calendar;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
return sb.append(cal.get(Calendar.YEAR))
.append(String.format("%03d", cal.get(Calendar.DAY_OF_YEAR)))
.toString();
}
/*
* output :
* Sun Aug 09 00:00:00 EDT 1998
* 1998221
*/
}
}
import java.util.GregorianCalendar;
import java.util.Calendar;
Given a time in ms, this HowTo will output the long form "<w> days, <x> hours, <y> minutes and (z)
seconds" and the short form "<dd:>hh:mm:ss".
private TimeUtils() {
}
/**
* converts time (in milliseconds) to human-readable format
* "<w> days, <x> hours, <y> minutes and (z) seconds"
*/
public static String millisToLongDHMS(long duration) {
StringBuffer res = new StringBuffer();
long temp = 0;
if (duration >= ONE_SECOND) {
temp = duration / ONE_DAY;
if (temp > 0) {
duration -= temp * ONE_DAY;
res.append(temp).append(" day").append(temp > 1 ? "s" : "")
.append(duration >= ONE_MINUTE ? ", " : "");
}
/**
* converts time (in milliseconds) to human-readable format
* "<dd:>hh:mm:ss"
*/
public static String millisToShortDHMS(long duration) {
String res = "";
duration /= ONE_SECOND;
int seconds = (int) (duration % SECONDS);
duration /= SECONDS;
int minutes = (int) (duration % MINUTES);
duration /= MINUTES;
int hours = (int) (duration % HOURS);
int days = (int) (duration / HOURS);
if (days == 0) {
res = String.format("%02d:%02d:%02d", hours, minutes, seconds);
} else {
res = String.format("%dd%02d:%02d:%02d", days, hours, minutes, seconds);
}
return res;
}
System.out.println(millisToLongDHMS(42 * ONE_DAY));
/*
output :
0 second
5 seconds
1 day, 1 hour
1 day and 2 seconds
1 day, 1 hour, 2 minutes
4 days, 3 hours, 2 minutes and 1 second
5 days, 4 hours, 1 minute and 23 seconds
42 days
*/
System.out.println(millisToShortDHMS(123));
System.out.println(millisToShortDHMS((5 * ONE_SECOND) + 123));
System.out.println(millisToShortDHMS(ONE_DAY + ONE_HOUR));
System.out.println(millisToShortDHMS(ONE_DAY + 2 * ONE_SECOND));
System.out
.println(millisToShortDHMS(ONE_DAY + ONE_HOUR + (2 * ONE_MINUTE)));
System.out.println(millisToShortDHMS((4 * ONE_DAY) + (3 * ONE_HOUR)
+ (2 * ONE_MINUTE) + ONE_SECOND));
System.out.println(millisToShortDHMS((5 * ONE_DAY) + (4 * ONE_HOUR)
+ ONE_MINUTE + (23 * ONE_SECOND) + 123));
System.out.println(millisToShortDHMS(42 * ONE_DAY));
/*
output :
00:00:00
00:00:05
1d01:00:00
1d00:00:02
1d01:02:00
4d03:02:01
5d04:01:23
42d00:00:00
*/
}
}
Using java.util.concurrent.TimeUnit
import java.util.concurrent.TimeUnit;
...
/**
* converts time (in milliseconds) to human-readable format
* "<dd:>hh:mm:ss"
*/
public static String millisToShortDHMS(long duration) {
String res = "";
long days = TimeUnit.MILLISECONDS.toDays(duration);
long hours = TimeUnit.MILLISECONDS.toHours(duration)
- TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(duration));
long minutes = TimeUnit.MILLISECONDS.toMinutes(duration)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(duration));
long seconds = TimeUnit.MILLISECONDS.toSeconds(duration)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration));
if (days == 0) {
res = String.format("%02d:%02d:%02d", hours, minutes, seconds);
}
else {
res = String.format("%dd%02d:%02d:%02d", days, hours, minutes, seconds);
}
return res;
}
We connect to a publicly accessible time server on the internet and parse the result.
NOTE : All users should ensure that their software NEVER queries a server more frequently than once every
4 seconds. Systems that exceed this rate will be refused service. In extreme cases, systems that exceed this
limit may be considered as attempting a denial-of-service attack.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
try {
conn = new Socket(ATOMICTIME_SERVER, ATOMICTIME_PORT);
in = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
String atomicTime;
while (true) {
if ( (atomicTime = in.readLine()).indexOf("*") > -1) {
break;
}
}
System.out.println("DEBUG 1 : " + atomicTime);
String[] fields = atomicTime.split(" ");
GregorianCalendar calendar = new GregorianCalendar();
// deals with the timezone and the daylight-saving-time (you may need to adjust this)
// here i'm using "EST" for Eastern Standart Time (to support Daylight Saving Time)
TimeZone tz = TimeZone.getTimeZone("EST"); // or .getDefault()
int gmt = (tz.getRawOffset() + tz.getDSTSavings()) / 3600000;
System.out.println("DEBUG 2 : " + gmt);
/*
ref : http://www.bldrdoc.gov/doc-tour/atomic_clock.html
| | | | | | | | |
It's not possible to set your local computer clock in pure Java.
You need to use an external utility provided by the OS or call a JNI routine, see this HowTo.
This HowTo computes a date interval based on the current date or given reference date. The returned interval
can be the previous week ou the previous month relative to the given reference date.
import java.text.*;
import java.util.*;
private DateUtils() { }
if (type == IntervalType.Month) {
// first date of the month
startDate.set(Calendar.DATE, 1);
// previous month
startDate.add(Calendar.MONTH, -1);
}
catch (Exception e) {
e.printStackTrace();
}
}
/*
output :
** previous month (relative today)
2008-06-01
2008-06-30
** previous week (relative today)
2008-06-30
2008-07-06
** previous month (relative jan 1, 2007)
2006-12-01
2006-12-31
** previous week (relative jan 1, 2007)
2006-12-25
2006-12-31
*/
}
import java.util.Calendar;
import java.text.SimpleDateFormat;
private 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, String start, String end) {
return ((target.compareTo(start) >= 0)
&& (target.compareTo(end) <= 0));
}
/**
* @param start interval start
* @param end interval end
* @return true true if the current hour is between
*/
public static boolean isNowInInterval(String start, String end) {
return DateUtils.isHourInInterval
(DateUtils.getCurrentHour(), start, end);
}
// TEST
public static void main (String[] args) {
String now = DateUtils.getCurrentHour();
String start = "14:00";
String end = "14:26";
System. out.println(now + " between " + start + "-" + end + "?");
System. out.println(DateUtils.isHourInInterval(now,start,end));
/*
* output example :
* 21:01 between 14:00-14:26?
* false
*
*/
}
}
SYSTEMTIME st;
GetLocalTime(&st);
st.wHour = hour;
st.wMinute = minutes;
SetLocalTime(&st);
}
class JavaHowTo {
public native void setSystemTime( short hour, short minutes);
static {
System.loadLibrary("javahowto");
}
}
// this example will set the system at 10h21 using the Windows API
// SetLocalTime.
Since the granulaty of a PC can be as high as 55ms (down to 10ms), you can't use the System time to generate
a unique ID because of the risk of getting duplicated IDs. This can be solved by using the following technique
to make sure that the number returned is unique (in a single JVM).
import java.text.DateFormatSymbols;
import java.util.Locale;
System.out.println(DateUtils.getMonthName(1));
System.out.println(DateUtils.getMonthName(1, new Locale("it")));
System.out.println
(DateUtils.getDayName(java.util.Calendar.SUNDAY, Locale.getDefault()));
/*
* output :
* january
* gennaio
* sunday
*/
}
}
import java.util.Calendar;
import java.util.GregorianCalendar;
// using GregorianCalendar
public static boolean isLeap0(int year) {
GregorianCalendar cal = new GregorianCalendar();
cal.set(Calendar.YEAR, year);
return cal.isLeapYear(cal.get(Calendar.YEAR));
}
// using a Calendar
public static boolean isLeap1(int year) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
return cal.getActualMaximum(Calendar.DAY_OF_YEAR) > 365;
}
NOTE: JDK1.5 or better provides a simpler way to achieve this, see this HowTo.
JDK up to 1.4
Start the JVM with the "-D" switch to pass properties to the application and read them with the
System.getProperty() method.
then in myClass
If you don't know in advance, the name of the variable to be passed to the JVM, then there is no 100% Java
way to retrieve them.
One approach (not the easiest one), is to use a JNI call to fetch the variables, see this HowTo.
A more low-tech way, 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.
import java.io.*;
import java.util.*;
Environment 141
Real's HowTo PDF version
}
else if ( (OS.indexOf("nt") > -1)
|| (OS.indexOf("windows 2000") > -1 )
|| (OS.indexOf("windows xp") > -1) ) {
// thanks to JuanFran for the xp fix!
p = r.exec( "cmd.exe /c set" );
}
else {
// our last hope, we assume Unix (thanks to H. Ware for the fix)
p = r.exec( "env" );
}
BufferedReader br = new BufferedReader
( new InputStreamReader( p.getInputStream() ) );
String line;
while( (line = br.readLine()) != null ) {
int idx = line.indexOf( '=' );
String key = line.substring( 0, idx );
String value = line.substring( idx+1 );
envVars.setProperty( key, value );
// System.out.println( key + " = " + value );
}
return envVars;
}
I found that, on Windows 2003 server, the property value for "os.name" is actually "windows 2003." So either
that has to be added to the bunch of tests or just relax the comparison strings a bit:
I started with "windows 200" but thought "what the hell" and made it "windows 20" to lengthen its longivity.
You could push it further and use "windows 2," I suppose. The only thing to watch out for is to not overlap
with "windows 9."
On Windows, pre-JDK 1.2 JVM has trouble reading the Output stream directly from the SET command, it
never returns. Here 2 ways to bypass this behaviour.
First, instead of calling directly the SET command, we use a BAT file, after the SET command we print a
known string. Then, in Java, when we read this known string, we exit from loop.
[env.bat]
@set
@echo **end
[java]
...
if (OS.indexOf("windows") > -1) {
p = r.exec( "env.bat" );
}
...
The other solution is to send the result of the SET command to file and then read the file from Java.
...
if (OS.indexOf("windows 9") > -1) {
p = r.exec( "command.com /c set > envvar.txt" );
}
else if ( (OS.indexOf("nt") > -1)
|| (OS.indexOf("windows 2000") > -1
|| (OS.indexOf("windows xp") > -1) ) {
// thanks to JuanFran for the xp fix!
p = r.exec( "cmd.exe /c set > envvar.txt" );
}
...
Thanks to JP Daviau
// UNIX
public Properties getEnvironment() throws java.io.IOException {
Properties env = new Properties();
env.load(Runtime.getRuntime().exec("env").getInputStream());
return env;
}
Java's System properties contains some useful informations about the environment, for example, the TEMP
and PATH environment variables (on Windows).
public class ShowSome {
public static void main(String args[]){
System.out.println("TEMP : "
+ System.getProperty("java.io.tmpdir"));
System.out.println("PATH : "
+ System.getProperty("java.library.path"));
System.out.println("CLASSPATH : "
+ System.getProperty("java.class.path"));
System.out.println("SYSTEM DIR : " +
System.getProperty("user.home")); // ex. c:\windows on Win9x
System.out.println("CURRENT DIR: "
+ System.getProperty("user.dir"));
}
}
Here some tips from H. Ware about the PATH on different OS.
PATH is not quite the same as library path. In unixes, they are completely different---the libraries typically
have their own directories.
System.out.println("LIBPATH: {" +
System.getProperty("java.library.path")+"}");
gives
on my linux workstation. (java added all those except /lib and /usr/lib). But these two lines aren't the same on
window either:
Java is prepending itself! That confused me--- and broke my exec from ant.
Belorussian translation
JDK1.5
System.getenv() is back!
import java.util.*;
For some odd reasons, the getenv() method was removed from the JDK. Rumors is that a mechanism to
retrieve an environment will be back in JDK1.5 (see this HowTo). But for now, you can use -D switch to
retrieve named environment variable and pass them to the JVM (see this HowTo) or use this JNI routine :
NOTE : This is fine if the environment variable contains only regular 7-bit ASCII characters.
JAVAHOME=c:\windev\jdk1.1.3
JAVAC= $(JAVAHOME)\bin\javac
PATH=$(JAVAHOME)\bin;$(PATH)
CLASSPATH=.;$(JAVAHOME)\lib\classes.zip;$(JSDKHOME)\lib\classes.zip
DEST=.
DOC=.
JAVA=$(JAVAHOME)\bin\java
JAVACFLAGS=-deprecation
.java.class:
$(JAVAC) -classpath $(CLASSPATH) $(JAVACFLAGS) $<
CLASSFILES = GetImage.class \
myCanvas.class
SOURCEFILES = GetImage.java \
myCanvas.java
Name: myCanvas.class
Java-Bean: True
<<
# end ---- JAR support ----------
doc : $(CLASSFILES)
install :
copy $CLASSESFILE $(DEST)
clean:
del $(CLASSFILES)
This HowTo is obsolete. Check this one instead : Detect browser type from an Applet
One way is to instanciate a known browser-specific method and catch the Exception if not found
import java.applet.*;
For an application, by looking at the string representation of the getDefaultToolkit() method, we detect the
JVM type
if (theBrowser.equals("APPLICATION") {
if (toolkit.startsWith( "sun.awt.windows.WToolkit"))
theJVM = "JAVA";
else if (toolkit.startsWith( "com.ms.awt.WToolkit"))
theJVM = "JVIEW";
}
For example, our MyApplet.class exists in three versions. One is using Microsoft-specific classes, the other is
a JDK1.1 applet and finally a version for JDK102-only browser. The idea is to put all the required classes in
an ARCHIVE file. By using a javascript entities, we decide which archive to use. During layout time, the
javascript entity is remplaced by the right archive name.
<HTML></HTML><HEAD>
<SCRIPT>
function isBrowser(b,v) {
browserOk = false;
versionOk = false;
browserOk = (navigator.appName.indexOf(b) != -1);
versionOk = (v <= parseInt(navigator.appVersion));
return browserOk && versionOk;
}
archiveToBeUsed = "java102.jar";
if (isBrowser("Microsoft", 4)) {
archiveToBeUsed = "ie4.jar";
}
else {
if isBrowser("Netscape", 4) {
archiveToBeUsed = "n4.jar";
}
}
</SCRIPT></HEAD><BODY>
<APPLET CODE ="MyApplet.class"
HEIGHT=100
WIDTH=400
ARCHIVE=&{archiveToBeUsed}; >
</APPLET>
</BODY></HTML>
NOTE: You may need to use the document.write() method to generate the right APPLET tag instead of a the Javascript entity to be compatible with Netscape
and IE.
The "magic number" is represented by the first few bytes of a given file. It is used to identified the file type.
For Java classes, the magic number is 0xCAFEBABE (you can verify this by viewing a class file with
hexadecimal editor or the DOS Debug utility). This is used by the browser JVM as a quick check of whether
the called file is really a Java class.
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.
Ant
We insert into the code a special tag to delimit code that need to be stripped by the Ant script. Let's say we use
//@STARTDEBUG@// and //@ENDDEBUG@//.
package com.rgagnon.howto;
import javax.swing.JFrame;
If you execute this code, the JFrame title will have the word "DEBUG" appended to it.
<project default="buildme">
<target name="compileprod">
<copy todir="../out" includeEmptyDirs="false">
<filterchain>
<tokenfilter>
<replacestring from="//@STARTDEBUG@//" to="/*" />
<replacestring from="//@ENDDEBUG@//" to="*/" />
</tokenfilter>
</filterchain>
<fileset dir=".">
<include name="**/*.java" />
</fileset>
</copy>
<target name="compiledebug">
<javac srcdir="." />
</target>
After running this script, the source (in the ..\out directory)
package com.rgagnon.howto;
import javax.swing.JFrame;
See this HowTo. This technique relies on the compiler optimization which remove code in the bytecode
generated because it will never be executed.
In Netscape
In application
NOTE: This can be useful if you want to trim a JAR to include only classes actually used.
If your program allocates a lot of memory, you may need to increase this value to give more room to the
garbage collector.
When starting the JVM, two parameters can be adjusted to suit your memory needs :
The default value for the minimum is 2Mb, for the maximum it's 64Mb.
The javadoc utility uses the regular Java mechanism to internationalize its output. The tools.jar in the lib
directory contains the resource bundle standard.properties used by Javadoc to generated the labels. To add a
new language, you need to create the appropriate resource bundle, in our case for french, we need a file called
standard_fr.properties.
Extract from tools.jar, the standard.properties files (keep the directory structure). Copy it under the name
standard_fr.properties. Translate it (or you can download my "incomplete" version here).
[standard.properties (extract)]
doclet.Window_Split_Index={0}\: {1}-Index
doclet.Packages=Packages
doclet.SerialData=Serial Data\:
doclet.Since=Since\:
doclet.Warn_inline_taglet=Inline tag {0} should only be used with a {1}.
doclet.ClassUse_Subinterface=Subinterfaces of {0} in {1}
doclet.Frame_Version=Frame version
doclet.Generated_Docs_Untitled=Generated Documentation (Untitled)
[standard_fr.properties (extract)]
doclet.Window_Split_Index={0}\: {1}-Index
doclet.Packages=Paquetages
doclet.SerialData=Donn\u00E9e s\u00E9rialis\u00E9e\:
doclet.Since=Depuis\:
doclet.Warn_inline_taglet=Inline tag {0} should only be used with a {1}.
doclet.ClassUse_Subinterface=Sous-interfaces de {0} dans {1}
doclet.Frame_Version=Version avec cadres
doclet.Generated_Docs_Untitled=Documentation g\u00E9n\u00E9r\u00E9e
Once everything translated, put your standard_fr.properties into the tools.jar making sure that the file is
located in the right package (along standard.properties in com.sun.tools.doclets.standard.resources).
Using Ant,
<javadoc
locale="fr"
sourcefiles="c:/client/Client.java"
destdir="javadoc/Client"
author="true"
version="true"
use="true"
private="true"
windowtitle="Client">
<doctitle><![CDATA[<h1>Client</h1>]]></doctitle>
<bottom><![CDATA[<i>Copyright © 2003 Real's Howto.</i>]]></bottom>
</javadoc>
On Windows, if you have a "file not found" message, it's because the JVM can't be found through the
PATH. Do it again but with the complete path (if the path contains spaces, make sure to use quotes!) :
Note the switch "-source 1.5", if you don't specify it you won't be able to access the new features (like
System.out.printf()).
• Run it
>"C:\Program Files\Java\j2sdk1.5.0\bin\java" Test15
Local time: 15:26:04
The first 4 bytes are a magic number, 0xCAFEBABe, to identify a valid class file then the next 2 bytes
identify the class format version (major and minor).
import java.io.*;
magic
The magic item supplies the magic number identifying the class file format; it has the value 0xCAFEBABE.
minor_version, major_version
The values of the minor_version and major_version items are the minor and major version numbers of this
class file.Together, a major and a minor version number determine the version of the class file format. If a
class file has major version number M and minor version number m, we denote the version of its class file
format as M.m. Thus, class file format versions may be ordered lexicographically, for example, 1.5 < 2.0 <
2.1.
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.0 v Mj.m. 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.
The RuntimeMXBean defines several convenient methods for accessing system properties about the Java
virtual machine.
[J2SE 1.5]
import java.util.Date;
import java.lang.management.RuntimeMXBean;
import java.lang.management.ManagementFactory;
class JMXTest {
public static void main(String args[]) {
JMXTest x = new JMXTest();
x.doit();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
System.getProperty("java.vm.name")
.toLowerCase().indexOf("64") >= 0;
}
// probably 32bit
return false;
}
}
you get
The default JVM with a JIT (Just-In-Time compiler) for a "client" mode is used. The other available mode is
"server".
These two systems are different binaries. They are essentially two different compilers (JITs)interfacing to the
same runtime system. The client system is optimal for applications which need fast startup times or small
footprints, the server system is optimal for applications where the overall performance is most important. In
general the client system is better suited for interactive applications such as GUIs. Some of the other
differences include the compilation policy,heap defaults, and inlining policy.
Client and server systems are both downloaded with the 32-bit Solaris and Linux downloads. For 32-bit
Windows, if you download the JRE, you get only the client, you'll need to download the SDK to get both
systems.
For 64-bit, only the server system is included. On Solaris, the 64-bit JRE is an overlay on top of the 32-bit
distribution. However, on Linux and Windows, it's a completely separate distribution. The default setting is
defined the file jvm.cfg.
A content like
-client KNOWN
-server KNOWN
-server KNOWN
-client KNOWN
If the JRE is properly installed on Windows, informations about each version are stored in the registry. The
installation process installs a special java.exe in the system PATH. So you don't need to alter you PATH
because this special java.exe will find the current JRE. From a command line, type java -version to display the
current jre version installed.
With release 1.6, it's now possible to select a different JRE installation than the last one without any registry
modification.
It's probably the 1.6 JRE that will be used since it's the last installed.
If the bytecode is incompatible with the given JRE then .. it won't work, of course.
You can always give the complete path to use a specific installation. Launching the JVM this way does not
use the registry setting at all.
This solution use the RuntimeMXBean. The name of the bean contains the pid (ex. 12345@localhost).
Warning : The returned name string can be any arbitrary string and a Java virtual machine implementation can
choose to embed platform-specific useful information in the returned name string.
private SystemUtils() {}
javax.swing.JOptionPane.showConfirmDialog((java.awt.Component)
null, msg, "SystemUtils", javax.swing.JOptionPane.DEFAULT_OPTION);
The result is
class JavaHowTo {
public native long getCurrentProcessId();
static {
System.loadLibrary("jni2");
}
}
#include "stdafx.h"
#include <process.h>
#include "JavaHowTo.h"
// return GetCurrentProcessId();
return getpid();
}
Set default value for Java property or JVM option (system wide)
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java-set-java-properties-system-wide.html
If you find yourself using the same options over and over before laucing a java process, you can set up a
special environment variable to contain your default options and the JVM will pick up the the values.
If the Java process is launch via java.exe then the environment variable is called _JAVA_OPTIONS,
e.g. In Windows:
In Linux:
ref : http://java.sun.com/j2se/1.5.0/docs/guide/2d/flags.html
If the Java process is launch via javaw.exe (Applet) then the environment variable is called
_JPI_VM_OPTIONS.
For example :
_JPI_VM_OPTIONS = -Dsome.property=true
For a Java Web Start process (javaws.exe), the environment variable is called JAVAWS_VM_ARGS.
For example :
JAVAWS_VM_ARGS = -Dsome.property=true
ref : http://docs.oracle.com/javase/7/docs/webnotes/tsg/TSG-Desktop/html/plugin.html#gcexdd
If you want to detect if your program is running in debug mode (ex. Eclipse).
User level
The deployment.properties file is used for storing and retrieving deployment configuration properties
shown in the Java Control Panel. The properties are also used for customizing runtime behavior for both Java
Plug-in and Java Web Start.
Set default value for Java property or JVM option (system wide) 163
Real's HowTo PDF version
On the Windows, <User Application Data Folder> is typically C:\Users\<your username>\AppData (or
%APPDATA%) which is hidden by default.
#deployment.properties https://gist.githubusercontent.com/MyITGuy/9628895/raw/3727348918e036ba
# Security Tab
# Enable Java content in the browser
deployment.webjava.enabled=true
deployment.webjava.enabled.locked
# Security Level
deployment.security.level=MEDIUM
deployment.security.level.locked
# Advanced Tab
# Debugging\Enable tracing
deployment.trace=false
deployment.trace.locked
# Debugging\Enable logging
deployment.log=false
deployment.log.locked
# Debugging\Show applet lifecycle exceptions
deployment.javapi.lifecycle.exception=false
deployment.javapi.lifecycle.exception.locked
# Java console
deployment.console.startup.mode.locked
deployment.console.startup.mode=HIDE
# Default Java for browsers\Microsoft Internet Explorer
deployment.browser.vm.iexplorer=true
deployment.browser.vm.iexplorer.locked
# Default Java for browsers\Mozilla family
deployment.browser.vm.mozilla.locked
deployment.browser.vm.mozilla=false
# Java Plug-in\Enable the next-generation Java Plug-in (requires browser restart)
# This must be done by executing one of the following commands as an administrator:
# [Disable] - {JREInstallPath}\bin\ssvagent.exe -high -jpisetup -old
# [Enable] - {JREInstallPath}\bin\ssvagent.exe -high -jpisetup -new
# Shortcut Creation
deployment.javaws.shortcut=ASK_IF_HINTED
deployment.javaws.shortcut.locked
# JNLP File/MIME Association
deployment.javaws.associations=ASK_USER
deployment.javaws.associations.locked
# Application Installation
deployment.javaws.install=IF_HINT
deployment.javaws.install.locked
#JRE Auto-Download
deployment.javaws.autodownload=NEVER
deployment.javaws.autodownload.locked
# Security Execution Environment\Enable granting elevated access to signed apps
deployment.security.SSLv2Hello=false
deployment.security.SSLv2Hello.locked
# Advanced Security Settings\Use SSL 3.0
deployment.security.SSLv3=true
deployment.security.SSLv3.locked
# Advanced Security Settings\Use TLS 1.0
deployment.security.TLSv1=true
deployment.security.TLSv1.locked
# Advanced Security Settings\Use TLS 1.1
deployment.security.TLSv1.1=false
deployment.security.TLSv1.1.locked
# Advanced Security Settings\Use TLS 1.2
deployment.security.TLSv1.2=false
deployment.security.TLSv1.2.locked
# Miscellaneous\Place Java icon in system tray
# Miscellaneous\Java Quick Starter
deployment.system.tray.icon=false
deployment.system.tray.icon.locked
# Screen: Your Java version is insecure. or Your Java version is out of date.
deployment.expiration.check.enabled=false
deployment.expiration.check.enabled.locked
#
deployment.capture.mime.types=true
deployment.capture.mime.types.locked
deployment.security.expired.warning=false
deployment.security.expired.warning.locked
deployment.user.security.exception.sites=C:\\WINDOWS\\Sun\\Java\\Deployment\\exception.sites
deployment.user.security.exception.sites.locked
# Java 7 Update 10
deployment.expiration.decision.10.10.2.locked
deployment.expiration.decision.10.10.2=later
deployment.expiration.decision.suppression.10.10.2.locked
deployment.expiration.decision.suppression.10.10.2=true
deployment.expiration.decision.timestamp.10.10.2.locked
deployment.expiration.decision.timestamp.10.10.2=2/28/2014 12\:1\:31
Example of a deployment.properties
#deployment.properties
deployment.webjava.enabled=true
deployment.security.level=MEDIUM
deployment.security.level.locked
deployment.user.security.exception.sites=c\:/Windows/Sun/Java/Deployment/exception.sites
The exception.sites file is a one URL per line list of sites that you want in the Exception Site List field
found in the Java Control Panel. Nothing else goes in this file.
System level
The deployment.config file is used for specifying the system-level deployment.properties in the
infrastructure. By default no deployment.config file exists, so no system-wide deployment.properties file
exists.
deployment.system.config=file\://ourserver.local/deploy/Sun/Java/Deployment/deployment.properti
deployment.system.config.mandatory=true
This example points to a deployment.properties file on a DFS path //ourserver.local/deploy/. Since the
property deployment.system.config.mandatory=true then if the deployment.properties file is not found, then
nothing is allowed to run.
The previous How-to was using a Microsoft utility to enable access to Java objects from a COM-aware
development tool. Sun provides a similar tool but you must package everything in a jar file and use the Beans
technology. The tool is called packager, written in Java, you execute it from the sun.beans.ole package. The
Java Plug-in 1.2 and the JDK1.2 must be installed on the system (for download, see Java Sun Web site).
package JavaCom;
public class JavaBeanSays {
private String _hello = "Hello World!";
The next step is to build a manifest file to identify the bean in the jar. Here it is (manifest.txt):
Name: JavaCom/JavaBeanSays
Java-Bean: true
NOTE: If no manifest is present all classes in the jar are treated as beans.
The JavaBeanSays class is in the directory JavaCom, the manifest.txt is the directory under it. From the
directory under (the one containing manifest.txt), we built the jar with :
The next step is to run the packager. You run it from the JDK installation directory. If the JDK is installed in
c:\dev\java\jdk1.2.1\ for example , you go there. And you start the packager with
A wizard is started, you follow the 5 steps to create the "JavaBeans bridge for ActiveX" for the JavabeanSays
component.
The first step is to specify where is located the JavaCom.jar file. When selected, the wizard should list the
JavaCom.JavaBeanSays bean, press Next. The "ActiveX" name under which the beans will be seen is shown,
press Next (in VbScript, the beans suffix must be added to this name).
An output directory is needed, be careful because this directory name will be hard-coded in the generated files
(REG and TLB), you need to specify a valid directory name. The packager assume that a subdirectory bin is
present with the file beans.ocx in it. You can create it and then copy beans.ocx from the JRE\bin into it or edit
Wrap a Java bean in a COM object (using Sun ActiveX bridge) 168
Real's HowTo PDF version
the REG file to specify the original JRE\bin and update the registry with the good location.
NOTE: There is a command-line interface available in the packager if you want to bypass the wizard.
strFromJava = objJava.getHello
MsgBox strFromJava, _
0, _
"JAVA BEAN OUTPUT"
objJava.setHello("Bonjour le monde!")
strFromJava = objJava.getHello
MsgBox strFromJava, _
0, _
"JAVA BEAN OUTPUT"
NOTE: Check the JAVA PLUG-IN SCRIPTING documentation (jdk1.2) or (jsdk1.4). document for more infos.
We launch the REG utility and capture the output. The performance is poor so it's a good idea to cache
frequently used values.
Note : The Microsoft Windows NT Server 4.0 Resource Kit contains REG.EXE. In Windows 2000 and later REG.EXE is a native command. The REG utility
can be used to write values in the registry (reg add /? for more infos).
In this example,we query the registry to extract the personal folder path ("My Documents") and the processor
ID and its name.
import java.io.*;
"\"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\"
+ "Explorer\\Shell Folders\" /v Personal";
private static final String CPU_SPEED_CMD = REGQUERY_UTIL +
"\"HKLM\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\""
+ " /v ~MHz";
private static final String CPU_NAME_CMD = REGQUERY_UTIL +
"\"HKLM\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\""
+ " /v ProcessorNameString";
reader.start();
process.waitFor();
reader.join();
if (p == -1)
return null;
reader.start();
process.waitFor();
reader.join();
if (p == -1)
return null;
reader.start();
process.waitFor();
reader.join();
if (p == -1)
return null;
StreamReader(InputStream is) {
this.is = is;
sw = new StringWriter();
}
String getResult() {
return sw.toString();
}
}
For a better way to access the Registry, see Read/Write Windows Registry using JNA.
The JDK contains the required code (java.util.prefs.WindowsPreferences) to access the Windows registry but
to preserve the "purity" of Java, the code is declared as private so it's not visible. The trick is to use reflection
to access private methods defined in the WindowsPreference class.
Remember : This code is a hack and may break anytime. A better alternative is to use JNA.
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
import java.util.prefs.Preferences;
static {
try {
regOpenKey = userClass.getDeclaredMethod("WindowsRegOpenKey",
new Class[] { int.class, byte[].class, int.class });
regOpenKey.setAccessible(true);
regCloseKey = userClass.getDeclaredMethod("WindowsRegCloseKey",
new Class[] { int.class });
regCloseKey.setAccessible(true);
regQueryValueEx = userClass.getDeclaredMethod("WindowsRegQueryValueEx",
new Class[] { int.class, byte[].class });
regQueryValueEx.setAccessible(true);
regEnumValue = userClass.getDeclaredMethod("WindowsRegEnumValue",
new Class[] { int.class, int.class, int.class });
regEnumValue.setAccessible(true);
regQueryInfoKey = userClass.getDeclaredMethod("WindowsRegQueryInfoKey1",
new Class[] { int.class });
regQueryInfoKey.setAccessible(true);
regEnumKeyEx = userClass.getDeclaredMethod(
"WindowsRegEnumKeyEx", new Class[] { int.class, int.class,
int.class });
regEnumKeyEx.setAccessible(true);
regCreateKeyEx = userClass.getDeclaredMethod(
"WindowsRegCreateKeyEx", new Class[] { int.class,
byte[].class });
regCreateKeyEx.setAccessible(true);
regSetValueEx = userClass.getDeclaredMethod(
"WindowsRegSetValueEx", new Class[] { int.class,
byte[].class, byte[].class });
regSetValueEx.setAccessible(true);
regDeleteValue = userClass.getDeclaredMethod(
"WindowsRegDeleteValue", new Class[] { int.class,
byte[].class });
regDeleteValue.setAccessible(true);
regDeleteKey = userClass.getDeclaredMethod(
"WindowsRegDeleteKey", new Class[] { int.class,
byte[].class });
regDeleteKey.setAccessible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
private WinRegistry() { }
/**
* Read a value from key and value name
* @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
* @param key
* @param valueName
* @return the value
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static String readString(int hkey, String key, String valueName)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
if (hkey == HKEY_LOCAL_MACHINE) {
return readString(systemRoot, hkey, key, valueName);
}
else if (hkey == HKEY_CURRENT_USER) {
return readString(userRoot, hkey, key, valueName);
}
else {
throw new IllegalArgumentException("hkey=" + hkey);
}
}
/**
* Read value(s) and value name(s) form given key
* @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
* @param key
* @return the value name(s) plus the value(s)
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static Map<String, String> readStringValues(int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
if (hkey == HKEY_LOCAL_MACHINE) {
return readStringValues(systemRoot, hkey, key);
}
else if (hkey == HKEY_CURRENT_USER) {
return readStringValues(userRoot, hkey, key);
}
else {
throw new IllegalArgumentException("hkey=" + hkey);
}
}
/**
* Read the value name(s) from a given key
* @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
* @param key
* @return the value name(s)
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static List<String> readStringSubKeys(int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
if (hkey == HKEY_LOCAL_MACHINE) {
return readStringSubKeys(systemRoot, hkey, key);
}
else if (hkey == HKEY_CURRENT_USER) {
return readStringSubKeys(userRoot, hkey, key);
}
else {
throw new IllegalArgumentException("hkey=" + hkey);
}
}
/**
* Create a key
* @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
* @param key
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static void createKey(int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int [] ret;
if (hkey == HKEY_LOCAL_MACHINE) {
ret = createKey(systemRoot, hkey, key);
regCloseKey.invoke(systemRoot, new Object[] { new Integer(ret[0]) });
}
else if (hkey == HKEY_CURRENT_USER) {
ret = createKey(userRoot, hkey, key);
regCloseKey.invoke(userRoot, new Object[] { new Integer(ret[0]) });
}
else {
throw new IllegalArgumentException("hkey=" + hkey);
}
if (ret[1] != REG_SUCCESS) {
throw new IllegalArgumentException("rc=" + ret[1] + " key=" + key);
}
}
/**
* Write a value in a given key/value name
* @param hkey
* @param key
* @param valueName
* @param value
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static void writeStringValue
(int hkey, String key, String valueName, String value)
/**
* Delete a given key
* @param hkey
* @param key
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static void deleteKey(int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int rc = -1;
if (hkey == HKEY_LOCAL_MACHINE) {
rc = deleteKey(systemRoot, hkey, key);
}
else if (hkey == HKEY_CURRENT_USER) {
rc = deleteKey(userRoot, hkey, key);
}
if (rc != REG_SUCCESS) {
throw new IllegalArgumentException("rc=" + rc + " key=" + key);
}
}
/**
* delete a value from a given key/value name
* @param hkey
* @param key
* @param value
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static void deleteValue(int hkey, String key, String value)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int rc = -1;
if (hkey == HKEY_LOCAL_MACHINE) {
rc = deleteValue(systemRoot, hkey, key, value);
}
else if (hkey == HKEY_CURRENT_USER) {
rc = deleteValue(userRoot, hkey, key, value);
}
if (rc != REG_SUCCESS) {
throw new IllegalArgumentException("rc=" + rc + " key=" + key + " value=" + value);
}
}
// =====================
private static String readString(Preferences root, int hkey, String key, String value)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {
new Integer(hkey), toCstr(key), new Integer(KEY_READ) });
if (handles[1] != REG_SUCCESS) {
return null;
}
byte[] valb = (byte[]) regQueryValueEx.invoke(root, new Object[] {
new Integer(handles[0]), toCstr(value) });
regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });
return (valb != null ? new String(valb).trim() : null);
}
regSetValueEx.invoke(root,
new Object[] {
new Integer(handles[0]), toCstr(valueName), toCstr(value)
});
regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });
}
// utility
private static byte[] toCstr(String str) {
byte[] result = new byte[str.length() + 1];
How to use it :
package com.rgagnon.howto;
WinRegistry.HKEY_LOCAL_MACHINE,
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\AcroRd32.exe",
"");
System.out.println("Acrobat Reader Path = " + value);
/*
this code is broken under win7 64 :-( 20130112
WinRegistry.createKey(
WinRegistry.HKEY_CURRENT_USER, "SOFTWARE\\rgagnon.com");
WinRegistry.writeStringValue(
WinRegistry.HKEY_CURRENT_USER,
"SOFTWARE\\rgagnon.com",
"HowTo",
"java");
// WinRegistry.deleteValue(
// WinRegistry.HKEY_CURRENT_USER,
// "SOFTWARE\\rgagnon.com", "HowTo");
// WinRegistry.deleteKey(
// WinRegistry.HKEY_CURRENT_USER,
// "SOFTWARE\\rgagnon.com\\");
System.out.println("Done." );
}
}
The output :
Using regedit
Use regedit utility to query the Windows registry, the result is written into a file.
@echo off
::Find the current (most recent) Java version
start /w regedit /e reg1.txt "HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment"
type reg1.txt | find "CurrentVersion" > reg2.txt
if errorlevel 1 goto ERROR
pause
Output example :
C:\temp>findjava.cmd
Java Version = 1.6
Java home path (per registry) = C:\\applications\\dev\\jre6
Note :
The above script returns the default JVM if the PATH variable does not override it!
Oracle client installation is famous to force an outdated Java at the beginning of the PATH. This one-liner
displays the java.exe (if any) found in the PATH :
The java.exe in the system32 relies on the CurrentVersion registry setting to determine which registry key to
use to look up the location of the Java RE.
However, it's easy to do from a VBS. You execute the script from Java, wait for its completion and capture
the return code.
import java.io.File;
import java.io.FileWriter;
Using TASKLIST.EXE
The Microsoft TASKLIST.EXE is used to dump the list of the currently running processes. It is similar to
tasklist window but for the console.
From a Java program, we are launching TASKLIST.EXE and capture its output.
Note : TASKLIST.EXE is not included the HOME edition of XP. But you can download it from Web, for
example : http://www.computerhope.com/download/winxp.htm.
import java.io.*;
import java.util.*;
}
input.close();
}
catch (Exception err) {
err.printStackTrace();
}
return processes;
}
while (it.hasNext()) {
result += it.next() +",";
i++;
if (i==10) {
result += "\n";
i = 0;
}
}
msgBox("Running processes : " + result);
}
Thanks to M. Korbel
Using a VBS
Another technique to build the required VBScript on-the-fly, execute it and capture its output.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.*;
fw.write(vbs);
fw.close();
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
BufferedReader input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
processList.add(line);
}
input.close();
}
catch(Exception e){
e.printStackTrace();
}
return processList;
}
Iterator<String> it = processes.iterator();
int i = 0;
while (it.hasNext()) {
result += it.next() +",";
i++;
if (i==10) {
result += "\n";
i = 0;
}
}
msgBox("Running processes : " + result);
}
Based on this HowTo which list the currently running processes, we adapt it to check for a specific program
name.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
fw.write(vbs);
fw.close();
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
BufferedReader input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
String line;
line = input.readLine();
if (line != null) {
if (line.equals(process)) {
found = true;
}
}
input.close();
}
catch(Exception e){
e.printStackTrace();
}
return found;
}
WMIC is a powerful Windows utility. You can use to know if a particular process is running or not.
This example detects if a Tomcat instance (can be anything, ex: Apache or Excel) is running from a batch file.
@echo off
wmic process list brief | find /i "tomcat.exe"
set result=%ERRORLEVEL%
if "%result%"=="1" echo "not running"
if "%result%"=="0" echo "running"
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
try {
ProcessBuilder builder = new ProcessBuilder(command);
Process process = builder.start();
is = process.getInputStream();
The JDK itself does not use the windows registry to run.
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.
Finally, the JRE will only use the registry if it is run from the Windows system directory (ex .
C:/winnt/system32/java.exe). This would happen if the user just types "java" on the commandline in some
random directory, because the system directory is always in the user's path. In this situation, the java.exe will
locate the current Java installation by looking at the registry key
and then get the path of the JRE from the corresponding key
Beware that some software (eg. Oracle) installs themself at the beginning of the PATH definition, so it's their
Java installation that will be found first.
It will not use the registry, and it will be guaranteed to use jre1.5.0.
So for a regular Java SE program, it is safe to specify the complete path to the JRE to launch it.
But for the Applet/Plugin or WebStart-based programs, the registry is always used to determine the current
JRE.
This command file queries the registry to find out the path of the current JRE installation and then launch it to
display the version found .
@echo off
cls
setlocal ENABLEEXTENSIONS
set KEY_NAME="HKLM\SOFTWARE\JavaSoft\Java Runtime Environment"
set VALUE_NAME=CurrentVersion
::
:: get the current version
::
FOR /F "usebackq skip=2 tokens=3" %%A IN (`REG QUERY %KEY_NAME% /v %VALUE_NAME% 2^>nul`) DO (
set ValueValue=%%A
)
if defined ValueValue (
@echo the current Java runtime is %ValueValue%
) else (
@echo %KEY_NAME%\%VALUE_NAME% not found.
goto end
)
set JAVA_CURRENT="HKLM\SOFTWARE\JavaSoft\Java Runtime Environment\%ValueValue%"
set JAVA_HOME=JavaHome
::
:: get the javahome
::
FOR /F "usebackq skip=2 tokens=3*" %%A IN (`REG QUERY %JAVA_CURRENT% /v %JAVA_HOME% 2^>nul`) DO
set JAVA_PATH=%%A %%B
)
echo the path of the current Java JVM according to the registry is
echo %JAVA_PATH%
echo.
echo now if we try it :
"%JAVA_PATH%\bin\java.exe" -version
:end
[j.cmd XP version]
@echo off
cls
setlocal ENABLEEXTENSIONS
set KEY_NAME="HKLM\SOFTWARE\JavaSoft\Java Runtime Environment"
set VALUE_NAME=CurrentVersion
::
:: get the current version
::
FOR /F "usebackq skip=4 tokens=3" %%A IN (`REG QUERY %KEY_NAME% /v %VALUE_NAME% 2^>nul`) DO (
set ValueValue=%%A
)
if defined ValueValue (
::
:: get the javahome
::
FOR /F "usebackq skip=4 tokens=3,4" %%A IN (`REG QUERY %JAVA_CURRENT% /v %JAVA_HOME% 2^>nul`) D
set JAVA_PATH=%%A %%B
)
echo the path of the current Java JVM according to the registry is
echo %JAVA_PATH%
echo.
echo now if we try it :
"%JAVA_PATH%\bin\java.exe" -version
:end
Output :
>j.cmd
the current Java runtime is 1.6
the path of the current Java JVM according to the registry is
C:\Program Files\Java\jre1.6.0_06
now if we try it :
java version "1.6.0_06"
Java(TM) SE Runtime Environment (build 1.6.0_06-b02)
Java HotSpot(TM) Client VM (build 10.0-b22, mixed mode, sharing)
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, see this HowTo.
import javax.swing.JFileChooser;
javax.swing.filechooser.FileSystemView;
import java.io.*;
private WindowsUtils() {}
reader.start();
process.waitFor();
reader.join();
if (p == -1)
return null;
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Desktop directory : "
+ getCurrentUserDesktopPath());
StreamReader(InputStream is) {
this.is = is;
sw = new StringWriter();
}
String getResult() {
return sw.toString();
}
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
private VBSUtils() { }
fw.write(vbs);
fw.close();
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
BufferedReader input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
result = input.readLine();
input.close();
}
catch(Exception e){
e.printStackTrace();
}
return result;
}
See also :
Get Windows Desktop path using the registry
Get Windows "My Documents" path using FileSystemView.getDefaultDirectory()
import java.io.*;
private WindowsUtils() { }
// see note
private static final String WINDOWS_DESKTOP = "Desktop";
/**
* the current user desktop path
* @return the current user desktop path
*/
public static String getWindowsCurrentUserDesktopPath() {
return System.getenv("userprofile") + "/" + WINDOWS_DESKTOP ;
}
/**
* Create an Internet shortcut on User's Desktop no icon specified
/**
* Create an Internet shortcut on User's Desktop, icon specified
* @param name name of the shortcut
* @param target URL
* @param icon URL (ex. http://www.server.com/favicon.ico)
* @throws IOException
*/
public static void createInternetShortcutOnDesktop
(String name, String target, String icon)
throws IOException
{
String path = getWindowsCurrentUserDesktopPath() + "/"+ name + ".URL";
createInternetShortcut(name, path, target, icon);
}
/**
* Create an Internet shortcut
* @param name name of the shortcut
* @param where location of the shortcut
* @param target URL
* @param icon URL (ex. http://www.server.com/favicon.ico)
* @throws IOException
*/
public static void createInternetShortcut
(String name, String where, String target, String icon)
throws IOException
{
FileWriter fw = new FileWriter(where);
fw.write("[InternetShortcut]\n");
fw.write("URL=" + target + "\n");
if (!icon.equals("")) {
fw.write("IconFile=" + icon + "\n");
}
fw.flush();
fw.close();
}
/**
* @param args
*/
public static void main(String[] args) throws IOException {
WindowsUtils.createInternetShortcutOnDesktop
("GOOGLE", "http://www.google.com");
}
}
NOTE:
Prior Vista, the desktop path for a localized Windows can be different. With an english version, it's Desktop
while for a french version, it's called Bureau.
The only way to get the right name is to ask the Registry, see this HowTo.
[Windows only]
To detect if an application is running in a Remote Desktop session, you can call the Windows API
GetSystemMetrics. The GetSystemMetrics() function will return a non-zero value with a
SM_REMOTESESSION parameter value if the application is associated with a client terminal session.
In Java, you need to use JNI (Java Native Interface) to call this Windows native API. Native Call is an Open
Source project which provide an easy way to that.
http://johannburkard.de/software/nativecall/
All you need is 2 jars (nativecall-0,4,1.jar and nativeloader-200505172341.jar) plus 1 DLL (NativeCall.dll) in
your classpath.
When running from Eclipse, the DLL should be in the bin directory of your application.
import java.io.IOException;
import com.eaio.nativecall.IntCall;
import com.eaio.nativecall.NativeCall;
private WindowsUtils() {}
An easy way is to check the Windows environment variable sessionname. The value of this environment
variable will be 'Console' for a normal, local session. For an Remote Desktop session it will contain the phrase
'RDP'.
Note that environment varialbe values are read at the JVM startup. So if the JVM process was started by a
console session, but then accessed by an RDP session, further calls to System.getenv("sessionname") still
return 'Console'
The easiest way is to query the environment variable SESSIONNAME. The value starts with ICA... in a Citrix
session, RDP if in remote desktop session or Console if directly on a workstation.
Since JDK1.4, it is possible to create a taglet to be used with javadoc to customized the generated
documentation.
This example implements a new javadoc tag to document which tables a class is dealing with. If a method
interact with 2 tables, employee and address, then the javadoc tag
/**
*@table employee:firstname,lastname;address:city,country
* @return value
*/
public String newMethod() {
return "yo";
}
will be documented as
newMethod
Returns:
value
Table(s):
employee address
firstname city
lastname country
/*
* Table.java
*/
package com.rgagnon.taglet;
import com.sun.tools.doclets.Taglet;
import com.sun.javadoc.*;
import java.util.Map;
/**
* This is a taglet to document tables and fields used by a classes
* example : @table employee:lastname,firstname;address:city,country
*
* @author Réal Gagnon
*/
public class Table implements Taglet{
/**
* Return the name of this custom tag.
*/
public String getName() {
return NAME;
}
/**
* Will return true since <code>@todo</code>
* can be used in field documentation.
* @return true since <code>@todo</code>
* can be used in field documentation and false
* otherwise.
*/
public boolean inField() {
return false;
}
/**
* Will return true since <code>@todo</code>
* can be used in constructor documentation.
* @return true since <code>@todo</code>
* can be used in constructor documentation and false
* otherwise.
*/
public boolean inConstructor() {
return true;
}
/**
* 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
* otherwise.
*/
public boolean inMethod() {
return true;
}
/**
* Will return true since <code>@todo</code>
* can be used in method documentation.
* @return true since <code>@todo</code>
* can be used in overview documentation and false
* otherwise.
*/
public boolean inOverview() {
return true;
}
/**
* Will return true since <code>@todo</code>
* can be used in package documentation.
* @return true since <code>@todo</code>
* can be used in package documentation and false
* otherwise.
*/
public boolean inPackage() {
return true;
}
/**
* Will return true since <code>@todo</code>
* can be used in type documentation (classes or interfaces).
* @return true since <code>@todo</code>
* can be used in type documentation and false
* otherwise.
*/
public boolean inType() {
return true;
}
/**
* Will return false since <code>@todo</code>
* is not an inline tag.
* @return false since <code>@todo</code>
* is not an inline tag.
*/
/**
* Register this Taglet.
* @param tagletMap the map to register this tag to.
*/
public static void register(Map tagletMap) {
Table tag = new Table();
Taglet t = (Taglet) tagletMap.get(tag.getName());
if (t != null) {
tagletMap.remove(tag.getName());
}
tagletMap.put(tag.getName(), tag);
}
/**
* Given the <code>Tag</code> representation of this custom
* tag, return its string representation.
/**
* Given an array of Tags representing this custom
* tag, return its string representation.
* @param tags the array of Tags representing of this custom tag.
*/
public String toString(Tag[] tags) {
if (tags.length == 0) {
return null;
}
String result = "";
for (int i = 0; i < tags.length; i++) {
result += toString(tags[i]);
}
return result ;
}
}
Compile your taglet. Use javac compiler version 1.4.0 (or later) in the Java 2 SDK. The required class files are
in the lib\tools.jar file in the SDK. Assuming the SDK is installed at C:\Program Files\j2sdk1.4.1 :
Run the javadoc tool using the -taglet and -tagletpath options. For example, if your taglet class file is defined
to be in package com.rgagnon.taglet and is stored in C:\taglets\com\rgagnon\taglet\Table.class, then you
should set tagletpath to C:\taglets. This example calls javadoc on package com.package1, including Table
taglet tags:
The javadoc utility uses the regular Java mechanism to internationalize its output. The tools.jar in the lib
directory contains the resource bundle standard.properties used by Javadoc to generated the labels. To add a
new language, you need to create the appropriate resource bundle, in our case for french, we need a file called
standard_fr.properties.
Extract from tools.jar, the standard.properties files (keep the directory structure). Copy it under the name
standard_fr.properties. Translate it (or you can download my "incomplete" version here).
[standard.properties (extract)]
doclet.Window_Split_Index={0}\: {1}-Index
doclet.Packages=Packages
doclet.SerialData=Serial Data\:
doclet.Since=Since\:
doclet.Warn_inline_taglet=Inline tag {0} should only be used with a {1}.
doclet.ClassUse_Subinterface=Subinterfaces of {0} in {1}
doclet.Frame_Version=Frame version
doclet.Generated_Docs_Untitled=Generated Documentation (Untitled)
[standard_fr.properties (extract)]
doclet.Window_Split_Index={0}\: {1}-Index
doclet.Packages=Paquetages
doclet.SerialData=Donn\u00E9e s\u00E9rialis\u00E9e\:
doclet.Since=Depuis\:
doclet.Warn_inline_taglet=Inline tag {0} should only be used with a {1}.
doclet.ClassUse_Subinterface=Sous-interfaces de {0} dans {1}
Once everything translated, put your standard_fr.properties into the tools.jar making sure that the file is
located in the right package (along standard.properties in com.sun.tools.doclets.standard.resources).
Using Ant,
<javadoc
locale="fr"
sourcefiles="c:/client/Client.java"
destdir="javadoc/Client"
author="true"
version="true"
use="true"
private="true"
windowtitle="Client">
<doctitle><![CDATA[<h1>Client</h1>]]></doctitle>
<bottom><![CDATA[<i>Copyright © 2003 Real's Howto.</i>]]></bottom>
</javadoc>
com
rgagnon
HelloWorld.java
This must be a complete HTML file (with HEAD and BODY). the first line of the body will be used a the
package description by javadoc.
<html><head></head><body>
this is <i>com.rgagnon</i> package description,
see <a href="http://www.rgagnon.com" target="_top">web site</a>
</body></html>
Now execute the javadoc utility located in [JDK]\bin directory from the root of the com.rgagnon package.
Since JDK 1.5, to create a package comment file, you have a choice of two files to place your comments:
• package-info.java - Can contain a package declaration, package annotations, package comments and
Javadoc tags. This file is new in JDK 5.0, and is preferred over package.html.
• package.html - Can contain only package comments and Javadoc tags, no package annotations.
See http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/javadoc.html#packagecomment
Use the numerical identity to represent the / in the javadoc section to avoid any conflict with a real comment.
import java.awt.*;
public class Example {
/**
* Simple Frame
* <pre>
* /* create a frame */
* Frame f = new Frame()
* </pre>
* @param args
*/
public static void main(String args[]){
Frame f = new Frame();
f.setSize(200,200);
f.setVisible(true);
}
}
You can represent any character with a numerical identity, the syntax is &#nnn; where nnn is the Unicode
code (decimal value) of the character.
/**
* 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.
With Javadoc 1.5, you can use the {@code ... } command. :
/**
* To use this class use this XML
* <pre>
* {@code
* <xml>
* <parameter>foo</parameter>
* <value>bar</value>
* </xml>
* }
* </pre>
*/
With the previous versions, one way was to add a space after the <.
/**
* To use this class use this XML
* <pre>
* < xml>
* < parameter>foo< /parameter>
* < value>bar< /value>
* < /xml>
* }
* </pre>
*/
Since 1.4, a logging functionnality is included with the JDK. It's the java.util.logging package.
import java.util.logging.*;
import java.io.*;
static {
try {
boolean append = true;
FileHandler fh = new FileHandler("TestLog.log", append);
//fh.setFormatter(new XMLFormatter());
fh.setFormatter(new SimpleFormatter());
logger = Logger.getLogger("TestLog");
logger.addHandler(fh);
}
catch (IOException e) {
e.printStackTrace();
}
}
<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>
import java.util.logging.*;
import java.io.*;
static {
try {
boolean append = true;
FileHandler fh = new FileHandler("TestLog.log", append);
fh.setFormatter(new Formatter() {
public String format(LogRecord rec) {
StringBuffer buf = new StringBuffer(1000);
buf.append(new java.util.Date());
buf.append(' ');
buf.append(rec.getLevel());
buf.append(' ');
buf.append(formatMessage(rec));
buf.append('\n');
return buf.toString();
}
});
logger = Logger.getLogger("TestLog");
logger.addHandler(fh);
}
catch (IOException e) {
e.printStackTrace();
}
}
Default values are defined in JRE_HOME/lib/logging.properties. To use a different properties file, you
specify a filename with the java.util.logging.config.file system property.
Look for the property handlers and remove the value java.util.logging.ConsoleHandler
You may want to take a look at another popular logging mechanism : Log4J.
JDK1.5+
[LogUtils.java]
class Test {
public void doit() {
System.out.println("*Howto Trace only 1 level\n" + LogUtils.getStack(1));
System.out.println("*Howto Trace only 10 levels\n" + LogUtils.getStack(10));
System.out.println("*Howto Trace no level (current)\n" + LogUtils.getStack(0));
}
}
public ExecutionTimer() {
reset();
}
See this HowTo to format a duration in ms into a string as "Days , Hours , minutes and seconds".
In production code, a good practice is to only log what is necessary in the context.
With Log4J, you can have different levels of message written into your log.
/**
* Logger log4j
*/
static Logger logger = Logger.getLogger(MyClass.class.getName());
...
logger.debug("I'm here");
logger.info(e.getMessage());
logger.warning("something wrong " + e.getMessage());
logger.error("omg " + e.getMessage());
...
While you can set the level in your code with something like
logger.setLevel(Level.WARN);
You put the properties file in the classpath and then from your code
Logging activities have a cost. Even if you set the level at DEBUG level, the logger.debug(...) is
interpreted. Consider this line :
logger.setLevel(Level.DEBUG);
logger.debug("something wrong with the value of " + myValue.toString());
the toString() method will be called and the result concatened to a String even if the DEBUG level is
disabled.
logger.setLevel(Level.DEBUG);
if (logger.isDebugEnabled()) {
logger.debug("something wrong with the value of " + myValue.toString());
}
This way you will not incur the cost of parameter construction if debugging is disabled for logger.
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 :
even if myValue is null, this toString() method will display "null" as the value and not throw a
NullPointerExeception.
While you can set the logging level through the configuration properties file
It may be useful to change it on-the-fly for debugging purpose. You need to get the Log4J "root" Logger
and then change its "level".
...
setLogLevel("DEBUG");
...
setLogLevel("INFO");
...
root.setLevel(org.apache.log4j.Level.DEBUG);
}
else {
root.setLevel(org.apache.log4j.Level.INFO);
}
}
You can enable the logging at the DEBUG level by simply setting 2 environment variable.
For example, if you have something using the Axis library to do a Web Service call, then
java.exe -Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.SimpleLog
-Dorg.apache.commons.logging.simplelog.defaultlog=debug
MyClassUsingAxis
will launch the program and output to stdout the debugging information.
...
...
-Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.SimpleLog
-Dorg.apache.commons.logging.simplelog.showdatetime=true
-Dorg.apache.commons.logging.simplelog.log.httpclient.wire=debug
-Dorg.apache.commons.logging.simplelog.log.org.apache.commons.httpclient=debug
if (logger.isDebugEnabled()) {
Logger logpdfengine = Logger.getLogger("org.apache.pdfbox.util.PDFStreamEngine");
logpdfengine.setLevel(org.apache.log4j.Level.OFF);
}
In the manifest file of a JAR, it is possible to specify the class to be used when the JVM is lauched with the
JAR as parameter. The class must have a main().
import java.awt.*;
import java.awt.event.*;
Then create this manifest file (manifest.mft) with any text editor.
Manifest-Version: 1.0
Main-Class: MyClass
Class-path: .
Main-Class specifies the entry point with the main(String args[]) method.
The Class-path is used to specify the dependency of this jar (if any). You add the directories and jars
separated by a space. It is important because when running a jar , the CLASSPATH definition (as defined
by the environnement variable) is overridden.
Next, you include the manifest file in the JAR (MyJar.jar) with the MyClass class.
Then you are able to start the MyClass.class by double-clicking on the MyJar.jar file (if the JRE is correctly
installed) or by typing
If you need to pass parameters, use the -D switch before the -jar switch and use the getProperty() method to
get the value.
The file association mechanism is made during the installation of the JRE.
You can verify that everything is ok with the following command from a DOS Shell
>assoc .jar
.jar=jarfile
>ftype jarfile
jarfile="C:\Program Files\Java\jre1.5.0_10\bin\javaw.exe" -jar "%1" %*
If the association is broken or you need to change the JRE used then by using the assoc/ftype utilities, you
can modify the association easily (use /? to display the syntax of the assoc and ftype utilities).
NOTE: On WinXp (or better), your user account needs to be at the Admin level.
On Windows (NT or better), you can also make JARs run from the command-line by setting the PATHEXT
environment variable, for example
SET PATHEXT=.EXE;.BAT;.CMD;.JAR
Then if you have the jar file MyJar.jar accessible via the PATH environment variable, typing "MyJar" on
the DOS command line will invoke "javaw -jar MyJar.jar" .
Supposed we have a jar called Main.jar for the application. This application needs Second.jar and Third.jar
. In the manifest file of the first jar (Main.jar), you adjust the Class-Path setting :
Manifest-Version: 1.0
Main-Class: MyClass
Class-Path: Second.jar Third.jar
The value of the Class-Path attribute specifies the relative URLs of the extensions or libraries that this
application or extension needs. URLs are separated by one or more spaces. The application or extension
class loader uses the value of this attribute to construct its internal search path.
You can use the -i option to speed up your application's class loading time:
jar -i main.jar
This will build an an INDEX.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.
import java.io.*;
import java.util.jar.*;
import java.util.zip.*;
InputStream in =
new BufferedInputStream(jar.getInputStream(entry));
OutputStream out =
new BufferedOutputStream(new FileOutputStream(efile));
byte[] buffer = new byte[2048];
for (;;) {
int nBytes = in.read(buffer);
if (nBytes <= 0) break;
out.write(buffer, 0, nBytes);
}
out.flush();
out.close();
in.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
Manifest-Version: 1.0
Classpath: .\mydb.jar
Main-Class: ExtractFromJAR
Run it ... and the mydb.mdb file should appear in the current directory.
I got a problem when the jar file was located in C:\Program Files\xyz due to the embedded space. So I
modified the code to
package com.rgagnon;
The output
>java com.rgagnon.HelloClass
file:/C:/DEV/WORK/JAVA/com/rgagnon/HelloClass.class
Here a variation on this subject, a method to return the name of the current running jar.
package com.rgagnon.howto;
/*
output :
*/
See these related HowTo's : Obtain from where a Class is loaded Get the "root" of an application
import java.util.jar.*;
import java.util.*;
import java.io.*;
private PackageUtils() {}
while(true) {
jarEntry=jarFile.getNextJarEntry ();
if(jarEntry == null){
break;
}
if((jarEntry.getName ().startsWith (packageName)) &&
/**
*
*/
public static void main (String[] args){
List list = PackageUtils.getClasseNamesInPackage
("C:/j2sdk1.4.1_02/lib/mail.jar", "com.sun.mail.handlers");
System.out.println(list);
/*
output :
Found com.sun.mail.handlers.image_jpeg.class
Found com.sun.mail.handlers.multipart_mixed.class
Found com.sun.mail.handlers.message_rfc822.class
[com.sun.mail.handlers.text_html.class,
com.sun.mail.handlers.text_xml.class, com
.sun.mail.handlers.image_jpeg.class,
, com.sun.mail.handlers.message_rfc822.class]
*/
}
}
package com.rgagnon;
Manifest-Version: 1.0
Main-Class: com.rgagnon.Hello
Manifest-Version: 1.0
Main-Class: com.rgagnon.Hello
Specification-Version: 2.1
Implementation-Version: 1.1
package com.rgagnon;
Hello() {
Package p = this.getClass().getPackage();
System.out.println("Hello Specification Version : "
+ p.getSpecificationVersion());
System.out.println("Hello Implementation Version : "
+ p.getImplementationVersion());
}
This example opens a given Jar and outputs its version information.
package com.rgagnon.howto;
import java.util.jar.*;
private JarUtils() {}
System.out.println("Specification-Version: "
+ JarUtils.getJarSpecificationVersion(javaMailJar));
System.out.println("Implementation-Version: "
+ JarUtils.getJarImplementationVersion(javaMailJar));
/*
* output :
* Specification-Version: 1.3
* Implementation-Version: 1.3.1
*/
}
}
compile:
[javac] Compiling 1 source file
• Go back to the editor and add the jar building command. The target compile is also executed since the target
jar depends on it.
<project default="buildHello">
<target name="compile">
<javac srcdir="." />
</target>
compile:
jar:
[jar] Building jar: /Dev/hello.jar
BUILD SUCCESSFUL
Total time: 2 seconds
$ jar -tvf hello.jar
jar -tvf hello.jar
0 Wed May 03 17:06:32 EST 2006 META-INF/
55 Wed May 03 17:06:32 EST 2006 META-INF/MANIFEST.MF
55 Wed May 03 17:06:32 EST 2006 howto/
335 Wed May 03 16:36:16 EST 2006 howto/Hello.class
• Try your new Jar file
> java -cp Hello.jar howto.Hello
Hello World
• Make your Jar auto-executable by specifying the Main class into a MANIFEST.MF file to be included in
the Jar. Add the following lines to build.xml
<project default="buildHello">
<target name="compile">
<javac srcdir="." />
</target>
<jar destfile="hello.jar"
basedir="."
includes="**/*.class"
manifest="MANIFEST.MF"
/>
</target>
<manifest file="MANIFEST.MF">
<attribute name="Built-By" value="${user.name}"/>
<attribute name="Main-Class" value="howto.Hello"/>
<attribute name="Implementation-Version"
value="${version.num}-b${build.number}"/>
</manifest>
<jar destfile="hello.jar"
basedir="."
includes="**/*.class"
manifest="MANIFEST.MF"
/>
</target>
<target name="jar">
<delete file="hello.jar"/>
<property name="version.num" value="1.00"/>
<buildnumber file="build.num"/>
<manifest file="MANIFEST.MF">
<attribute name="Built-By" value="${user.name}"/>
<attribute name="Main-Class" value="howto.Hello"/>
<attribute name="Implementation-Version"
value="${version.num}-b${build.number}"/>
</manifest>
<jar destfile="hello.jar"
basedir="."
includes="**/*.class"
manifest="MANIFEST.MF"
/>
</target>
<target name="cleanup">
<delete>
<fileset dir="." includes="**/*.class"/>
<fileset file="MANIFEST.MF"/>
</delete>
</target>
</project>
• Build and launch the Hello class
> ant buildHello
...
> java -jar hello.jar
Hello World
version : 1.00-b3
...
<target name="jar">
<delete file="hello.jar"/>
<property name="version.num" value="1.00"/>
<buildnumber file="build.num"/>
<tstamp>
<format property="TODAY" pattern="yyyy-MM-dd HH:mm:ss" />
</tstamp>
<manifest file="MANIFEST.MF">
<attribute name="Built-By" value="${user.name}"/>
<attribute name="Main-Class" value="howto.Hello"/>
<attribute name="Implementation-Version"
value="${version.num}-b${build.number}"/>
<attribute name="Built-Date" value="${TODAY}"/>
</manifest>
<jar destfile="hello.jar"
basedir="."
includes="**/*.class"
manifest="MANIFEST.MF"
/>
</target>
Specifying all the required jar in the classpath can be a pain. Here some techniques to set the classpath
definition automatically.
For Windows 2000 (or better), we need a set of 3 CMD files to scan a given directory and build the
classpath defintion with all the jars found.
main.cmd
@echo off
call buildclasspath.cmd .\lib
Echo The Classpath definition is %CLASSPATH%
...
java MyClass
buildclasspath.cmd
set _CLASSPATH=%CLASSPATH%
set CLASSPATH=%1
for %%i in ( %1\*.jar ) do call buildclasspath_append.cmd %%~fsi
:END
buildclasspath_append.cmd
set CLASSPATH=%CLASSPATH%;%1
With XP (or better), it's simpler ... a single batch file can do the job.
@echo off
setlocal ENABLEDELAYEDEXPANSION
if defined CLASSPATH (set CLASSPATH=%CLASSPATH%;.) else (set CLASSPATH=.)
FOR /R .\lib %%G IN (*.jar) DO set CLASSPATH=!CLASSPATH!;%%G
Echo The Classpath definition is %CLASSPATH%
...
java MyClass
JDK6
Note : There is a bug when using this feature with JAVAW, see
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6510337
Note : Use quote to avoid problem during the wildcard expansion, ex. javac -cp "C:\mylib\*"
HelloWorld.java
The best solution when you have a jar is to try to include the required jars into the manifest declaration.
Manifest-Version: 1.0
Class-Path:
customer_client.jar
mailer_client.jar
signon_client.jar
The manifest file format restrictions mandated by the JDK requires the use of a space ' ' character as the line
continuation character, so ensure that your editor is not set up to trim trailing spaces on saves and exits.
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.
the CLASSPATH definition (as defined by the environment variable) is overriden by the "class-path"
defined the jar's manifest.
See http://java.sun.com/docs/books/tutorial/deployment/jar/downman.html
Ant can be used to build your Jar and built the manifest class-path definition.
</target>
It's possible (but not so simple) to do it automatically without specifying each jar one by one :
<path id="build.classpath">
<fileset dir="${basedir}"/>
<include name="lib/*.jar"/>
</fileset>
</path>
Latest Ant version (1.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. See
http://ant.apache.org/manual/CoreTasks/manifestclasspath.html
<path id="build-classpath">
<fileset dir="${build.dir}">
<include name="*.jar"/>
</fileset>
</path>
<jar>
...
<manifest>
<attribute name="Main-Class" value="com.mycompany.TestMain"/>
<attribute name="Class-Path" value=". ${lib.list}"/>
</manifest>
...
</jar>
To compile, make sure that you have the plugin.jar in the classpath (or Eclipse Build Path). This jar is
usually located in [JRE]/lib folder. During runtime, it's already included by the Java plugin so you don't
have to worry about that.
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
import netscape.javascript.*;
TextField tf;
Button b1;
JSObject win;
b1.addActionListener(this);
add(tf);add(b1);
}
Don't forget the MAYSCRIPT parameter in the APPLET tag, it's required since the Applet is using the
JSObject to interact with the Javascript.
<html>
<head>
<script>
function getUserAgent() {
return navigator.userAgent;
}
</script>
</head><body>
<applet code="GetUserAgent.class" MAYSCRIPT height=100 width=500></Applet>
</body>
</html>
Try it here
You need to parse the returned value to detect browser type. Look at this utility,
http://code.google.com/p/user-agent-utils/ or at this code : http://nerds.palmdrive.net/useragent/code.html
to get the idea.
When serving the HTML containing the Applet, you add the User-Agent as parameter for the Applet.
In a JSP/EL
<HTML><HEAD></HEAD><BODY>
<APPLET CODE="MyApplet.class"
NAME="myApplet"
HEIGHT=400 WIDTH=400 ALT="Oups! You don't have JAVA enabled">
<A HREF="nojava.html">Oups! You don't have JAVA enabled, click here.</A>
</APPLET>
</BODY></HTML>
The Java Console Window Log is also stored on disk. On the Windows plateform, it's in the folder :
There are two ways to include resources based on the current Locale. One way is to use Properties files and
the other are classes extending the ListResourceBundle base class. You need to follow a naming standard so
that the JVM retrieves the right resources bundle.
Note that if a resource is missing for the current locale then the default definition is used.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.text.*;
// String
aLabel = new JLabel
(MyResources.rb.getString("aLabel"));
add(aLabel);
// Object
aCheckbox =
(JCheckBox)MyResources.rb.getObject("aCheckbox");
add(aCheckbox);
Internationalization 236
Real's HowTo PDF version
setSize(400,400);
}
SwingUtilities.invokeLater(t);
}
}
import java.util.*;
import javax.swing.*;
import java.text.*;
import java.util.*;
import java.util.*;
import javax.swing.*;
import java.util.*;
This example uses ListResourceBundle classes to store the required resources. It is possible to substitute them
for Properties files without any change to the code. The properties files must have the .properties extension.
This HowTo lets you select a language and change its GUI to reflect the choice.
We are using a special class, a ListResourceBundle, to store our resources. We have a class per Locale. If a
specific resource is not in a specific Locale ListResourceBundle then the default resource is used.
To use a properties file instead of a class to store resources then look at this HowTo.
import java.util.*;
import java.text.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
int localeChoosen = 0;
Locale localeCurrent;
ResourceBundle rb;
ButtonGroup bg;
JButton btnQuit;
JRadioButton r0, r1, r2;
JLabel today;
boolean defaultDone = false;
// RADIO buttons
bg = new ButtonGroup();
r0 = new JRadioButton();
r1 = new JRadioButton();
r2 = new JRadioButton();
bg.add(r0);
bg.add(r1);
bg.add(r2);
add(r0);
add(r1);
add(r2);
if (!defaultDone) {
String rDef = rb.getString("rDefault");
if (rDef.equals("r0"))
r0.setSelected(true);
else if (rDef.equals("r1"))
r1.setSelected(true);
else
r2.setSelected(true);
defaultDone = true;
}
else {
if (localeChoosen == 0)
r0.setSelected(true);
else if (localeChoosen == 1)
r1.setSelected(true);
else
r2.setSelected(true);
}
// QUIT button
btnQuit = new JButton();
add(btnQuit);
// today label
today = new JLabel();
add(today);
//
r0.addActionListener(this);
r1.addActionListener(this);
r2.addActionListener(this);
btnQuit.addActionListener(this);
setSize(400,100);
setVisible(true);
}
i.initLocale();
i.initGUI();
i.initText();
i.pack();
}
};
SwingUtilities.invokeLater(t);
}
}
import java.util.*;
import java.util.*;
import java.util.*;
import java.util.*;
With the previous JAVA How-to, the resources were stored in classes. The drawback is when there is a
modification, we must recompile the class. With a resources file, we simply add or modify the resource in a
special file with a regular text editor. The JDK provides a class, PropertyResourceBundle, to use properties
file very easily. In fact, from the programmer's point of view, there is no difference if the resources are stored
in classes or properties files.
The ResourceBundle will look first for classes and if not found, it will look for properties files. We don't have
to specify filenames, the ResourceBundle will construct the filename using the same mechanism used for
The ResourceBundle try to load the properties file from the current classpath.
For example, 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.getBundle("subdir.ResourcesDynamic", localeCurrent);
[InternationalDynamic.java]
import java.util.*;
import java.text.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
int localeChoosen = 0;
Locale localeCurrent;
ResourceBundle rb;
ButtonGroup bg;
JButton btnQuit;
JRadioButton r0, r1, r2;
JLabel today;
boolean defaultDone = false;
(rb.getString("today"), localeCurrent);
today.setText(mf.format(new Object [] { d }));
}
// RADIO buttons
bg = new ButtonGroup();
r0 = new JRadioButton();
r1 = new JRadioButton();
r2 = new JRadioButton();
bg.add(r0);
bg.add(r1);
bg.add(r2);
add(r0);
add(r1);
add(r2);
// QUIT button
btnQuit = new JButton();
add(btnQuit);
// today label
today = new JLabel();
add(today);
//
r0.addActionListener(this);
r1.addActionListener(this);
r2.addActionListener(this);
btnQuit.addActionListener(this);
setSize(400,100);
setVisible(true);
}
[RresourcesDynamic.properties]
title=Example
r0=United States
r1=France
r2=Germany
rDefault=r0
btnQuit=Quit
today=(def) {0,date,long}
[RresourcesDynamic_en.properties]
title=Example
r0=United States
r1=France
r2=Germany
rDefault=r0
btnQuit=Quit
today=(en) {0,date,long}
[ResourcesDynamic_fr.properties]
title=Exemple
r0=Etats-Unis
r1=France
r2=Allemagne
rDefault=r1
btnQuit=Quitte
today=(fr) {0,date, dd/MM/yyyy}
[ResourcesDynamic_de.properties]
title=Beispiel
r0=Vereinigte Staaten
r1=Frankreich
r2=Deutschland
rDefault=r2
btnQuit=Verlassen
today=(de) {0,date,dd.MM.yyyy}
For example :
import java.awt.*;
public class TestUnicode extends java.applet.Applet {
add(a);
add(b);
}
}
Output :
Java not enabled!
á \u00e0 Á \u00c0
à \u00e1 À \u00c1
â \u00e2 Â \u00c2
é \u00e9 É \u00c9
è \u00e8 È \u00c8
ê \u00ea Ê \u00ca
î \u00ee Î \u00ce
ç \u00e7 Ç \u00c7
The Indian rupee symbol ( ₹ HTML entity : ₹) is quite new (2010) so you need to make sure that
the Font that you are using has it. To display it from Java, you need to use Swing because AWT won't be able
to display it.
import java.awt.*;
import javax.swing.*;
This example will show 2 radio buttons, one for english messages and buttons and the other one for french.
Press the button to display a localized JOptionPane according to the radio button selected.
[JOptionPane_en.properties]
Yes=Yes
No=No
Cancel=Cancel
SaveMsg=Do you want to save your data
[JOptionPane_fr.properties]
Yes=Oui
No=Non
Cancel=Annuler
SaveMsg=Voulez-vous sauvegarder vos donnees
Then
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public MessageBoxExample() {
group = new ButtonGroup();
locale = Locale.US;
}
UIManager.put("OptionPane.yesButtonText", rb.getString("Yes"));
UIManager.put("OptionPane.noButtonText", rb.getString("No"));
UIManager.put("OptionPane.cancelButtonText", rb.getString("Cancel"));
msg = rb.getString("SaveMsg");
}
frame.getContentPane().add(panel,"Center");
frame.setSize(panel.getPreferredSize());
frame.setVisible(true);
}
}
Depending on the International setting, numbers with comma as decimal separator may be permitted. The
NumberFormat class can handle this based on the current Locale().
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
private NumberUtils() {}
Localize a JFileChooser
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java-0299.html
Modern Swing release have now built-in ready-to-use translations for the JFileChooser. The language is
choosen based on the current Locale. So you don't have to do anything to display the JFileChooser in the right
language.
The user interface elements provided by the J2SE Runtime Environment 5.0, include Swing dialogs, messages
written by the runtime environment to the standard output and standard error streams, as well as messages
produced by the tools provided with the JRE. These user interface elements are localized into the following
languages:
Language Locale ID
Chinese (Simplified) zh_CN
Chinese (Traditional) zh_TW
English en
French fr
German de
Italian it
Japanese ja
Korean ko
Spanish es
Swedish sv
Sun Supported Locales
This example will show 2 radio buttons, one for english, one for french. Press the button to display a localized
JFileChooser according to the radio button selected.
Create 2 properties files, one for english , one for french (these files are incomplete but should be enough to
get you started).
[JFileChooser_en.properties]
Title=Real's JFileChooser
lookInLabelText=Current
filesOfTypeLabelText=File type
upFolderToolTipText=go up
[JFileChooser_fr.properties]
Title=JFileChooser de R\u00e9al
lookInLabelText=Courant
filesOfTypeLabelText=Type de fichier
upFolderToolTipText=Remonte
Then
[LocalizeJFileChooser.java]
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public LocalizeJFileChooser() {
group = new ButtonGroup();
add(button);
locale = Locale.US;
z_choosertitle = rb.getString("Title");
UIManager.put
("FileChooser.lookInLabelText",
rb.getString("lookInLabelText"));
UIManager.put
("FileChooser.filesOfTypeLabelText",
rb.getString("filesOfTypeLabelText"));
UIManager.put
("FileChooser.upFolderToolTipText",
rb.getString("upFolderToolTipText"));
/*
do the same with :
FileChooser.fileNameLabelText
FileChooser.homeFolderToolTipText
FileChooser.newFolderToolTipText
FileChooser.listViewButtonToolTipTextlist
FileChooser.detailsViewButtonToolTipText
FileChooser.saveButtonText=Save
FileChooser.openButtonText=Open
FileChooser.cancelButtonText=Cancel
FileChooser.updateButtonText=Update
FileChooser.helpButtonText=Help
FileChooser.saveButtonToolTipText=Save
FileChooser.openButtonToolTipText=Open
FileChooser.cancelButtonToolTipText=Cancel
FileChooser.updateButtonToolTipText=Update
FileChooser.helpButtonToolTipText=Help
Almost all Swing widgets can be customize this way. You can
examine the Swing sources to get these values or check
http://www.gargoylesoftware.com/papers/plafdiff.html for
a list of them.
*/
Disable localization
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java-0418.html
By default, the JVM uses the current locale as defined by the OS. To bypass this configuration, you specify on
the command line the locale to be used :
The javadoc utility uses the regular Java mechanism to internationalize its output. The tools.jar in the lib
directory contains the resource bundle standard.properties used by Javadoc to generated the labels. To add a
new language, you need to create the appropriate resource bundle, in our case for french, we need a file called
standard_fr.properties.
Extract from tools.jar, the standard.properties files (keep the directory structure). Copy it under the name
standard_fr.properties. Translate it (or you can download my "incomplete" version here).
[standard.properties (extract)]
doclet.Window_Split_Index={0}\: {1}-Index
doclet.Packages=Packages
doclet.SerialData=Serial Data\:
doclet.Since=Since\:
doclet.Warn_inline_taglet=Inline tag {0} should only be used with a {1}.
doclet.ClassUse_Subinterface=Subinterfaces of {0} in {1}
doclet.Frame_Version=Frame version
doclet.Generated_Docs_Untitled=Generated Documentation (Untitled)
[standard_fr.properties (extract)]
doclet.Window_Split_Index={0}\: {1}-Index
doclet.Packages=Paquetages
doclet.SerialData=Donn\u00E9e s\u00E9rialis\u00E9e\:
doclet.Since=Depuis\:
doclet.Warn_inline_taglet=Inline tag {0} should only be used with a {1}.
doclet.ClassUse_Subinterface=Sous-interfaces de {0} dans {1}
doclet.Frame_Version=Version avec cadres
doclet.Generated_Docs_Untitled=Documentation g\u00E9n\u00E9r\u00E9e
Once everything translated, put your standard_fr.properties into the tools.jar making sure that the file is
located in the right package (along standard.properties in com.sun.tools.doclets.standard.resources).
Using Ant,
<javadoc
locale="fr"
sourcefiles="c:/client/Client.java"
destdir="javadoc/Client"
author="true"
version="true"
use="true"
private="true"
windowtitle="Client">
<doctitle><![CDATA[<h1>Client</h1>]]></doctitle>
<bottom><![CDATA[<i>Copyright © 2003 Real's Howto.</i>]]></bottom>
</javadoc>
Case sensitive
java.util.Arrays.sort(myArray);
Case insensitive
java.util.Arrays.sort(myArray, String.CASE_INSENSITIVE_ORDER);
import java.util.*;
import java.io.*;
java.util.Arrays.sort(words);
w.write("\nAfter :\n");
for (String s : words) {
w.write(s + " ");
}
w.flush();
w.close();
}
catch(Exception e){
e.printStackTrace();
}
The output is :
Before :
Réal Real Raoul Rico
After :
Raoul Real Rico Réal
java.util.Arrays.sort(words);
by
java.util.Arrays.sort(words, java.text.Collator.getInstance(java.util.Locale.FRENCH));
// or
// java.util.Arrays.sort(words, java.text.Collator.getInstance());
Before :
Réal Real Raoul Rico
After :
Raoul Real Réal Rico
import java.util.Locale;
import java.text.Collator;
...
Locale loc = Locale.FRENCH;
sortArray(Collator.getInstance(loc), words);
...
In this code, we have 2 strings, "état" and "famille". We expect that "état" is before "famille". But
String.compareTo() will return that "famille" is before "état".
class Test {
public static void main(String args[]) {
String s1 = "état";
String s2 = "famille";
import java.text.Collator;
String s1 = "état";
String s2 = "famille";
// Collator c = Collator.getInstance(java.util.Locale.FRANCE);
Collator c = Collator.getInstance();
c.setStrength(Collator.PRIMARY);
Equality
To compare without taking into account the presence of accentued so that "é" == "e", we use a Collator.
import java.text.Collator;
// import java.util.Locale;
The following snippets remove from a String accented letters and replace them by their regular ASCII
equivalent.
These can be useful before inserting data into a database to made sorting easier.
Using java.text.Normalizer
We are calling the normalize(). If we pass à, the method returns a + ` . Then using a regular expression, we
clean up the string to keep only valid US-ASCII characters.
import java.text.Normalizer;
import java.util.regex.Pattern;
Using String.replaceAll()
s = s.replaceAll("[èéêë]","e");
s = s.replaceAll("[ûù]","u");
s = s.replaceAll("[ïî]","i");
s = s.replaceAll("[àâ]","a");
s = s.replaceAll("Ô","o");
s = s.replaceAll("[ÈÉÊË]","E");
s = s.replaceAll("[ÛÙ]","U");
s = s.replaceAll("[ÏÎ]","I");
s = s.replaceAll("[ÀÂ]","A");
s = s.replaceAll("Ô","O");
System.out.println(s);
// output : E,E,E,E,U,U,I,I,A,A,O,e,e,e,e,u,u,i,i,a,a,o
}
}
The String.indexOf()
While the two techniques above are ok... there are a little bit slow.
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 we need to detect the position in the first String and then
do a lookup in the second String.
As a bonus, here a method to convert a given string to uppercase with no accent. This can be useful in a
database field to simplify name searching with accent or not.
return null;
}
String txtUpper = txt.toUpperCase();
StringBuilder sb = new StringBuilder();
int n = txtUpper.length();
for (int i = 0; i < n; i++) {
char c = txtUpper.charAt(i);
int pos = UPPERCASE_UNICODE.indexOf(c);
if (pos > -1){
sb.append(UPPERCASE_ASCII.charAt(pos));
}
else {
sb.append(c);
}
}
return sb.toString();
}
In Java 1.6 you can use System.console() instead of System.out.println() to display accentuated characters to
console.
C:\temp>java Test
caractþres franþais : Ó Ú Ú
caractères français : à é é
When starting the JVM and pass on the command line the default file encoding to be used. Then you will be
able to use regular System.out.println().
import java.io.*;
try {
ps = new PrintStream(System.out, true, "Cp850");
}
catch (UnsupportedEncodingException error) {
System.err.println(error);
System.exit(0);
}
ps.println(javaString);
}
}
System.out.println(java.nio.charset.Charset.defaultCharset().name());
}
}
>java Hello
Cp1252
Cp1252
windows-1252
See also java encoding table for the encoding sets supported.
We are using an InputStreamReader which convert the specified input encoding to Unicode and an
OutputStreamWriter which from Unicode to the specified output encoding.
This can be useful when migrating data from a legacy database (ex. Clipper, dBase) to newer DBMS (ex.
mySQL, Sybase).
import java.io.*;
w.flush();
}
w.close();
r.close();
System.exit(0);
}
}
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharacterCodingException;
A different (and simpler) approach is to take a given string and check if it's possible to encode it into ASCII.
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
/*
* output :
* Réal isPureAscii() : false
* Real isPureAscii() : true
*/
}
}
Another way is to use a regular expression, see this Javascript HowTo for a hint!
import java.text.DateFormatSymbols;
import java.util.Locale;
System.out.println(DateUtils.getMonthName(1));
System.out.println(DateUtils.getMonthName(1, new Locale("it")));
System.out.println
(DateUtils.getDayName(java.util.Calendar.SUNDAY, Locale.getDefault()));
/*
* output :
* january
* gennaio
* sunday
*/
}
}
[JDK1.1]
import java.awt.*;
import java.awt.event.*;
import java.io.*;
boolean logFile;
RedirectedFrame(boolean logFile) {
this.logFile = logFile;
System.setOut(aPrintStream);
System.setErr(aPrintStream);
setTitle("Error message");
setSize(500,300);
setLayout(new BorderLayout());
add("Center" , aTextArea);
displayLog();
addWindowListener
(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
}
);
}
IO 271
Real's HowTo PDF version
aTextArea.append(aString);
}
public void write(byte b[], int off, int len) throws IOException {
String aString = new String(b , off , len);
aTextArea.append(aString);
if (logFile) {
FileWriter aWriter = new FileWriter("error.log", true);
aWriter.write(aString);
aWriter.close();
}
}
}
import java.io.*;
Class.forName("unknown").newInstance();
// or this could be changed to:
// throw new Exception();
}
catch (Exception e) {
System.out.println(stack2string(e));
}
}
// Unix style
PrintStream nps = new PrintStream(new FileOutputStream("/dev/null"));
System.setErr(nps);
System.setOut(nps);
//Windows style
PrintStream nps = new PrintStream(new FileOutputStream("NUL:"));
System.setErr(nps);
System.setOut(nps);
You may want to suppress output done with the regular System.out but maintain the ability to write to the
original streams directly when necessary.
This example will print a given text file using the javax.print API.
• With cheap personal printer (at least with mine!), you cannot select many options... more than one copy and
page orientation (portrait or landscape) won't work.
• You need to set the "flavor" as AUTOSENSE so the content is sent as "OCTET-STREAM" even if it's
possible, according to the Javadoc, to set the "flavor" as UTF8 or US_ASCII. I believe this is a limitation of
the Windows platform implementation.
• You need to send a FORMFEED between each print job to eject the last page.
• A special class, PrintJobWatcher, is used to wait for the completion of a print job.
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.File;
import java.io.FileInputStream;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.event.PrintJobAdapter;
import javax.print.event.PrintJobEvent;
String defaultPrinter =
PrintServiceLookup.lookupDefaultPrintService().getName();
System.out.println("Default printer: " + defaultPrinter);
class PrintJobWatcher {
boolean done = false;
PrintJobWatcher(DocPrintJob job) {
job.addPrintJobListener(new PrintJobAdapter() {
public void printJobCanceled(PrintJobEvent pje) {
allDone();
}
public void printJobCompleted(PrintJobEvent pje) {
allDone();
}
public void printJobFailed(PrintJobEvent pje) {
allDone();
}
public void printJobNoMoreEvents(PrintJobEvent pje) {
allDone();
}
void allDone() {
synchronized (PrintJobWatcher.this) {
done = true;
System.out.println("Printing done ...");
PrintJobWatcher.this.notify();
}
}
});
}
public synchronized void waitForDone() {
try {
while (!done) {
wait();
}
} catch (InterruptedException e) {
}
}
}
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.event.PrintJobAdapter;
import javax.print.event.PrintJobEvent;
String defaultPrinter =
PrintServiceLookup.lookupDefaultPrintService().getName();
System.out.println("Default printer: " + defaultPrinter);
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
class PrintJobWatcher {
boolean done = false;
PrintJobWatcher(DocPrintJob job) {
job.addPrintJobListener(new PrintJobAdapter() {
public void printJobCanceled(PrintJobEvent pje) {
allDone();
}
public void printJobCompleted(PrintJobEvent pje) {
allDone();
}
public void printJobFailed(PrintJobEvent pje) {
allDone();
}
public void printJobNoMoreEvents(PrintJobEvent pje) {
allDone();
}
void allDone() {
synchronized (PrintJobWatcher.this) {
done = true;
System.out.println("Printing done ...");
PrintJobWatcher.this.notify();
}
}
});
}
public synchronized void waitForDone() {
try {
while (!done) {
wait();
}
} catch (InterruptedException e) {
}
}
}
A quick and simple way to output some text to a printer is to print to OS logical device attached a printer.
import java.io.FileWriter;
theJobAttribs.setDialog(JobAttributes.DialogType.NONE);
theJobAttribs.setPrinter("HP DeskJet 610C"); // the printer to be used
PrintJob myJob = getToolkit().getPrintJob(this, "PrintJob", theJobAttribs, thePageAttribs);
if (myJob != null) {
Graphics g = myJob.getGraphics();
if (g != null) {
String s = myArea.getText(); // what you like to print
printText(myJob, g, s);
g.dispose();
}
}
myJob.end();
(Win)Initialization is done via the MODE.COM utility. Then to write, simply open a stream using the OS
logical name attached to the serial port. You can use the same technique to print to the printer port (in this
case the local name would be "LPTx:").
In this HowTo, we are creating a temporary vbs file and execute it. 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. The vbs file is created
in the "temporary" folder and is deleted by the JVM at the end.
import java.io.File;
import java.io.FileWriter;
}
catch(Exception e){
e.printStackTrace();
}
}
import java.io.*;
import javax.swing.filechooser.*;
}
}
The output
>java VolumeLabel c:
"temp"
import java.io.File;
import java.util.Arrays;
import java.util.List;
import javax.swing.filechooser.FileSystemView;
*Disquette 3½ pouces
*Disque local
*Lecteur CD
*Disque local
*/
}
}
import java.io.File;
import java.util.Arrays;
import java.util.List;
import javax.swing.filechooser.FileSystemView;
*
*REGA1 (C:)
*
*My Book (F:)
*/
}
}
Websphere MQ exposes many properties to control debugging inforation output. See this document.
When starting the JRE, set the properties on the command line. For example :
-Dcom.ibm.msg.client.commonservices.trace.status=ON
-Dcom.ibm.msg.client.commonservices.trace.outputName=C:\myapps\logs\mq.log
If your program is doing a lot printing to the console using System.out.println() then it is possible to get a
good performance boost by using an alternative to do the console output.
By default, System.out.print() is only line-buffered and does a lot work related to Unicode handling.
Because of its small buffer size, System.out.println() is not well suited to handle many repetitive outputs in
a batch mode. Each line is flushed right away. If your output is mainly ASCII-based then by removing the
Unicode-related activities, the overall execution time will be better.
import java.io.BufferedWriter;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
The result is
Now, rewrite this program to use a 512-bytes buffer and specify the ASCII as character-encoding to be
used.
import java.io.BufferedWriter;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
}
out.flush();
System.err.println("Loop time: " +
(System.currentTimeMillis() - start));
}
The result is
Note that your result will vary depending on your machine/java version but the performance gain should in
the same magnitude.
First method
import java.io.*;
public class TestReadLine {
public static void main (String args[]) {
StreamTokenizer Input=new StreamTokenizer(System.in);
try {
System.out.print(" Your first name : ");
Input.nextToken();
System.out.println("Hi " + Input.sval + "!");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
java.io.DataInputStream in =
new java.io.DataInputStream(System.in);
String aLine = in.readLine();
NOTE: JDK 1.5 provides the Scanner class to do this, see this HowTo.
In Java 1.6 you can use System.console() instead of System.out.println() to display accentuated characters to
console.
C:\temp>java Test
caractþres franþais : Ó Ú Ú
caractères français : à é é
When starting the JVM and pass on the command line the default file encoding to be used. Then you will
be able to use regular System.out.println().
import java.io.*;
try {
ps = new PrintStream(System.out, true, "Cp850");
}
catch (UnsupportedEncodingException error) {
System.err.println(error);
System.exit(0);
}
ps.println(javaString);
}
}
To clear the screen, you can use many System.out.println();, that's about it!
While it is possible to use the DOS ANSI.SYS driver with Windows 9x and make old JVM use it ... it won't
work with modern Windows installations. Windows NT (or better) CMD.EXE does not support ANSI
escape sequences at all.
Fortunately many Open Source solutions are coming to the rescue and Jansi and JCurses are two of them.
Jansi
Jansi is a small java library that allows you to use ANSI escape sequences to format your console output
which works even on Windows.
import org.fusesource.jansi.AnsiConsole;
}
}
NOTE: Check this "old" text file to have an overview of ANSI Escape Sequences.
The above example shows that it's possible to use ANSI codes directly but Jansi provides a neat mechanism
to help building the required ANSI sequence.
JCurses
The Java Curses Library (JCurses) is a library for developing text terminal based applications using Java
programming language. It is implemented as a Windowing toolkit similar to AWT, but built upon the
UNIX "curses" windowing system.
JCurses works on Unix and Windows (32 bit only, on a 64-bit OS you need to use JCurses with a 32-bit
JVM).
This example will display a character-based window with a label, a textfield and a button (don't click with
you mouse, use the keyboard!).
import jcurses.system.*;
import jcurses.widgets.*;
import jcurses.util.*;
import jcurses.event.*;
mgr.addWidget(
new Label("Hello World!",
new CharColor(CharColor.WHITE, CharColor.GREEN)),
0, 0, 20, 10,
WidgetsConstants.ALIGNMENT_CENTER,
WidgetsConstants.ALIGNMENT_CENTER);
button.setShortCut('q');
button.addListener(this);
window.addListener((WindowListener) this);
window.show();
}
import java.util.Scanner;
class TestScanner {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println(sc.nextLine());
System.out.println("Done");
}
}
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The
resulting tokens may then be converted into values of different types using the various next methods.
import java.util.Scanner;
class TestScanner {
public static void main(String args[]) {
// if input is
// 10,12
// then the output is
// 10
// 12
//
// we use a regex as delimiter to combine "," and
// whitespace (in this case the ENTER key)
Scanner sc = new Scanner(System.in).useDelimiter("[,\\s]");
while (sc.hasNextInt()) {
int i = sc.nextInt();
System.out.println(i);
}
System.out.println("Done");
}
}
Scanner can be used with String or Stream. For exemple, the above HowTo can be written like this :
import java.util.Scanner;
class TestScanner {
public static void main(String args[]) {
String input = "10,12"
Scanner sc = new Scanner(System.in).useDelimiter(",");
while (sc.hasNextInt()) {
int i = sc.nextInt();
System.out.println(i);
}
System.out.println("Done");
}
}
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
NOTE : This technique changes the keyboard state so the effect is also seen outside the Java program.
System.setOut(new PrintStream(System.out) {
public void println(String s) {
super.println(s.toUpperCase());
}
});
os2.close();
}
System.out.println("*");
for (int i = 1; i<= 10; i++) {
System.out.println(i);
}
System.out.println("*");
System.setOut(originalOutStream);
System.out.println("Done. Check the log");
}
}
Be sure to read this Javaworld article. It describes the various pitfalls related to the Runtime.exec()
method.
Using Runtime.exec()
This example will capture the output (from stdio) of an external program.
package com.rgagnon.howto;
import java.io.*;
(new InputStreamReader(p.getErrorStream()));
while ((line = bri.readLine()) != null) {
System.out.println(line);
}
bri.close();
while ((line = bre.readLine()) != null) {
System.out.println(line);
}
bre.close();
p.waitFor();
System.out.println("Done.");
}
catch (Exception err) {
err.printStackTrace();
}
}
}
The next example, launch CMD.EXE, grab stdin/stdout and push to stdin command to be interpreted by the
shell.
String line;
OutputStream stdin = null;
InputStream stderr = null;
InputStream stdout = null;
stdin.close();
Launch a Windows CMD (or BAT) file and retrieve the errorlevel or exitcode
// win xp
import java.io.*;
public class CmdExec {
public static void main(String argv[]) {
try {
String line;
Process p = Runtime.getRuntime().exec("test.cmd");
p.waitFor();
System.out.println(p.exitValue());
}
catch (Exception err) {
err.printStackTrace();
}
}
}
@java -garbage
@java -version
Since 1.5, the ProcessBuilder class provides more controls overs the process to be started. It's possible to
set a starting directory.
import java.io.*;
import java.util.*;
See also this HowTo about the new Desktop API, the recommended solution (but you need JDK1.6).
See also this one to open the default browser.
[Dialup.java]
public class Dialup {
public static void main(String[] args) throws Exception {
Process p = Runtime.getRuntime()
.exec("rundll32.exe rnaui.dll,RnaDial MyConnection");
p.waitFor();
System.out.println("Done.");
}
}
You still need to press ENTER to CONNECT, there is an option in the Connection properties to connect
automatically.
You can include a path for the program to be executed. On the Win plateform, you need to put the path in
quotes if the path contains spaces.
If you need to pass arguments, it's safer to a String array especially if they contain spaces.
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.
VBSCRIPT
// Win9x
Runtime.getRuntime().exec("start myscript.vbs");
// WinNT
Runtime.getRuntime().exec("cmd /c start myscript.vbs");
or
Runtime.getRuntime().exec("hh.exe myhelpfile.chm");
Start Excel
import java.io.IOException;
class StartExcel {
public static void main(String args[])
throws IOException
{
Runtime.getRuntime().exec("cmd /c start excel.exe");
}
}
To load a worksheet
import java.io.IOException;
class StartExcel {
public static void main(String args[])
throws IOException
{
String fileName = "c:\\temp\\xls\\test2.xls";
String[] commands = {"cmd", "/c", "start", "\"DummyTitle\"",fileName};
Runtime.getRuntime().exec(commands);
}
}
It's important to pass a dummy title to the Windows start command where there is a possibility that the
filename contains a space. It's a feature.
You use the RUNAS command from the command line to start an application under another account (not
available with XP Home edition). There are many switches that can enhance the behaviour of RUNAS.
Typing "runas /?" from the command prompt gets you all the options.
Runtime.getRuntime().exec(commands);
/SaveCred option allows you to save a password for that account and then reuse it later. For example,
The command runas /savecred /user:administrator regedit.exe prompts for the
password, and then Regedit runs. Next time you use the same command, there is no password prompt.
One potential problem is that when /SaveCred saves the credentials it saves it for whenever RUNAS
invokes that user account. 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. The appropriate registry key is
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explorer, create a
new DWORD value named HideRunAsVerb and assign it a value of 1 to disable Run as.
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.
We simply extract to environnment variable called %programfiles% and build the complete path from
there.
[JDK1.5]
String[] commands =
{"cmd.exe",
"/c",
WIN_PROGRAMFILES
+ FILE_SEPARATOR
+ "textpad 4"
+ FILE_SEPARATOR + "textpad.exe"};
Runtime.getRuntime().exec(commands);
}
}
NOTE : Prior Vista, System folders were localized on disk like C:\Program Files -> C:\Archivos de
programa on the Windows with the Spanish localization. Since Vista, System Folders always exists with
the english name BUT when viewed through Explorer, the localized name is shown. See
http://msmvps.com/blogs/carlosq/archive/2007/02/12/windows-vista-junctions-points-mui-and-localized-folder-nam
JDK1.6
The java.awt.Desktop class uses your host operating system's file associations to launch applications
associated with specific file types.
First it's a good idea to check if the Desktop operations are supported on the running plateform.
import java.awt.*;
...
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
for (Desktop.Action action : Desktop.Action.values()) {
System.out.println("action " + action + " supported? "
+ desktop.isSupported(action));
}
}
then
// default browser
public static void browse(URI document) throws IOException {
Desktop dt = Desktop.getDesktop();
dt.browse(document);
}
While you can exec("java myanotherapp"), it is more appropriate to instanciate and called the main method
of the other application.
Launch many programs using Thread and use join() to wait for the completion.
[Program2.java]
public class Program2 {
public static void main(String arg[]) {
System.out.println("Hello from Program2");
System.out.println("Hello from Program2");
System.out.println("Hello from Program2");
System.out.println("Hello from Program2");
}
}
[Program1a.java]
public class Program1a {
public static void main(String arg[]) throws Exception{
System.out.println("Hello from Program1a");
Thread t1 = new Thread(){
public void run() {
Program2.main(new String[]{});}
};
t1.start();
t1.join();
System.out.println("Hello from Program1a");
}
}
The output :
C:\>java Program1a
Hello from Program1a
Hello from Program2
Hello from Program2
Hello from Program2
Hello from Program2
Hello from Program1a
In this snippet, we initialize a Listbox from a file containing some URLs. When we double click an item,
the default browser is started with the selected HTML page as parameter. This example is Windows
oriented since I have used the start command which supports the file association.
[urlList.txt]
http://www.rgagnon.com/javadetails/java-0001.html|JAVA How-to 1
http://www.rgagnon.com/javadetails/java-0002.html|JAVA How-to 2
http://www.rgagnon.com/javadetails/java-0003.html|JAVA How-to 3
http://www.rgagnon.com/javadetails/java-0004.html|JAVA How-to 4
http://www.rgagnon.com/javadetails/java-0005.htmL|JAVA How-to 5
[StartBrowser.java]
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public AFrame() {
// dispaly setup
setTitle("URL selection");
setSize(400,400);
lbx = new List();
add(lbx);
initLbx();
// action on listbox double click
lbx.addActionListener(this);
// to close the Frame
addWindowListener
(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
setVisible(true);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
Runtime.getRuntime().exec
("rundll32 url.dll,FileProtocolHandler " + theUrl);
You may have difficulty to open a URL ending with .htm. All you need is to replace the last m with %6D,
like
for
See http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html
See https://jdic.dev.java.net
try {
Desktop.browse(new URL("http://www.rgagnon.com");
}
catch (MalformedURLException e1) {
e1.printStackTrace();
}
catch (DesktopException e2) {
e2.printStackTrace();
}
try {
Runtime.getRuntime().exec
("cmd /c start " + currentDir + "/viewLog.lnk");
}
In this example, a file with the extension .xox will be defined and associated with a java program (display
the first 10 lines of selected .xox file).
First the java program to be associated with the .xox file type.
import java.io.*;
With Windows, two commands are used to define a file association, assoc and ftype. 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.
>assoc .xox=Xoxfile
.xox=Xoxfile
Then we specify which program is used to handle the Xoxfile type of file.
The ftype command sets up an association between a file type name, and a string to be used to execute it.
In this example, we specify the Java JVM to be used, the classpath to load the Head.class plus the
parameter (the selected .xox file).
Now, if you double-click on a file with .xox extension, a Dos shell is opened, the Head class is launched
with the clicked filename as a parameter and the first 10 line are displayed.
To make the file association works from a command line, you define the environment variable PATHEXT
to include the .xox extension.
>set pathext=.xox;%pathext%
PATHEXT=.XOX;.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
then you will be able, from a Dos shell, to type only the name of .xox file and the associated program will
be launched with that file as a parameter.
This HowTo query the Windows Registry for a specific key. The VBS prints the result and from Java, we
capture this output.
Since we need the output, we must use the VBS interpreter for the console mode (CSCRIPT.EXE).
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
However, it's easy to do from a VBS. You execute the script from Java, wait for its completion and capture
the return code.
import java.io.File;
import java.io.FileWriter;
In this example, a CMD file is stored a JAR file. The Java code extracts the file as a ressource, launch a
Windows CMD Shell and write the content to the stdin without any temporary file.
In this How-to, the CMD included is used to trigger the default Windows screen saver.
scrnsave.scr /s
import java.io.*;
try {
// that our CMD file in our JAR
InputStream is =
getClass().getResource("/screensaver.cmd").openStream();
BufferedReader brCmdLine =
new BufferedReader(new InputStreamReader(is));
JDK1.6
Open the default file explorer.
import java.io.File;
import java.io.IOException;
import java.awt.Desktop;
try {
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
desktop.open(file);
}
else {
System.out.println("desktop is not supported");
}
catch (IOException e){ }
}
}
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
try {
fin = new FileInputStream("D:/temp/howto.txt");
isr = new InputStreamReader(fin);
br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
finally {
if (br != null) br.close();
if (isr != null) isr.close();
if (fin != null) fin.close();
}
}
The following method read a data file and return the content as a String. We use a StringBuilder to optimize
string concatenation operations.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
try {
fr = new FileReader(filename);
br = new BufferedReader(fr);
String nextLine = "";
StringBuilder sb = new StringBuilder();
while ((nextLine = br.readLine()) != null) {
sb.append(nextLine); // note: BufferedReader strips the EOL character
// so we add a new one!
sb.append(EOL);
}
return sb.toString();
}
finally {
if (br != null) br.close();
if (fr != null) fr.close();
}
}
JDK1.5 provides the java.util.Scanner class which can be used to quickly read a file.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
scanner.close();
}
}
JDK7+ provides, with the NIO package, a new way to get all the content of file quickly. You don't need to
close anything because readAllLines() is taking care of that.
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.io.*;
import java.util.*;
try {
is = FileUtils.class.getResourceAsStream(s);
br = new BufferedReader(new InputStreamReader(is));
while (null != (line = br.readLine())) {
list.add(line);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if (br != null) br.close();
if (is != null) is.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
return list;
}
list = FileUtils.readTextFromJar("/test/datafile2.txt");
it = list.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
}
Create 2 datafiles.
datafile1.txt in the same directory as FileUtils.class (in the root) and datafile2.txt in a subdirectory called
test
[datafile1.txt]
datafile1 line 1
datafile1 line 2
datafile1 line 3
datafile1 line 4
datafile1 line 5
[/test/datafile2.txt]
datafile2 line 1
datafile2 line 2
datafile2 line 3
datafile2 line 4
datafile2 line 5
Try it :
datafile1 line 1
datafile1 line 2
datafile1 line 3
datafile1 line 4
datafile1 line 5
datafile2 line 1
datafile2 line 2
datafile2 line 3
datafile2 line 4
datafile2 line 5
import java.applet.*;
import java.io.*;
The html
<HTML><HEAD></HEAD><BODY>
<APPLET CODE=ReadFromJar.class width=1 height=1 archive=MyJarApplet.jar>
</APPLET>
See java console for output</BODY></HTML>
Try it here
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
private NetUtils() {}
import java.io.*;
import java.util.jar.*;
import java.util.zip.*;
InputStream in =
new BufferedInputStream(jar.getInputStream(entry));
OutputStream out =
new BufferedOutputStream(new FileOutputStream(efile));
byte[] buffer = new byte[2048];
for (;;) {
int nBytes = in.read(buffer)