You are on page 1of 124

I/O FAQ From jGuru

Generated Sep 13, 2005 1:06:44 PM

Location: http://www.jguru.com/faq/IO
Ownership: http://www.jguru.com/misc/user-agree.jsp#ownership.

How can I compress my data to save bandwidth when sending across a


socket?
Location: http://www.jguru.com/faq/view.jsp?EID=3823
Created: Dec 31, 1999 Modified: 2002-03-25 09:34:57.661
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The GZIPInputStream and GZIPOutputStream classes found in the java.util.zip


package compress data with the GZIP file format, as defined by RFC 1952
(ftp://ftp.uu.net/graphics/png/documents/zlib/zdoc-index.html).

See also http://cnrit.tamu.edu/sir_anodos/ for classes to use compression over a


network stream. [User seems to have left university. Anyone know where it went?]

Comments and alternative answers

For more info, see How can I compress/uncompress a...


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Oct 1,
2000
For more info, see How can I compress/uncompress a long string or a file (of any
type)?.

Doesn't work so well with live Socket communications.


Author: Andy DePue (http://www.jguru.com/guru/viewbio.jsp?EID=24220), Mar 28,
2001
The short answer above doesn't really help those people who want to add a
"compression layer" to their socket streams. The reality is, if you wrap your Socket
streams in these compressed streams, you will find that your client or server will seem
to hang. Why? Say you write a byte to a GZip stream... does that mean a byte (or less
than a byte) comes out on the other end right when you write it? Nope. The GZip
streams do not write to the underlying stream until there are enough bytes on the
incoming side to send compressed bytes to the outgoing side. Here is an example:
Client A connects to Server B. They both use the GZip streams to compress their
socket streams. Server B sends a HELLO message to Client A, but Client A never
receives it because the GZip output stream on Server B doesn't have enough data to
compress to output anything. Meanwhile, Server B is waiting for an ACK from Client
A, and never gets it because Client A never got its HELLO message. Nothing else
happens. Again, this is because Server B never sent all the HELLO bytes out of its
Socket to Client A, because the GZip streams hold on to the outgoing data until they
have enough to compress. And calling flush() doesn't help at all. An alternative is not
to wrap the Socket streams in the GZIP streams, but instead individually compress the
pieces you send (in other words, put a GZIP output stream around a
ByteArrayOutputStream, write out your data, close the stream, and then send the
resulting byte array from the ByteArrayOutputStream out the socket). This, of course,
is not very effecient CPU, memory, or compression wise. Anyone else have any ideas
on how to wrap a Socket stream in a GZIP stream and have it actually work?

Re: Doesn't work so well with live Socket communications.


Author: Mark Phillips (http://www.jguru.com/guru/viewbio.jsp?EID=134288), Jul
12, 2002

About a year ago I wrestled with the same problem Andy outlines and failed to
solve it.

Nowadays I expect the task is fairly easily accomplished with NIO and
ByteBuffers. You compress your data before loading it into your ByteBuffer for
transmission. Steams be damned, LOL.

--Mark

Re[2]: Doesn't work so well with live Socket communications.


Author: Patrice Espie
(http://www.jguru.com/guru/viewbio.jsp?EID=1097058), Jun 25, 2003
Well, I wrote a litle library where you can find
CompressedInputStream/CompressedOutputStream classes. See at
http://www.patrice-espie.org Enjoy !

Can I use a BufferedOutputStream with an ObjectOutputStream to serialize an


object?
Location: http://www.jguru.com/faq/view.jsp?EID=5295
Created: Jan 17, 2000 Modified: 2000-03-13 21:50:27.046
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10)

Yes. In fact, it is recommended that you buffer all your input and output unless you
have a good reason not to.

Here's an example of how to do this:

...
String myobject = new String("myobject");
FileOutputStream file = new FileOutputStream("myobject.ser");
BufferedOutputStream bout = new BufferedOutputStream(file);
ObjectOutputStream out = new ObjectOutputStream(bout);
out.writeObject(myobject);
out.flush();
...
Java allows you to chain I/O streams together. Using a BufferedOutputStream
makes output much more efficient because the I/O overhead is then expended on
large chunks of data, rather than on individual bytes.

Likewise, many times it makes sense to compress your output, say if you are writing
many large objects to a file or a socket. You can do this using a ZipOutputStream or
a GZIPOutputStream in place of (or in addition to!) the BufferedOutputStream in
the above example.

How do I work with the StreamTokenizer to get number and word tokens
from a file?
Location: http://www.jguru.com/faq/view.jsp?EID=7190
Created: Jan 21, 2000 Modified: 2001-08-18 16:52:55.831
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

After opening up a FileReader, you get the next token and switch based upon which
type of token you have:
FileReader reader = new FileReader(filename);
BufferedReader br = new BufferedReader(reader);
StreamTokenizer tokenizer = new StreamTokenizer(br);
int type;
while ((type = tokenizer.nextToken()) != StreamTokenizer.TT_EOF) {
switch (type) {
case StreamTokenizer.TT_NUMBER:
System.out.println("Number: " + tokenizer.nval);
break;
case StreamTokenizer.TT_WORD:
System.out.println("Word: " + tokenizer.sval);
break;
}
}
Comments and alternative answers

How do I work with the StreamTokenizer to get number and word tokens from a
file?
Author: D B (http://www.jguru.com/guru/viewbio.jsp?EID=1050692), Jan 27, 2003
StreamTokenizer will not recognize say "1.0e+1" as a single number. Instead you'll
get TT_NUMBER "1.0" followed by TT_WORD "e" followed by .... There must be a
trick to make StreamTokenizer return TT_WORD and then parse this token by, e.g.
Double.parseDouble(). And there must be another trick to parse "1.0d+1" as a
number. Or there is a more preferred way to parse things like "key number" than
StreamTokenizer?

What happened to printf or how do I format the numbers I need to print?


Location: http://www.jguru.com/faq/view.jsp?EID=8882
Created: Jan 26, 2000 Modified: 2000-01-26 01:22:50.759
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The Java libraries and println() method provide no direct equivalent to printf/sprintf.
While Acme labs provides an alternative at
http://www.acme.com/java/software/Acme.Fmt.html, the NumberFormat class
provides a mechanism for setting the number of characters to display before and
after the decimal point.

For instance, the following would print out a number with commas for the thousand,
millions, billions, etc, at least one number after the decimal point, and at most two
numbers (w/o rounding) after the decimal point.

NumberFormat format = new DecimalFormat("#,##0.0#");


System.out.println(format.format(0));
System.out.println(format.format(10000));
System.out.println(format.format(100000000));
System.out.println(format.format(25.25));
System.out.println(format.format(-10.125));

Running this would display:

0.0
10,000.0
100,000,000.0
25.25
-10.12

For additional formatting options, see the description of the DecimalFormat class.

How do I change what standard output or standard error goes to so it can


go somewhere other than the console?
Location: http://www.jguru.com/faq/view.jsp?EID=13177
Created: Feb 10, 2000 Modified: 2000-02-11 19:21:13.023
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The System class allows you to reassign where these streams go to with either the
static setOut(PrintStream) method or the setErr(PrintStream) method.

How do I get FilenameFilter to work on my FileDialog?


Location: http://www.jguru.com/faq/view.jsp?EID=17853
Created: Feb 24, 2000 Modified: 2001-08-20 11:00:38.007
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Basically, it doesn't work on Windows machines.

The JFileDialog provides a better alternative that supports filters, if you can use the
Swing component set.

See Bug 4031440 for more information:


http://developer.java.sun.com/developer/bugParade/bugs/4031440.html.

How can I set file permissions for files created from Java?
Location: http://www.jguru.com/faq/view.jsp?EID=19558
Created: Mar 1, 2000 Modified: 2001-08-18 16:55:48.616
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4) Question
originally posed by Akhil Gupta
(http://www.jguru.com/guru/viewbio.jsp?EID=19377

In pure Java code, you can only specify the read, write, or read & write file modes
using the java.io.File class.

Unfortunately, for operating systems like Linux, that means that you don't have any
portable way to distinguish and control the various user classes (i.e., the file's owner,
other folks in the owner's "group", or random folks) nor can you deal with things like
the "sticky" bit.

The proper way on Unix machines to do this is to set the userMask to the desired
value. When JVM is run on Unix box it takes the file permissions from the value of
userMask.

How do I append to end of a file in Java?


Location: http://www.jguru.com/faq/view.jsp?EID=19681
Created: Mar 2, 2000 Modified: 2001-08-18 19:05:38.856
Author: Nicholas Wright (http://www.jguru.com/guru/viewbio.jsp?EID=19679)

You can use java.io.RandomAccessFile and something like the following:

try {
RandomAccessFile raf =
new RandomAccessFile("filename.txt", "rw");
raf.skipBytes( (int)raf.length() );
// You are now at the end of the file,
// and can start writing new data out, e.g.
raf.writeBytes(
"Log restarted at 13:00pm 3-2-2000\n");
raf.close();
} catch (IOException ex ) {
ex.printStackTrace();
}
or you can use FileWriter / FileOutputStream and open it for append:

FileWriter writer =
new FileWriter("filename.txt", true);

How can I save/load application settings that I would normally use .ini files
or the Windows Registry?
Location: http://www.jguru.com/faq/view.jsp?EID=20462
Created: Mar 5, 2000 Modified: 2005-09-12 14:42:49.101
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by chih-ming yan
(http://www.jguru.com/guru/viewbio.jsp?EID=20234
You can use Java property files for storing settings for an application. Use the
java.util.Properties class, which includes a load and store method.

You can also use a PropertyResourceBundle, but there is no way to automatically


store these files built into the Java classes, only read them.

How can I implement a FileFilter that supports wildcards in the file pattern?
Location: http://www.jguru.com/faq/view.jsp?EID=22021
Created: Mar 8, 2000 Modified: 2001-08-18 17:01:18.315
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Nicholas Whitehead
(http://www.jguru.com/guru/viewbio.jsp?EID=1260

You can find an implementation of FilenameFilter that supports this at


http://www.jzoo.com/java/wildcardfilter/index.html. This should be easily modifiable
to a FileFilter.

How can I accept a password from the console without an echo?


Location: http://www.jguru.com/faq/view.jsp?EID=23448
Created: Mar 13, 2000 Modified: 2000-03-23 12:45:07.947
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Govind Seshadri PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=14

You can't. Java provides no way to disable echo when reading from System.in.
Comments and alternative answers

http://www.javaworld.com/javaworld/javaqa/2000-04/...
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Apr 9,
2000
http://www.javaworld.com/javaworld/javaqa/2000-04/f_01-qa-0407-command.html
provides some ideas on some alternatives.

Re: http://www.javaworld.com/javaworld/javaqa/2000-04/...
Author: Giedrius Tumelis (http://www.jguru.com/guru/viewbio.jsp?EID=457067),
Jul 18, 2001
yes your method is good enougt. I did so:
class Eraser extends Thread {
PrintStream out;
boolean finish=false;
public Eraser (PrintStream out) {
this.out = out;
}
public void run () {
while ( !finish ) {
out.print ( "\010*" );
try {
sleep ( 10 );
} catch ( InterruptedException inte
) {
finish = true;
}
}
}
}

// .....

public static String readPassword () {


Eraser eraser = new Eraser ( System.out );
eraser.start ();
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
String password = "";
try {
password = in.readLine();
} catch ( IOException ioe ) {
}
eraser.interrupt ();
try {
Thread.sleep ( 100 );
} catch (InterruptedException inte ) {
}
return password;
}
}

There is only one real pure Java solution


Author: Eugene Kuleshov (http://www.jguru.com/guru/viewbio.jsp?EID=442441), Jul
11, 2001
It's a bit tricky but pretty elegant. :)

In short, you have to start additional thread and setup that thread to print sequences of
random character and then double backspace for about 100 times in a second (better
to both System.out and System.err). So. That thread will make enough noice to made
entered password completely unreadable. Of course thread should be stopped after
user will press Enter.

How do I create directories in the local file system?


Location: http://www.jguru.com/faq/view.jsp?EID=28215
Created: Mar 24, 2000 Modified: 2001-08-18 17:04:06.664
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Chris Senior
(http://www.jguru.com/guru/viewbio.jsp?EID=2900

The File class includes mkdir() and mkdirs() methods that should help you. mkdir()
will only make the file as a directory, at the last level. What mkdirs() does is create
all parent directories, too, if they do not exist.

How do I check for the existence of a file?


Location: http://www.jguru.com/faq/view.jsp?EID=29346
Created: Mar 28, 2000 Modified: 2001-08-18 17:04:31.874
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Stephen Musgrave
(http://www.jguru.com/guru/viewbio.jsp?EID=28297

The File class includes an exists() method that reports on the existence of a file. The
method returns false to mean the file doesn't exist, true if it does.

How are the serial/parallel I/O ports set up and accessed from a Java
program?
Location: http://www.jguru.com/faq/view.jsp?EID=29867
Created: Mar 29, 2000 Modified: 2000-09-15 13:45:35.948
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by phil nelson
(http://www.jguru.com/guru/viewbio.jsp?EID=29858

The Java Communications API (http://java.sun.com/products/javacomm/index.html)


provides support for accessing RS232 serial ports and IEEE 1284 parallel ports.

StringBufferInputStream has been deprecated; the documentation


recommends you use StringReader instead. Yet, many stream-related
methods in other classes (often those that predate the deprecation) will
only accept an InputStream. How does one send an InputStream that came
from an in-memory string?
Location: http://www.jguru.com/faq/view.jsp?EID=30875
Created: Apr 1, 2000 Modified: 2001-08-18 17:06:49.626
Author: Joseph Shelby (http://www.jguru.com/guru/viewbio.jsp?EID=26292)

Nearest I can figure out is you have to convert the String to its byte array, and pass
that into a ByteArrayInputStream. I had to do this because I was passing properties
data over the 'net, embeded as CDATA in XML, and I couldn't therefore pass the
whole network stream over to the Properties loader.
String s = ...;
Properties p = new Properties();
byte[] bArray = s.getBytes();
ByteArrayInputStream bais = new ByteArrayInputStream(bArray);
p.load(bais);
Comments and alternative answers

When converting to a ByteArrayInputStream, this uses...


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Apr 1,
2000
When converting to a ByteArrayInputStream, this uses the platform's default
character encoding. This can potentially lose information. The other option is save to
a temporary file and read in from file. Be sure to enable delete on exit for the file so it
doesn't hang around.

I'm writing to a socket using a buffered stream. When control returns after
write() is invoked, has the data been sent over the network or just copied
to the buffer? How does the user get notification of a network failure if the
data is just put into the buffer?
Location: http://www.jguru.com/faq/view.jsp?EID=32701
Created: Apr 5, 2000 Modified: 2000-04-05 12:53:55.476
Author: Maxim Senin (http://www.jguru.com/guru/viewbio.jsp?EID=21992)
Question originally posed by Harinder Sood
(http://www.jguru.com/guru/viewbio.jsp?EID=32196

The data is sent only when the buffer is full or flush() is invoked on the buffered
stream. If the network fails (e.g. the remote host closes the socket), an
IOException will be thrown the next time you perform an operation on the socket.
Comments and alternative answers

Network failure
Author: Mark Phillips (http://www.jguru.com/guru/viewbio.jsp?EID=134288), Jul 12,
2002

Actually in reality you'll receive notice (an IOException) only if the remote host
explicitly closes the socket. If the network fails due to a routing error or a modem
drop, etc., it's possible you may never receive notice of the disconnect. This is one
reason why it's important for robust server implementations to migrate to NIO's
nonblocking sockets.

Hope this helps.

--Mark

How can I see from an applet the names of files and directories that are in
the server?
Location: http://www.jguru.com/faq/view.jsp?EID=32770
Created: Apr 5, 2000 Modified: 2001-08-18 17:08:00.954
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Vardit Goldner
(http://www.jguru.com/guru/viewbio.jsp?EID=32664

There is no built-in support for this. Basically, you must create a service on the
server that when requested returns a list of available files and directories.

How can I get an event or notification when a file is changed or modified


using standard java.io classes?
Location: http://www.jguru.com/faq/view.jsp?EID=32811
Created: Apr 5, 2000 Modified: 2001-08-18 17:08:43.202
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Khoivu N (http://www.jguru.com/guru/viewbio.jsp?EID=32600

There is no built in support for this capability.


Comments and alternative answers
Well it depends on how often you want to do it and...
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537), Apr 6,
2000
Well it depends on how often you want to do it and you do not want to poll. It is
conceivable though to write a low priority thread to check the files last modified time
stamp and say fires a property change event. (Somewhat along the lines of
java.awt.MediaTracker)
public class FileMonitor implements Runnable {
public static final String FILE_CHANGED_PROPERTY =
"FILE_CHANGED_PROPERTY";
private File fileToMonitor;
private PropertychangeSupport;

public FileMonitor(File fileToMonitor)


{
this.fileToMonitor = fileToMonitor;
pcs = new PropertychangeSupport(this);
}

public void addPropertyChangeListener(PropertyChangeListener pcl)


{
pcs.addPropertyChangeListener(pcl);
}

public void removePropertyChangeListener(PropertyChangeListener


pcl)
{
pcs.removePropertyChangeListener(pcl);
}

private Thread monitor;


public void startMonitoring() {
if (monitor != null) {
monitor = new Thread(this, /* desired priority */);
monitor.start();
}
}

private long lastModified = -1;


public void run() {
lastModified = fileToMonitor.lastModified();

// check the lastModified every so often


// if there is a difference fire the event
}
}
PS: This is an untested code obviously.

Could you describe the architecture behind jGuru.com: JSP, Servlets,


database, servers, transactions etc...?
Location: http://www.jguru.com/faq/view.jsp?EID=34896
Created: Apr 11, 2000 Modified: 2002-11-20 12:23:54.439
Author: Terence Parr (http://www.jguru.com/guru/viewbio.jsp?EID=1) Question
originally posed by Benoit Xhenseval
(http://www.jguru.com/guru/viewbio.jsp?EID=3363

[Updated Nov 20, 2002 to remove old description and point at some articles. TJP]

jGuru.com Case-Study.

Little Nybbles of Development Wisdom.

When using object streams over sockets, I have to flush the streams after
each write operation. In fact I even have to flush the output stream soon
after creation. Is there a way out of this?
Location: http://www.jguru.com/faq/view.jsp?EID=35512
Created: Apr 12, 2000 Modified: 2000-04-12 12:47:14.803
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by Viswanathan Kodaganallur
(http://www.jguru.com/guru/viewbio.jsp?EID=35421

The ObjectOutput interface provides a flush() method, implying that


implementations are allowed to buffer the output. The semantics of buffered output
are such that if you want the data to be sent immediately, you need to flush the
buffer (the FAQ at http://www.jguru.com/jguru/faq/view.jsp?EID=32701 talks about
this as well).

It seems you are expecting to be able to read the data on the other end of the
stream immediately after it is written; as you have found out, the only way to ensure
that the data is sent over the socket immediately is to flush the buffer. The
alternatives, setting the buffer size to be very small or turning off buffering entirely,
are not available with socket output streams.

The other problem you mention, having to flush the buffer after creation of the
ObjectOutputStream, is similar. Instantiating an ObjectOutputStream causes the
stream header information to be written to the underlying (buffered) stream. On the
other end, instantiating ObjectInputStream causes this header information to be
read from the stream. If the output stream buffer hasn't been flushed, then the
ObjectInputStream constructor will block until it can read the header information.
Hence, when using buffered I/O, it is usually a good idea to flush the
ObjectOutputStream right after creation. There is no other way to do this.

How can I read .zip and .jar file using standard Java classes?
Location: http://www.jguru.com/faq/view.jsp?EID=41035
Created: Apr 27, 2000 Modified: 2001-08-18 17:12:00.941
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Khoivu N (http://www.jguru.com/guru/viewbio.jsp?EID=32600

The ZIP and JAR reading classes are found in the java.util.zip and java.util.jar
packages respectively. The following demonstrates reading from a ZIP file, listing all
the files in the zip and displaying the contents of the first file in the zip. JAR file
reading is similar, just with different classes and having a manifest.

import java.util.zip.*;
import java.util.*;
import java.io.*;

public class ZipExample {


public static void main(String args[]) {
try {
ZipFile zf = new ZipFile("the.zip");
Enumeration entries = zf.entries();
String first = null;
while (entries.hasMoreElements()) {
ZipEntry ze = (ZipEntry)entries.nextElement();
System.out.println("Entry " + ze.getName());
if (first == null) first = ze.getName();
}
ZipEntry ze = zf.getEntry(first);
if (ze != null) {
BufferedReader br = new BufferedReader(
new InputStreamReader(zf.getInputStream(ze)));
long size = ze.getSize();
if (size > 0) {
System.out.println(first + " Length is " + size);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
Comments and alternative answers

How to get an input stream from a nested zip file (zip inside zip)?
Author: Vitaly Lisovsky (http://www.jguru.com/guru/viewbio.jsp?EID=454013), Nov
16, 2001
I tried to use this approach, but I get null when I try to extract data from an embedded
.zip file.
ZipFile zFile = new ZipFile(file);

Enumeration enum = zFile.getEntries();

while(enum.hasNext())
{
ZipEntry zEntry =(ZipEntry)enum.next();
if (isZipFile(zEntry)==true)
{
InputStream is =
zFile.getInputStream(zEntry);
ZipInputStream zIs = mew
ZipInputStream(is);

//now we iterate inside of an


//embedded zip file
ZipEntry ze == null;
while(true)
{
ZipEntry ze = zIs.getNextEntry();

if(ze==null) {
break; //no more entries
}

//get an input stream


InputStream is2 =
zFile.getInputStream(ze);

if (is2 == null) {
//I'm getting null here...

}
}
PS I wrote this code from the top of my head, so there might be some bugs. PPS Is
there a way to get an InputStream of an embedded zip file file? Or I need to first
extract that embedded .zip file, then load it up with ZipFile and then iterate again?
thanks, -Vitaly }

What is meant by canonical path and canonical file?


Location: http://www.jguru.com/faq/view.jsp?EID=42115
Created: Apr 28, 2000 Modified: 2001-08-18 17:13:15.078
Author: Ken Graham (http://www.jguru.com/guru/viewbio.jsp?EID=26759) Question
originally posed by sharma MR (http://www.jguru.com/guru/viewbio.jsp?EID=4939

First - both Absolute and Canonical forms are OS dependent per the API
documentation for java.io.File.

Second - Absolute is not absolute. It is not a resolved path name. If File f is not
already an absolute path name, according to OS dependent rules, then it simply
prepends the value of System.getProperty("user.dir"). However, don't think that
you can use setProperty("user.dir",otherdir), because it will be ignored under
Windows. At some future point Sun may change their mind regarding this. :-)))))

Thirdly - Canonical is resolved, but in an OS dependent form.


Therefore, if you want to really know about the name of the file avoid either of these
two methods, and use File.toURL().toExternalForm() instead. The form is
resolved, and in an OS Independent way, so you can write code that is Write Once
Run Anywhere.

Comments and alternative answers

File.toURL() does getAbsolutePath and checks if the...


Author: Mark Thornton (http://www.jguru.com/guru/viewbio.jsp?EID=276034), Dec
29, 2000
File.toURL() does getAbsolutePath and checks if the file is a directory. It does not
adjust the capitalisation or remove redundant components from the path. While File
objects may ignore case when comparing paths, a URL or the string external form
will not.

The following is output from a simple test program. Files are compared with the first
file, URLs are compared with the first URL. If equal, then "is equal" is printed,
otherwise nothing

File: d:\java\classes
AbsolutePath: d:\java\classes is equal
CanonicalPath: D:\Java\Classes is equal
url: file:/d:/java/classes/

File: d:\Java\Classes is equal


AbsolutePath: d:\Java\Classes is equal
CanonicalPath: D:\Java\Classes is equal
url: file:/d:/Java/Classes/

File: d:\java\projects\..\classes
AbsolutePath: d:\java\projects\..\classes
CanonicalPath: D:\Java\Classes is equal
url: file:/d:/java/projects/../classes/
As you can see the canonical path is reduced to its simplest form, and (for a case
insensitive file system) the case corrected to that stored (if the path exists).

use file.equals(file.getCanonicalFile()) to filter symbolic links on Unix plattforms


Author: Dirk Zoettl (http://www.jguru.com/guru/viewbio.jsp?EID=1203733), Oct 6,
2004
File file = ...

if file is a symbolic link, then either file.isFile() or file.isDirectory() will


return true, depending on the link target.

To filter symbolic links compare file to the result of file.getCanonicalFile().

Tested on Mac OS X with Java 1.4.2_05-141.3 , but should work on all Unix
plattforms.
How do I check for end-of-file when reading from a stream?
Location: http://www.jguru.com/faq/view.jsp?EID=43969
Created: May 3, 2000 Modified: 2000-05-03 06:54:20.664
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Exactly how depends upon which stream you are reading from. If you are reading
with the read() method of InputStream/Reader, this will return -1 on EOF. If however
you are using BufferedReader.readLine(), then this will return null on end of file. And,
the readXXX operations of the DataInput interface throw an EOFException. If you are
unclear how to terminate your reading, check the javadoc for the stream you are
using.

Is there any way to communicate between two classes within an application


using InputStreams and OutputStreams?
Location: http://www.jguru.com/faq/view.jsp?EID=54012
Created: May 22, 2000 Modified: 2000-05-23 18:28:32.671
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Sean Wiechman
(http://www.jguru.com/guru/viewbio.jsp?EID=53867

The PipedInputStream/PipedReader and PipedOutputStream/PipedWriter streams


provide synchronized I/O across threads, from within one class or multiple classes.

The following example demonstrates their usage and was taken from my Mastering
Java 2 book:

import java.io.*;

public class PipeTest {


public static void main (String args[]) {
new OilRefinery();
try { // delay arrival
Thread.currentThread().sleep(500);
} catch (InterruptedException e) {
}
new SuperTanker();
}

// This class consists of a Thread that can accept


"pipline" hook-ups
// via the "clickClunk" method. Clients have to find us
though from
// our Thread name "ThePipeTerminal"
static class OilRefinery extends Thread {
static final int EOF = -1;
boolean alone = true;
// Can't connect piped until "clickClunk"
PipedReader inPipe;
PipedWriter outPipe;

public OilRefinery() {
start(); // Start the thread
}

public synchronized void run() {


int ch;
// Open for business
setName ("ThePipeTerminal");
System.out.println ("Processing plant operational and
on-line");
while (alone) {
try {
wait(); // Non-busy wait for connection
} catch (InterruptedException ohLeaveMeAlone) {
}
}
System.out.println ("Client arrived");
// At this point, a client has connected up to the
pipes
// so process the flow of oil
try {
while ((ch = inPipe.read()) != EOF) {
// add some value to raw input...
outPipe.write (Character.toUpperCase((char)ch));
}
} catch (IOException pipeMalfunction) {
}
try {
outPipe.close(); // signal client "The show's
over!"
} catch (IOException ignored) {
}
alone = true;
System.out.println ("Processing plant shutting
down.");
}
// This is the method clients have to call to connect
up to
// the processing plant
public synchronized boolean clickClunk (PipedWriter
clientOutputPipe,
PipedReader
clientInputPipe) {
System.out.println ("Client arrives to hook-up its
pipes");
try {
inPipe = new PipedReader (clientOutputPipe);
outPipe = new PipedWriter (clientInputPipe);
} catch (IOException connectionFailed) {
System.err.println ("Hook up failed");
return false;
}
System.out.println ("Hook-up successful");
alone = false;
notify();
return true;
}
} // End of class OilRefinery

// This class implements a processing plant client, say a


// supertanker that arrives at the plant to unload its
// crude oil and load up with refined oil
static class SuperTanker {
OilRefinery pipeTerminal = null;
PipedReader returnPipe = new PipedReader();
PipedWriter crudePipe = new PipedWriter();

public SuperTanker() {
pipeTerminal = (OilRefinery) findThread
("ThePipeTerminal");
if (pipeTerminal == null) {
System.err.println ("Snow blizzards prevent
rendezvous");
System.exit (100);
} else {
if (pipeTerminal.clickClunk (crudePipe,
returnPipe)) {
haveOilProcessed();
} else {
System.err.println ("Failed to connect to
processing plant");
}
try {
crudePipe.close();
} catch (IOException brokenValves) {
System.err.println ("Couldn't close valves!");
}
}
}

// Send data (oil) to processing plant, which refines


data and
// sends it back via second pipe stream
public void haveOilProcessed() {
String oilToBeRefined = "Crude Oil";

try {
crudePipe.write (oilToBeRefined);
crudePipe.close();

// Get back refined oil


int ch;
while ((ch = returnPipe.read()) != -1) {
System.out.print ((char)ch);
}
System.out.println();
} catch (IOException oilFlowFailure) {
System.err.println ("Pipe malfunction");
}
}

// This generic method locates the refinery thread


// Note that threads may start/end while checking
public Thread findThread (String target) {
int SAFETY_MARGIN = 10;
// Find master ThreadGroup which all others descend
ThreadGroup rootGroup =
Thread.currentThread().getThreadGroup();
while (rootGroup.getParent() != null) {
rootGroup = rootGroup.getParent();
}
Thread threadList[] =
new Thread [rootGroup.activeGroupCount() +
SAFETY_MARGIN];
int count = rootGroup.enumerate (threadList);
Thread aThread;
for (int i=0;i<count;i++) {
aThread = threadList[i];
if (aThread == null)
continue;
if (aThread.getName().equals (target)) {
return aThread;
}
}
return null;
}
} // End of class SuperTanker

} // End of class PipeTest


Comments and alternative answers

I have found it immensely more practical to share ...


Author: Bret Hansen (http://www.jguru.com/guru/viewbio.jsp?EID=27595), May 28,
2000
I have found it immensely more practical to share objects rather than serializing data
between threads. For they share the same memory space. It is easier to code and you
will get better performance. If I was to extrapolate from the examples that I have seen
of PipedReader/PipeWriter and PipeInputStream/PipedOutputStream, I would be
serializing collections and classes that were composed of many other objects just to
hand it to another thread. Serialization also complicates the scenario if there are
multiple threads sending data to a single thread. I find the following a better way of
implementing inter-thread communication:
import java.io.*;
import java.util.*;

// class with main entry point. Creates the refinery and tanker(s).
public class Pipeline
{
public static void main (String args[])
{
OilRefinery.create();

// sleep a bit for dramatic purposes


try { Thread.sleep(500); } catch (InterruptedException e) { }
new SuperTanker("Tanker #1");

// sleep a bit for dramatic purposes


try { Thread.sleep(500); } catch (InterruptedException e) { }
new SuperTanker("Tanker #2");

// sleep for a while and then shutdown


try { Thread.sleep(5000); } catch (InterruptedException e)
{ }
OilRefinery.getRefinery().refine( new Request( "shutdown"
) );
}
}

class Request
{
String message;
Requestor requestor;

Request( String message )


{
this( message, null );
}

Request( String message, Requestor requestor )


{
this.message = message;
this.requestor = requestor;
}
}

interface Requestor
{
void response( String responseMessage );
}

// This is the refinery


class OilRefinery
extends Thread
{
private static OilRefinery cRefinery = null;

private LinkedList mConnectQue;


private boolean keepRefining;

private OilRefinery()
{
mConnectQue = new LinkedList();
keepRefining = true;

// This class is a self starting thread


start();
}

public static OilRefinery create()


{
if ( cRefinery == null )
{
cRefinery = new OilRefinery();
}

return cRefinery;
}

public static OilRefinery getRefinery()


{
return create();
}

public void refine( Request request )


{
synchronized ( mConnectQue )
{
mConnectQue.add( request );
mConnectQue.notify();
}
}

public void run()


{
// Open for business
System.out.println ("Refinery is now operational");

while (keepRefining)
{
Request request;

synchronized ( mConnectQue )
{
while ( mConnectQue.size() == 0 )
{
try
{
mConnectQue.wait();
}
catch ( InterruptedException e )
{
}
}

request = (Request) mConnectQue.removeFirst();


}

processRequest( request );
processRequest( request );
}

System.out.println ("Processing plant shutting down.");


}

private void processRequest( Request request )


{
System.out.println ("Client request arrived -> '" +
request.message + "'");

if ( request.message.equalsIgnoreCase("shutdown") )
{
keepRefining = false;
return;
}

if ( request.requestor != null)
{
String responseMessage = request.message.toUpperCase();

request.requestor.response( responseMessage );
}
}
}

// This class is a SuperTanker


// supertanker that arrives at the plant to unload its
// crude oil and load up with refined oil
class SuperTanker extends Thread
implements Requestor
{
static final int TankFulls = 5;

String name;
public SuperTanker(String name)
{
this.name = name;
setDaemon( true );
start();
}

public void run()


{
OilRefinery refinery = OilRefinery.getRefinery();

for (int i=0; i<TankFulls; i++)


{
String message = "Oil from " + name + " tank #" + i;
System.out.println( "Sending message to refinery of " +
message );
refinery.refine( new Request( message, this ) );

try { Thread.sleep(500); } catch (InterruptedException e)


{ }
}
}

public void response( String responseMessage )


{
System.out.println( "Received refined response of " +
responseMessage );
}
}

Re: I have found it immensely more practical to share ...


Author: Mahesh Kondwilkar
(http://www.jguru.com/guru/viewbio.jsp?EID=957437), Oct 20, 2002
Actually, as an aside, the PipedReader/Writer mechanism works very well in some
applns, for example when you want to create tons of XML data AND also apply
some XSLTs on them... you could pipe out your XML to xslt applier threads as the
xml is created... a huge saving of space...

How can I wake a thread that is blocked on a call to InputStream.read()?


Location: http://www.jguru.com/faq/view.jsp?EID=59535
Created: May 29, 2000 Modified: 2001-08-18 17:24:12.659
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Tim Murphy
(http://www.jguru.com/guru/viewbio.jsp?EID=57829

(...or any other IO method that wraps read(), like BufferedReader.readLine(). Calling
thread.interrupt() does nothing.)

You can't. That's the way it's supposed to work.


One workaround is to use a non-blocking input stream. Such a stream would call
in.available() to check for the number of bytes that can currently be read without
blocking. If the number is zero, or is less than the size of the data you're expecting,
then you can go on with your business in the rest of the program. One disadvantage
to this technique is that you must poll for input; one big advantage to the standard
block-on-read threads is that they process data as soon as it is availalble.

See Purpletech Code for source code to


com.purpletech.io.NonBlockingInputStream.

See the new (Java 1.4) java.nio.channels package for non-blocking I/O
support.

How can I efficiently compare two binary files for equality?


Location: http://www.jguru.com/faq/view.jsp?EID=66830
Created: Jun 7, 2000 Modified: 2000-06-07 18:11:07.065
Author: Brian O'Byrne (http://www.jguru.com/guru/viewbio.jsp?EID=38567)
Question originally posed by Prabir Das
(http://www.jguru.com/guru/viewbio.jsp?EID=60476

An option which I have used, and found to be reasonably performant, is to read the
files in blocks into byte arrays and use equals() to compare the blocks.
Something like this:

private final static int BLOCK_SIZE = 65536;


// vary BLOCK_SIZE to suit yourself.
// it should probably a factor or multiple of the size of a
disk sector/cluster.
// Note that your max heap size may need to be adjused
// if you have a very big block size or lots of these
comparators.

// assume inputStreamA and inputStreamB are streams from


your two files.
byte[] streamABlock = new byte[BLOCK_SIZE];
byte[] streamBBlock = new byte[BLOCK_SIZE];
boolean match;
do {
int bytesReadA = inputStreamA.read(streamABlock);
int bytesReadB = inputStreamB.read(streamBBlock);
match = ((bytesReadA == bytesReadB) &&
bytesReadA.equals(bytesReadB));
} while (match && (bytesReadA > -1));

It's not fancy, but I think when you want speed simple is good.

How do I modify (add/delete) the content of an existing JAR file?


Location: http://www.jguru.com/faq/view.jsp?EID=68627
Created: Jun 8, 2000 Modified: 2001-08-18 17:25:55.519
Author: V S N Murthy Boggavarapu
(http://www.jguru.com/guru/viewbio.jsp?EID=63013) Question originally posed by V
S N Murthy Boggavarapu (http://www.jguru.com/guru/viewbio.jsp?EID=63013

You can't update the existing JAR file. You have to create a copy with the changes in
it, remove the original, and then rename the updated JAR file. The following
demonstrates this by adding a file to the JAR.
http://gamelan.earthweb.com/journal/techworkshop/trose1/011199_jarzip.html
provides additional information for working with JAR/ZIP files.
import java.io.*;
import java.util.*;
import java.util.zip.*;
import java.util.jar.*;

public class JarUpdate {


/**
* main()
*/
public static void main(String[] args) throws IOException {
// Get the jar name and entry name from the command-line.

String jarName = args[0];


String fileName = args[1];

// Create file descriptors for the jar and a temp jar.

File jarFile = new File(jarName);


File tempJarFile = new File(jarName + ".tmp");

// Open the jar file.

JarFile jar = new JarFile(jarFile);


System.out.println(jarName + " opened.");

// Initialize a flag that will indicate that the jar was updated.

boolean jarUpdated = false;

try {
// Create a temp jar file with no manifest. (The manifest will
// be copied when the entries are copied.)

Manifest jarManifest = jar.getManifest();


JarOutputStream tempJar =
new JarOutputStream(new FileOutputStream(tempJarFile));

// Allocate a buffer for reading entry data.

byte[] buffer = new byte[1024];


int bytesRead;

try {
// Open the given file.

FileInputStream file = new FileInputStream(fileName);


try {
// Create a jar entry and add it to the temp jar.

JarEntry entry = new JarEntry(fileName);


tempJar.putNextEntry(entry);

// Read the file and write it to the jar.

while ((bytesRead = file.read(buffer)) != -1) {


tempJar.write(buffer, 0, bytesRead);
}

System.out.println(entry.getName() + " added.");


}
finally {
file.close();
}

// Loop through the jar entries and add them to the temp
jar,
// skipping the entry that was added to the temp jar
already.

for (Enumeration entries = jar.entries();


entries.hasMoreElements(); ) {
// Get the next entry.

JarEntry entry = (JarEntry) entries.nextElement();

// If the entry has not been added already, add it.

if (! entry.getName().equals(fileName)) {
// Get an input stream for the entry.

InputStream entryStream = jar.getInputStream(entry);

// Read the entry and write it to the temp jar.

tempJar.putNextEntry(entry);

while ((bytesRead = entryStream.read(buffer)) != -1) {


tempJar.write(buffer, 0, bytesRead);
}
}
}

jarUpdated = true;
}
catch (Exception ex) {
System.out.println(ex);

// Add a stub entry here, so that the jar will close


without an
// exception.

tempJar.putNextEntry(new JarEntry("stub"));
}
finally {
tempJar.close();
}
}
finally {
jar.close();
System.out.println(jarName + " closed.");

// If the jar was not updated, delete the temp jar file.

if (! jarUpdated) {
tempJarFile.delete();
}
}

// If the jar was updated, delete the original jar file and
rename the
// temp jar file to the original name.

if (jarUpdated) {
jarFile.delete();
tempJarFile.renameTo(jarFile);
System.out.println(jarName + " updated.");
}
}
}
Comments and alternative answers

Updating a JAR
Author: Scott Large (http://www.jguru.com/guru/viewbio.jsp?EID=777783), Mar 7,
2002
The jar command supports updating an existing JAR file with the -u option, as in:

jar -uf <jar-name> .....

Under what circumstances would I use random access I/O over sequential,
buffered I/O?
Location: http://www.jguru.com/faq/view.jsp?EID=69238
Created: Jun 8, 2000 Modified: 2001-02-16 08:42:31.719
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Ashish Melanta
(http://www.jguru.com/guru/viewbio.jsp?EID=51276

Whether you use random access I/O or sequential access really depends upon what
you are trying to do. Random access I/O is usually used for fixed-size data records,
where you want to overwrite the original record with changes, or to create something
like a rolling log file. Nowadays, there are lightweight database systems that would
do this type of operation for you, adding capabilities like querying and a standard
JDBC access so you wouldn't have to waste your time redesigning the wheel. While
not trying to tell you to never use random access I/O, the Java RandomAccessFile
class lives outside the Java streams class hierarchy meaning that you can't add a
facade around the random access file to buffer it or enrich its capabilities in any
manner. And you would also need to program in things like simultaneous access.

Sequential access is just for that, when you need to access a file sequentially from
start to finish. While you can skip() around the data, it is generally meant to be
read from beginning to end, where the whole file has some meaning. For
performance reasons, it is best to always buffer your I/O, at least when using
Reader, Writer, InputStream, and OutputStream classes, but not
RandomAccessFile.

How can I store and retrieve Unicode or Double Byte data in a file using the
java.io libraries?
Location: http://www.jguru.com/faq/view.jsp?EID=70736
Created: Jun 9, 2000 Modified: 2001-08-18 17:27:31.039
Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)
Question originally posed by Tian Hao
(http://www.jguru.com/guru/viewbio.jsp?EID=56209

Java supports a number of encodings for use with InputStreamReaders and


OutputStreamWriters. By using these classes, it's easy to read and write Unicode or
any other supported encodings. Here's some code that writes a Unicode string to a
file and then reads it back in. Please note that the sample's emphasis is on Unicode
functionality -- obviously more care should be taken with exceptions and file closings
in a production program:
import java.io.*;

public class WRUni


{
public static void main(String[] args)
{
FileOutputStream fos = null;
OutputStreamWriter osw = null;
BufferedWriter bw = null;

FileInputStream fis = null;


InputStreamReader isr = null;
BufferedReader br = null;

String sUni = null;

try
{ // write a UniCode string to a file
fos = new FileOutputStream( "javauni.txt" );
osw = new OutputStreamWriter( fos, "Unicode" );
bw = new BufferedWriter( osw );

bw.write( "A1B2C3D4E5" );
bw.flush();
bw.close();

// read a Unicode string from a file


fis = new FileInputStream( "javauni.txt" );
isr = new InputStreamReader( fis, "Unicode" );
br = new BufferedReader( isr );
while( true )
{
try
{
sUni = br.readLine();
if( sUni == null ) { break; }
System.out.println( "br value: " + sUni );
}
catch( Exception ae )
{
System.out.println("ae: " + ae );
break;
}
} // end while
br.close();
}
catch( Exception e )
{
System.out.println("e: " + e );
}

} // end main
} // End class WRUni

For information on supported encodings by JDK version, check the following URLs --
note that the international version of the JDK is required to use all of the listed
encodings.

JDK 1.1

JDK 1.2

JDK 1.3

How do I detect end of stream in a non-blocking manner when reading a


stream through URL/URLConnection, if available() reports nothing to read
on end of stream?
Location: http://www.jguru.com/faq/view.jsp?EID=72378
Created: Jun 11, 2000 Modified: 2002-03-25 10:37:55.456
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4) Question
originally posed by ceri jerome
(http://www.jguru.com/guru/viewbio.jsp?EID=67121

In the fully general case, you can't (since the client can just keep sending you data).
Given that Java doesn't have asynchronous I/O (yet), you need to design your
system to take into account the potentially blocking nature of the I/O. Also, if you do
the I/O in a separate thread then you also have to deal with the issue of properly
and safely being able to stop your thread if the I/O fails.

In terms of doing URL stuff, I suggest that you look at the HTTPClient package.
In terms of threading, you should definitely look at Doug Lea's util.concurrent
package. Also, of course, check out the jGuru Threads FAQ for more information
about threads.

Java 1.4 supports non-blocking I/O now.

From an applet, how do I get information, like size and creation time, about
a file on the server?
Location: http://www.jguru.com/faq/view.jsp?EID=75649
Created: Jun 14, 2000 Modified: 2001-08-18 17:30:02.807
Author: Brian O'Byrne (http://www.jguru.com/guru/viewbio.jsp?EID=38567)
Question originally posed by Steven Li
(http://www.jguru.com/guru/viewbio.jsp?EID=62131

Assuming you have access to the file in question through a web server, you can use
the URLConnection methods getContentLength() and getLastModified().
URL fileOfInterest = new URL(...);
URLConnection connectionToFileOfInterest =
fileOfInterest.getConnection();
int contentLength =
connectionToFileOfInterest.getContentLength();
long lastModifiedTime =
connectionToFileOfInterest.getLastModified();
You cannot get the creation time this way.

Warning: this is not reliable across Web servers and you may end up downloading
the file completely to get the size.

How do I set a default character encoding for file I/O operations, JDBC
requests and so on?
Location: http://www.jguru.com/faq/view.jsp?EID=78088
Created: Jun 16, 2000 Modified: 2001-08-18 17:31:58.349
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537)
Question originally posed by Dmitry Popov
(http://www.jguru.com/guru/viewbio.jsp?EID=45003

The default encoding used by locale/encoding sensitive API in the Java libraries is
determined by the System property "file.encoding". This system property is initialized
by the JVM startup code after querying the underlying native operating system. For
example on my English USA NT box it is initialized to:
Cp1252
It is generally recommended that you do not modify it. However if you know what
you are doing you could override the system property either on the command line
using the -

java -Dfile.encoding=...

syntax or programmatically at startup.

Here is the reference URL for supported encodings -

• http://java.sun.com/products/jdk/1.2/docs/guide/internat/encoding.doc.html
You may also find Sun's online tutorial helpful:

• http://java.sun.com/docs/books/tutorial/i18n/index.html

Comments and alternative answers

For an example of non-default file encoding and links...


Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100), Jun
16, 2000
For an example of non-default file encoding and links to supported encodings ( and
this can be done with Strings as well, ) see:

How can I store and retrieve Unicode or Double Byte data in a file using the java.io
libraries?

Where can I find a regular expression package in Java?


Location: http://www.jguru.com/faq/view.jsp?EID=72868
Created: Jun 16, 2000 Modified: 2002-03-25 10:41:24.948
Author: Davanum Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=2011)

Regexp is a 100% Pure Java Regular Expression package. It can be downloaded from
http://jakarta.apache.org/regexp/

For a GPL'd solution, check out the gnu.regexp package.

Also note that as of version 2.0, the ORO regexp package has been turned over to
the Jakarta project as well.

There is a standard regular expression package in Java 1.4.

How can I compress/uncompress a long string or a file (of any type)?


Location: http://www.jguru.com/faq/view.jsp?EID=83181
Created: Jun 21, 2000 Modified: 2001-08-18 17:34:20.474
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4) Question
originally posed by Rakesh Leekha
(http://www.jguru.com/guru/viewbio.jsp?EID=83064

Check out the java.util.zip.GZIPInputStream and java.util.zip.GZIPOutputStream


classes. The following demonstrates compressing a file:

import java.io.*;
import java.net.*;
import java.util.zip.*;

public class CompressIt {


public static void main(String[] args) {
if (args.length !=1) {
displayUsage();
System.exit(-1);
} else {
String filename = args[0];
compressIt(filename);
}
}
private static void displayUsage() {
System.err.println(
"Usage: java CompressIt filename");
}
private static void compressIt(String filename) {
try {
File file = new File(filename);
// small files only
int length = (int) file.length();
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis =
new BufferedInputStream(fis);
ByteArrayOutputStream baos =
new ByteArrayOutputStream(length);
GZIPOutputStream gos =
new GZIPOutputStream(baos);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
gos.write(buffer, 0, bytesRead);
}
bis.close();
gos.close();
System.out.println("Input Length: " + length);
System.out.println("Output Length: " +
baos.size());
} catch (FileNotFoundException e) {
System.err.println("Invalid Filename");
} catch (IOException e) {
System.err.println("I/O Exception in transit");
}
}
}

The following table demonstrates the compression results. Depending upon the type
of input, the results can vary considerably.

File Size Compressed


CompressIt.java 1,330 540
(AWT) Component.java 133,742 26,042
Symantec JIT - symcjit.dll 419,840 193,501
Java 2 SDK, version 1.2.2 - src.jar 17,288,462 3,252,177

When reading with a Reader from an ASCII source, how does the Reader
know it is ASCII/8-bit instead of Unicode/16-bit data?
Location: http://www.jguru.com/faq/view.jsp?EID=88802
Created: Jun 27, 2000 Modified: 2001-08-18 17:34:57.381
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537)
Question originally posed by ori soen
(http://www.jguru.com/guru/viewbio.jsp?EID=81264

Well the Reader really wraps an InputStream which gives byte-level access to the
data source. What the Reader (e.g. InputStreamReader) does is to load a correct
implementation of sun.io.ByteToCharConverter based on the "file.encoding"
System property. This property is initialized by the JVM by default after consulting
the native operating system settings. You can override that by setting the
"file.encoding" property using the

-Dfile.encoding=whatever

This affects all instances of the InputStreamReader though. The InputStreamReader


has a constructor which you can use to pass the encoding on a per instance basis.

Here is the link to supported encodings:

http://java.sun.com/products/jdk/1.2/docs/guide/internat/encoding.doc.html

This list varies based on JDK version.

How do I get a listing of the files in a directory?


Location: http://www.jguru.com/faq/view.jsp?EID=89870
Created: Jun 28, 2000 Modified: 2002-03-25 10:46:30.833
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Create a java.io.File for the directory, then ask for the list of files with one of the
following:
public java.lang.String[] list();
public java.lang.String[] list(java.io.FilenameFilter);
public java.io.File[] listFiles();
public java.io.File[] listFiles(java.io.FilenameFilter);
public java.io.File[] listFiles(java.io.FileFilter);
The first two return the filenames as strings (for that directory), the latter three
return actual File objects.

Also, see Re: how do i search a file from a folder that is in the server side using
servlet for another method that lists files in a directory.

Comments and alternative answers


Here's another one...
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 15, 2001
See Re: how do i search a file from a folder that is in... for another method that lists
files in a directory.

Where can I store temporary files?


Location: http://www.jguru.com/faq/view.jsp?EID=89995
Created: Jun 28, 2000 Modified: 2001-08-18 17:42:28.251
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The java.io.tmpdir system property defines an appropriate area:


String tempPath = System.getProperty("java.io.tmpdir");
File f = new File(tempPath, "test.out");
From Davanum Srinivas:

One more alternative is to use File.createTempFile() as follows:

File f = File.createTempFile("TMP","DAT");
See How do I create a temporary file? for more info.

How can I change time and date of a file?


Location: http://www.jguru.com/faq/view.jsp?EID=95338
Created: Jul 4, 2000 Modified: 2001-08-18 17:43:17.324
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Giuliano Iodice
(http://www.jguru.com/guru/viewbio.jsp?EID=95285

Provided you have write access to the file and are using JDK 1.2 or later, the
public boolean setLastModified(long time) method of File allows
you to modify the timestamp associated with a file.

The PropertyResourceBundle class constructor takes an InputStream (not a


Reader). Does this mean that the property files that back the
PropertyResourceBundle always have to be encoded in ASCII (Cp1252 really
on windows)? How are people (localizers) dealing with that in
Japan/Korea/China etc.?
Location: http://www.jguru.com/faq/view.jsp?EID=98171
Created: Jul 7, 2000 Modified: 2001-08-18 17:43:56.214
Author: Larry Widing (http://www.jguru.com/guru/viewbio.jsp?EID=96408) Question
originally posed by Sandip Chitale PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=14537

According to the book Core Java 1.1, Advanced Features, this is the case. The work
around suggested in the book is to use ListResourceBundle instead.

According to Sun's Bug Parade, there is a work around, of sorts. The property files
(at least as of 1.2) will support unicode characters if they are placed in the property
file using the \uXXXX notation. Not very nice.

The RFE number is 4221013


This is listed as a request for enhancement, but acting on it will be limited, based on
the comments from Sun about concerns over backwards compatibility.

Comments and alternative answers

Another way to solve this problem


Author: Phupha Punyapotasakul
(http://www.jguru.com/guru/viewbio.jsp?EID=873605), May 10, 2002
ResourceBundle rb=....;
String output=rb.getString("xxx");
try{
byte[] btmp=output.getBytes("Cp1252");
output=new String(btmp,"TIS620");
}catch(Exception e){
...........
}
As example "TIS620" is my Thai Encoding I want to change to.

property files and character encodings


Author: Andre Blum (http://www.jguru.com/guru/viewbio.jsp?EID=1045803), Jan 13,
2003
From javadoc: "The native2ascii tool can be used to convert property files to and
from other character encodings."

Use an editor to that will properly put all the escape sequences in for you.
Author: Stephen Ostermiller (http://www.jguru.com/guru/viewbio.jsp?EID=576685),
Aug 16, 2004
If you use a PropertyResourceBundle to store your translations I wrote a program that
translators can use to easily edit the strings when doing translations:
http://ostermiller.org/attesoro/

How do I delete a file / directory?


Location: http://www.jguru.com/faq/view.jsp?EID=98908
Created: Jul 9, 2000 Modified: 2001-08-18 17:44:25.046
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Use the delete() method of the File class.

How do I read text from standard input?


Location: http://www.jguru.com/faq/view.jsp?EID=98909
Created: Jul 9, 2000 Modified: 2001-08-18 17:46:05.509
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

System.in is the InputStream for standard input. The following demonstrating


reading from it a line at a time:
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(isr);
String line = null;
while ((line = reader.readLine()) != null) {
// Process line
}
Comments and alternative answers

How do I read text from standard input?


Author: ron london (http://www.jguru.com/guru/viewbio.jsp?EID=578967), Dec 10,
2001

One of the limitations of using the

read()
method with standard input
System.in
is that it waits for a new line to be entered before returning the contents of the stream.
In spite of this, it can still be useful in Java console applications.

How do I create a temporary file?


Location: http://www.jguru.com/faq/view.jsp?EID=98913
Created: Jul 9, 2000 Modified: 2000-07-09 11:02:50.687
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

To create a temporary file, use the createTempFile() method of the File class. This
allows you to set the file prefix, suffix, and directory. If no directory is specified, then
the java.io.tmpdir System property is used. To ensure the file is deleted when the
program ends (assuming normal termination), be sure to call the deleteOnExit()
method of the File object created by createTempFile().
File temp = File.createTempFile("jguru", ".tmp");
temp.deleteOnExit();
// use temp like any other File

How do I calculate the checksum of a byte array?


Location: http://www.jguru.com/faq/view.jsp?EID=99052
Created: Jul 9, 2000 Modified: 2001-08-18 17:47:01.468
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The Adler32 class in the java.util.zip package can be used to calculate the sum:
byte buffer[] = ...
ByteArrayInputStream bais = new
ByteArrayInputStream(buffer);
CheckedInputStream cis = new CheckedInputStream(bais, new
Adler32());
byte readBuffer[] = new byte[128];
while (cis.read(readBuffer) >= 0);
long value = cis.getChecksum().getValue();
Comments and alternative answers

simple md5 checksum hash code


Author: Cad Developer (http://www.jguru.com/guru/viewbio.jsp?EID=776790), Feb
28, 2002
//very simple
import java.security.*;
import java.io.*;

public class jmd5sum


{
public static void main(String []args) throws Exception {
if (args.length != 1) {
System.err.println("Usage: java jmd5sum <file>");
System.exit(1);
}

BufferedInputStream bis = new BufferedInputStream(new


FileInputStream(args[0]));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int c;
while ((c = bis.read()) > -1) {
baos.write(c);
}
bis.close();
byte[] buf = baos.toByteArray();

MessageDigest md = MessageDigest.getInstance("MD5");
md.update(buf);
byte[] digest = md.digest();

int decValue;
for (int i=0; i<digest.length; i++) {
if (digest[i] >= 0)
decValue = digest[i];
else
decValue = 256 + digest[i];

String hexVal = Integer.toHexString(decValue);


if (hexVal.length() == 1) hexVal = "0" + hexVal; //prefix a
zero to look uniformed;
System.out.print(hexVal + " ");
}
System.out.print(" "+ args[0]);
}
}

How do I write text to a file?


Location: http://www.jguru.com/faq/view.jsp?EID=100275
Created: Jul 11, 2000 Modified: 2001-08-18 17:47:30.913
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Writing text involves writing strings, so you would use a FileWriter.


FileWriter fw = new FileWriter(filename);
PrintWriter pw = new PrintWriter(fw);
pw.println("Hello, World");
pw.close();

Why do I get ??? or other dysfunctional characters on my DOS ( or other


character ) console for valid Unicode or other non-default encodings?
Location: http://www.jguru.com/faq/view.jsp?EID=102528
Created: Jul 14, 2000 Modified: 2001-08-20 19:55:52.896
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Jacky Chan
(http://www.jguru.com/guru/viewbio.jsp?EID=91603

PrintStream (aka System.out) trims off the high-order byte.

How do I copy a file?


Location: http://www.jguru.com/faq/view.jsp?EID=104197
Created: Jul 17, 2000 Modified: 2000-07-17 15:10:33.984
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by christian breu
(http://www.jguru.com/guru/viewbio.jsp?EID=103500

To make a copy of a file, open the source file as a FileInputStream. Open the
destination as a FileOutputStream. As you read a byte from the input, write it to the
output. There is no built-in method to make a file copy for you.
Comments and alternative answers

Here's an excellent reference from the Java Tutorial:...


Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362), Aug
21, 2000
Here's an excellent reference from the Java Tutorial: How to Use File Streams.

Here is how to do it:


Author: Ali Haj (http://www.jguru.com/guru/viewbio.jsp?EID=711559), Feb 20, 2002

//code for copying files:

String sourceFileAddress;

//You can give the address of the source file as a string

String destinationFileAddress;

//Address of the destination file as a string

try{

java.io.FileInputStream SourceFile=new
java.io.FileInputStream(sourceFileAddress);

java.io.FileOutputStream DestinationFile=new java.io.FileOutputStream


(destinationFileAddress);
byte readFromFile[]=new byte[SourceFile.available()];

//This is an array which contains the number of bytes that are


available in the source file. So if you want to read a part of the
source file (less memory usage when copying) you can change the
option SourceFile.available() to any number you want.

SourceFile.read(readFromFile);

//This reads the number of bytes specified above from the file(i.e
from byte number 0 to byte number readFromFile).Be careful with this,
if you try to read a huge amount of bytes into ram you will run out
of memory so be diplomatic with it, read small chunks.

DestinationFile.write(readFromFile);

//This writes all the things that you have read from your source
file.If you want to write the file in small chunks, you can do this
by putting this or part of this code into some sort of loop.

SourceFile.close();

//Let the file go.

DestinationFile.close();

//Let the file go.

}catch(Exception e)

//Happy copying

// I will be grateful if you comment on this code an the way it is


presented.You can sent this(if you feel like it :) ) to :
ali@alireza8.8m.com

Re: Here is how to do it:


Author: Samson Koletkar (http://www.jguru.com/guru/viewbio.jsp?EID=882104),
May 31, 2002
Hi Ali, I have a small qs about the file copying process.
Say I have a file "data.csv" arriving in directory "c:\indir" which i want to upload
into database. now this file is updated at regular intervals thruout the day (it grows
everytime its updated). i have to keep polling for any updates & upload the newly
added data at the end of the file.
My qs is: The upload of data from data.csv to database will take sometime. If the
updated file arrives in this time, what would happen...will the File object in java
read the new file contents ? Should i rather create a copy of the file as soon as i
read it & then upload from the temp copy ? What happens if while creating the
temp copy the original file is updated ?

In short what would happen if i was reading the file & it was to be updated. The
update happens because of ftp or remote copy. that is the file comes from some
other machine.
Hope my qs is clear enuff.

Re[2]: Here is how to do it:


Author: Ali Haj (http://www.jguru.com/guru/viewbio.jsp?EID=711559), May
31, 2002
Samson, When you open a file stream, it locks the file so it cannot be deleted
or modified. After you have finished working(reading/writing) with your file,
you close the stream and free the resources assigned to the file by *.close();
After this, the file can be modified. However, to be on the safe side you can
change file permissions using FilePermission class documented in java's api
documentation or just set your file as read only: *.readOnly();. If you are
developing a commercial application, you will have to experiment with this
method before you deploy it!

Re[3]: Here is how to do it:


Author: Samson Koletkar
(http://www.jguru.com/guru/viewbio.jsp?EID=882104), May 31, 2002
thanx for your quick response Ali. i still have the doubt - what happens in
case i make the file read only & the new file arrives & tries to overwrite ? It
will fail i suppose. in that case that updated file is lost.

What is the quickest way to create a copy of the file in another temp dir so
that the original file can be overwritten while i am working on the temp copy.
the thing is - the file could be overwritten while i am creating the temp file
using Reader/Writer.

Re[4]: Here is how to do it:


Author: Ali Haj (http://www.jguru.com/guru/viewbio.jsp?EID=711559),
May 31, 2002
When reading bytes from your file into an array, you can read the whole
file into it(provided you have enough memory). This is the quickest
way.the method that I explained reads the whole file into memory. You
can put the source.close(); bit immidiately after you have read it i.e after
sourceFile.read(....); then you can happily modify your file and have a
copy of the file into your memory which you can immidiatly dump into
a file on your disk. But being unable to write on the file that is being
worked with is inevetable. I have given you the quickest way(i hope).
Let me know how u r getting on. Ali

Re[5]: Here is how to do it:


Author: Samson Koletkar
(http://www.jguru.com/guru/viewbio.jsp?EID=882104), May 31,
2002
Thanx again Ali, for confirming the fact that there is no way to avoid
the "overlap" situation. I am trying to think of alternatives. Will
surely update you if i find one.

As for now, the file sizes i get are pretty negotiable for one shot read.
I could also read the file in (not too)large chunks.

Thanx once again !

Re[6]: Here is how to do it:


Author: John Zukowski
(http://www.jguru.com/guru/viewbio.jsp?EID=7), May 31, 2002
To avoid the overlap you need to install a monitor that accepts
the requests, vs. the direct writing to directory.

Re[7]: Here is how to do it:


Author: Samson Koletkar
(http://www.jguru.com/guru/viewbio.jsp?EID=882104), May 31,
2002
Hello John

Can you throw some more light on this ??? Any references /
articles / explanation...highly appreciated.

Sam

Re[8]: Here is how to do it:


Author: John Zukowski
(http://www.jguru.com/guru/viewbio.jsp?EID=7), May 31,
2002
Think of what a web server does. Instead of sending back an
HTML response, all you have to do is send back an ACK or
not, depending upon the success of the save.

Request 1 - save file


Request 2 - move file
Don't let move happen while saving and don't let save
happen while moving.

What is a stream?
Location: http://www.jguru.com/faq/view.jsp?EID=105982
Created: Jul 19, 2000 Modified: 2000-07-19 14:58:14.41
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Ninad Naik
(http://www.jguru.com/guru/viewbio.jsp?EID=82006

Basically, a stream is an ordered look at a sequence of bytes for input or output.

Low-level streams provide direct access to the underlying bytes, like a


FileInputStream, FileOutputStream, or CharArrayWriter, where reading and writing
work directly with the underlying input/output device. High-level streams, or filters,
instead build upon the low-level streams to provide additional capabilities, like
buffering, counting lines, compressing data, or reading/writing higher-level data
members like primitives or objects. You can chain multiple filters together to get
multiple higher-level operations on a single low-level stream.

Comments and alternative answers

A stream is an absraction that either produces or ...


Author: Rahul Bindu (http://www.jguru.com/guru/viewbio.jsp?EID=102204), Jul 20,
2000
A stream is an absraction that either produces or consumes information. A stream is
linked to a physical device by the Java I/O system. All the streams behave in the same
manner, even if the actual physical devices to which they are linked differ. Thus the
same I/O clasess and methods can be applied to any type of device. This means that
an input stream can abstract many diffrent kinds of input: from a disk file, a keyboard
or a network socket. Likewise is the output stream which abstracts diffrent kinds of
output types.

Streams are a clear way to deal with input/output without having to every part of your
code understand the diffrence between a keyboard and a network socket.

How can I open the same file for reading as well as writing?
Location: http://www.jguru.com/faq/view.jsp?EID=107894
Created: Jul 21, 2000 Modified: 2000-07-21 09:15:39.33
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Arun Bharathan
(http://www.jguru.com/guru/viewbio.jsp?EID=106958

The RandomAccessFile class supports simultanous reading and writing from the same
file. Just open it in "rw" mode:
RandomAccessFile raf =
new RandomAccessFile("filename.txt", "rw");
Use skipBytes() to move to where you wish to read/write.
Comments and alternative answers

How to overwrite certain keywords without overwriting text that follows?


Author: Suyog Mody (http://www.jguru.com/guru/viewbio.jsp?EID=908760), Jun 10,
2002
I tried using RandomAccessFile for reading and writing to the same file. What I need
to do is the following-
I have a test.txt file which has the following text-
abcd testtest $$testtest$$ abcd
ascdsldkfsdf $$testtest$$ aslkdjfsa
and so on...
I need to replace all occurences of $$testtest$$ in test.txt with some string that I have
a handle to (for eg, C:\documents and settings\my docs\something).

But when I try this using skipBytes & writeBytes from RandomAccessFile, what
happens is that it overwrites the text following $$testtest$$ so I get a output file like-
abcd testtest C:\documents and settings\my docs\something
ascdsldkfsdf C:\documents and settings\my docs\something
So, I have lost my abcd (1st line) and aslkdjfsa (2nd line) which I need to preserve.
Please help.
Thanks,
Suyog

Re: How to overwrite certain keywords without overwriting text that follows?
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Jun 10,
2002
Don't use RandomAccessFile then... it physically replacing the bytes. If you need
to replace difference lengths of text, you need to read bytes/strings and write to a
different file/output stream.

What does UTF stand for?


Location: http://www.jguru.com/faq/view.jsp?EID=109600
Created: Jul 24, 2000 Modified: 2001-08-18 17:51:46.335
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

UTF stands for UCS Transformation Format, where UCS stands for Universal
Character Set.
Comments and alternative answers

It is related to Unicode character set. It is used...


Author: shivashis bose (http://www.jguru.com/guru/viewbio.jsp?EID=79345), Jul 24,
2000
It is related to Unicode character set. It is used by Java. The major advantage is that
unlike ASCII it can store a huge number and type of characters.

Multilingual support in Java is posible due to it's built in support for Unicode.

It has been calculated that there are still thousands of characters which can be used for
new languages.

How can I read an entry from a jar file?


Location: http://www.jguru.com/faq/view.jsp?EID=109781
Created: Jul 24, 2000 Modified: 2001-08-27 07:49:42.856
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by ivan tzilev (http://www.jguru.com/guru/viewbio.jsp?EID=88883

Basically, open the .jar file, find the entry you want, then read it:
JarFile jar = new JarFile(jarfile);
ZipEntry entry = jar.getEntry(entryname);
InputStream is = jar.getInputStream(entry);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}

How do I list all drives/filesystem roots on my system?


Location: http://www.jguru.com/faq/view.jsp?EID=110867
Created: Jul 25, 2000 Modified: 2001-08-18 17:54:08.862
Author: Davanum Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=2011)

The listRoots() method of the File class was introduced with the 1.2 release for this:
File[] roots = File.listRoots();
for(int i=0;i<roots.length;i++)
System.out.println("Root["+i+"]:" + roots[i]);
Comments and alternative answers

Problems with this method under Windows


Author: Steven de Jong (http://www.jguru.com/guru/viewbio.jsp?EID=1220556), Jan
11, 2005

However, listRoots does not work well in Windows; it tries to access the A: drive, and
you actually get an error message dialog if there is no diskette in it. Whatever you
click in this dialog, the method throws an exception afterwards. So, actually the
listRoots method is rather useless.

In other words, an other method than the one described is needed. Does anyone know
of such a method?

Have a look here


Author: Arjuna Vijayanayagam
(http://www.jguru.com/guru/viewbio.jsp?EID=1222201), Jan 19, 2005
http://forums.devshed.com/showthread.php?mode=hybrid&t=97538

Where can I find Java packages for expressing numerical formulas?


Location: http://www.jguru.com/faq/view.jsp?EID=111171
Created: Jul 25, 2000 Modified: 2000-07-25 22:00:45.603
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by ds you (http://www.jguru.com/guru/viewbio.jsp?EID=32792

Colt offers, among others, efficient and usable data structures and algorithms for
Off-line and On-line Data Analysis, Linear Algebra, Multi-dimensional arrays,
Statistics, Histogramming, Monte Carlo Simulation, Parallel & Concurrent
Programming.

How to insert content into the middle of a file without overwriting the
existing content?
Location: http://www.jguru.com/faq/view.jsp?EID=111652
Created: Jul 26, 2000 Modified: 2000-07-26 07:35:09.048
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by penta java
(http://www.jguru.com/guru/viewbio.jsp?EID=111346

There is no direct support for inserting content in the middle of a file/stream. What
you need to do is copy the original content into another file/stream with the new
content added where necessary.

How can I use Runtime.exec() to run MS-DOS commands without having MS-
DOS shells popup each time?
Location: http://www.jguru.com/faq/view.jsp?EID=118872
Created: Aug 3, 2000 Modified: 2001-08-18 17:56:00.49
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Rhyd Lewis
(http://www.jguru.com/guru/viewbio.jsp?EID=103722

The following demonstrates executing a command without bringing up a popup.


import java.io.*;

public class Test {


public static void main (String args[]) throws
IOException {
String[] command = {
"C:\\winnt\\system32\\cmd.exe", "/y", "/c",
"dir"};
Process p = Runtime.getRuntime().exec(command);
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
However....

According to bug number 4244515 in Sun's Bug Parade


(http://developer.java.sun.com/developer/bugParade/bugs/4244515.html), javaw
doesn't always work without bringing up new window.

How do I read input from a stream "one word at a time"?


Location: http://www.jguru.com/faq/view.jsp?EID=121065
Created: Aug 7, 2000 Modified: 2001-08-18 17:57:08.874
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Muhammad Qureshi
(http://www.jguru.com/guru/viewbio.jsp?EID=87763

What you need to do is use the java.util.StringTokenizer or


java.io.StreamTokenizer to parse your input into words. Each has a default set of
delimiters like white space that can be changed. The following demonstrates the
using of StringTokenizer to count words in a file.
import java.io.*;
import java.util.*;

public class Test {


static final Integer ONE = new Integer(1);

public static void main (String args[])


throws IOException {

Map map = new TreeMap();


FileReader fr = new FileReader(args[0]);
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
processLine(line, map);
}
printMap(map);
}
static void processLine(String line, Map map) {
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
addWord(map, st.nextToken());
}
}
static void addWord(Map map, String word) {
Object obj = map.get(word);
if (obj == null) {
map.put(word, ONE);
} else {
int i = ((Integer)obj).intValue() + 1;
map.put(word, new Integer(i));
}
}
static void printMap(Map map) {
Set set = map.entrySet();
Iterator it = set.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
System.out.println(entry.getKey() +
": " + entry.getValue());
}
}
}

What is the difference between the stream tokenizer and string tokenizer?
Location: http://www.jguru.com/faq/view.jsp?EID=124856
Created: Aug 11, 2000 Modified: 2001-08-18 17:57:39.167
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by SREEDHAR REDDY
(http://www.jguru.com/guru/viewbio.jsp?EID=111571

You can think of the StringTokenizer as a specialized form of StreamTokenizer,


where each token that is returned is a String. Depending upon what you want to do
with the resultant tokens and/or how complex of a parse job you want to deal with
lets you decide which to use.

The StringTokenizer parses a string into a series of tokens. It is then your


responsibility to figure out what each token returned is, beyond the definition of a
token separated by delimiters. Usually, you just treat things as words when using
StringTokenizer.

On the other hand, a StreamTokenizer allows you to ask is the next token a number,
word, quoted string, end-of-file, end-of-line, comment, or whitespace. In this case,
the StreamTokenizer is smarter, though can be considerably harder to use.

See How do I work with the StreamTokenizer to get number and word tokens from
a file? and How do I read input from a stream "one word at a time"? for how they
might do similar tasks.

How can I reuse a StringWriter by flushing out its internal buffer? flush()
doesn't seem to do it and I'd like to avoid recreating the object many times.
Location: http://www.jguru.com/faq/view.jsp?EID=125611
Created: Aug 13, 2000 Modified: 2000-08-13 09:24:54.371
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Michael Peter
(http://www.jguru.com/guru/viewbio.jsp?EID=125503

To reuse a StringWriter you need to empty out the internal buffer. The way to do this
is to get the buffer with getBuffer() and set its length to zero:
StringWriter sw = ...
// use it
StringBuffer buf = sw.getBuffer();
buf.setLength(0);
// reuse it
As far as what the purpose of the flush() method is, its clearer if you think of it with
something like a BufferedWriter. If you flush() the BufferedWriter, the internal buffer
used by the BufferedWriter is flushed. This doesn't clear out the final destination of
what the BufferedWriter is attached to. So, in the case of a StringWriter, if it were to
use any internal buffering before writing to the StringBuffer, that is what would be
flushed. Since the StringWriter doesn't use any internal buffering, directly writing to
the StringBuffer, the flush() method effectively does nothing.
Comments and alternative answers

StringBuffer reuse as well:


Author: Craig Waterman (http://www.jguru.com/guru/viewbio.jsp?EID=740406), Jan
30, 2002
Incidentally, this is the exact method for reusing a standalone StringBuffer.
Remember, setting the buffer to null destroys the object. using setLength(0) resets
the buffer itself and allows the object to be reused.

How do I get the creation date and time of a file?


Location: http://www.jguru.com/faq/view.jsp?EID=132319
Created: Aug 22, 2000 Modified: 2001-08-18 17:58:39.434
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Neerav Koranne
(http://www.jguru.com/guru/viewbio.jsp?EID=132110

There is no support for getting the creation date and time of a file from Java. All you
can get is when the file was last modified, with the the lastModified() method of File.
Comments and alternative answers

Why?
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jan 10, 2002
Is there any way to get the file create date information from Java? What were they
thinking by leaving it out?

See also:

In File I didn't find a method to get date of file created

Retrieve file's timestamp

How can I parse an HTML page to capture a URL returned from, e.g., a
search engine?
Location: http://www.jguru.com/faq/view.jsp?EID=134999
Created: Aug 25, 2000 Modified: 2001-08-18 17:59:34.98
Author: Davanum Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=2011)
Question originally posed by Sharriff Aina
(http://www.jguru.com/guru/viewbio.jsp?EID=122696

Sun has an good article (with sources) at:

Writing a Web Crawler in the Java Programming Language

Comments and alternative answers


Also, before you start to parse a possibly messy HTML...
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Oct 9, 2000
Also, before you start to parse a possibly messy HTML file, you may want to clean it
up. HTMLTidy would help. Unfortunately, Andy decided not to keep maintaining the
Java version. See http://www3.sympatico.ca/ac.quick/

Where can I find code for converting Java data types to/from other data
formats such as: EBCDIC, IBM370 COMP (binary numbers up to 9 digits),
and COMP-16 (packed decimal numbers)?
Location: http://www.jguru.com/faq/view.jsp?EID=135894
Created: Aug 27, 2000 Modified: 2001-08-18 18:00:02.514
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537)
Question originally posed by claire kennedy
(http://www.jguru.com/guru/viewbio.jsp?EID=128156

You will have to use the java.io.InputStreamReader class. This can convert data in
any encoding to Unicode as long as the right ByteToCharConvertor is available. Here
are the supported encodings and some more info on Character Stream I/O.

How do I know that a particular file is in binary or text format without


relying on the extention of a file?
Location: http://www.jguru.com/faq/view.jsp?EID=135905
Created: Aug 27, 2000 Modified: 2001-08-18 18:00:46.152
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Jigar Shah
(http://www.jguru.com/guru/viewbio.jsp?EID=119342

Basically, you guess by reading the first few bytes of the file. Most binary file formats
have a hardcoded constant there, called a magic number. As long as you have a
complete list of magic numbers for the possible binary file formats you might come
across, you can try your best to determine if something is binary / text. For instance,
all Java class files start with 0xCAFEBABE.

How do I convert a String from Unicode to another encoding and vice versa?

Location: http://www.jguru.com/faq/view.jsp?EID=137049
Created: Aug 28, 2000 Modified: 2001-08-18 18:01:22.246
Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)
Question originally posed by Alexey Lonshakov
(http://www.jguru.com/guru/viewbio.jsp?EID=10550

The basic answer is to use one of the two String constructors that use an encoding
argument: String(byte[] bytes, int offset, int length, String enc) or String(byte[]
bytes, String enc). Because the encoding is internal and, generally, an encoding
translation takes place when writing to most output devices/peripherals/streams, it is
difficult to show the results directly. I have included some code that indirectly, via
getBytes(String enc), attempts to show what happens using UTF-16 ( Big Endian
Unicode, ) the platform default encoding and UTF-8. The base String contains "Enc"
plus the Japanese ideograph "go" or 5. In all cases, on English NT 4.0, the string
prints as "Enc?" - with the famous question mark, but the actual byte variation is
shown except in the platform default case where 3F ( = '?' ) displays. You can easily
change the String contents and encodings to determine other outputs on your
platform. See: character encoding and Supported Encodings. Note that only a few
encodings are supported if you don't have the international version of the JDK/JRE.

import java.io.*;

public class EncString


{
public static void main(String[] args)
{
byte[] bRay = null;
char quote = '"';
int ndx;
String sInitial = "Enc" + "\u4E94";

try { bRay = sInitial.getBytes("UTF-16"); }


catch( UnsupportedEncodingException uee )
{
System.out.println( "Exception: " + uee);
}

System.out.println( quote + sInitial + quote +


" String as UTF-16, " +
"bRay length: " + bRay.length + "." );
for( ndx = 0; ndx < bRay.length; ndx++ )
{
System.out.print( Integer.toHexString( bRay[
ndx++ ] ) + " " );
System.out.print( Integer.toHexString( bRay[
ndx ] ) + " " );
}

System.out.println("\n");

OutputStreamWriter osw = new OutputStreamWriter(


System.out );

bRay = sInitial.getBytes();
System.out.println( quote + sInitial + quote +
" String as platform default - " +
osw.getEncoding() +
", bRay length: " + bRay.length + "." );
for( ndx = 0; ndx < bRay.length; ndx++ )
{
System.out.print( Integer.toHexString( bRay[
ndx ] ) + " " );
}
System.out.println("\n");

try
{
sInitial = new String( sInitial.getBytes("UTF-8"),
"UTF-8");
bRay = sInitial.getBytes("UTF-8");
}
catch( UnsupportedEncodingException uee )
{
System.out.println( "Exception: " + uee);
}

System.out.println( quote + sInitial + quote +


" String as UTF-8, " +
"bRay length: " + bRay.length + "." );

for( ndx = 0; ndx < bRay.length; ndx++ )


{
System.out.print( Integer.toHexString( bRay[
ndx ] ) + " " );
}

}
} // End class EncString

Comments and alternative answers

Here is the answer according to Hans Bergsten from...


Author: Jonathan Asbell (http://www.jguru.com/guru/viewbio.jsp?EID=90272), Mar
8, 2001
Here is the answer according to Hans Bergsten from Gefion Software
http://www.gefionsoftware.com Author of JavaServer Pages (O'Reilly)
(Also I would like to thank him as he has been very generous in taking the time to
help me reslove this problem)

When a browser sends a parameter in some encoding, such as UTF-8, it encodes each
character byte value as a hexadecimal string using the encoding for the page (e.g.
UTF-8). At the server, however, the part of the container that interprets these
character values always assumes they are 8859-1 byte values. So it created a
Unicode string based on the byte values interpreted as 8859-1. Since the 8859-1
assumption is made by the container, this hack (read "fix") works independently
from which platform you run it on.

In the Servlet 2.2 API, the methods that parse parameter input always assume
that it's sent as ISO 8859-1 (i.e. getParameter() et al). so they create a String
containing the correct bytes but incorrect charset.

If you know what the charset is, you can convert the bytes to a string using the correct
charset:

new String(value.getBytes("8859_1"), "utf-8")

8859-1 is the default encoding of HTTP.

Convert HTML-Form Input from/to UTF-8 encoded Pages


Author: Michael Hauser (http://www.jguru.com/guru/viewbio.jsp?EID=940623), Jul
8, 2002

Maybe those two static methods are helpful for U.


/* convert from UTF-8 encoded HTML-Pages -> internal Java String
Format */
public static String convertFromUTF8(String s) {
String out = null;
try {
out = new String(s.getBytes("ISO-8859-1"), "UTF-8");
} catch (java.io.UnsupportedEncodingException e) {
return null;
}
return out;
}

/* convert from internal Java String Format -> UTF-8 encoded


HTML/JSP-Pages */
public static String convertToUTF8(String s) {
String out = null;
try {
out = new String(s.getBytes("UTF-8"));
} catch (java.io.UnsupportedEncodingException e) {
return null;
}
return out;
}

Re: Convert HTML-Form Input from/to UTF-8 encoded Pages


Author: eswara prasadh (http://www.jguru.com/guru/viewbio.jsp?EID=1194133),
Aug 30, 2004

few questions on encoding


1)on the same lines can we converted Shift-JIS to/from utf-8?

2)will the special characters appear without corruption?

thanks in advance,
eswar

I understood that Java always uses Big Endian. Why does the code at How
can I store and retrieve Unicode or Double Byte data in a file using the
java.io libraries? produce Little Endian output?
Location: http://www.jguru.com/faq/view.jsp?EID=137110
Created: Aug 28, 2000 Modified: 2001-08-18 18:02:32.258
Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

Actually, Java's guaranteed usage of Big Endian only applies to what I will loosely call
"numbers." String or byte encodings for characters are a different matter altogether.
The Little Endian output in the referenced code results from Java's interpretation of
the "Unicode" alias, which on NT, at least, apparently resolves to "UnicodeLittle." This
is not a problem in the code, because a byte order mark is written, but it would have
been better to use an encoding from character encoding or Supported Encodings.

How do I read a file created by program X in Java?


Location: http://www.jguru.com/faq/view.jsp?EID=139294
Created: Aug 31, 2000 Modified: 2000-08-31 11:27:52.321
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

There is no magic in Java that lets it automatically know how to read files created by
other programs. Basically, find a definition of what the format is, then read the file
in. It is your job to read in the file according to the format documentation you've
found. You'll have to worry about things like endian order for numerics, character
size, and versioning, as file formats tend to change between versions of the program.

Lots of times, other programs support exporting of data to a format that Java does
support, usually through an ODBC driver.

How can you combine multiple input streams to be treated as one?


Location: http://www.jguru.com/faq/view.jsp?EID=141158
Created: Sep 3, 2000 Modified: 2000-09-03 21:59:33.184
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
The SequenceInputStream class in the standard java.io package allows you to
combine multiple input streams into one. You can either create a vector of streams,
passing the elements() to the constructor, or combine two directly in a constructor.

How can I detect if there is a CD in the CD-ROM drive using Java?


Location: http://www.jguru.com/faq/view.jsp?EID=142062
Created: Sep 5, 2000 Modified: 2001-08-18 18:03:52.739
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by sundarv varadarajan
(http://www.jguru.com/guru/viewbio.jsp?EID=29816

There is no support for this built into Java. The best you can do is create a C/C++
program/routine and use JNI to test.
Comments and alternative answers

There is a simpler, though less rigorous, way to do...


Author: Jon Wingfield (http://www.jguru.com/guru/viewbio.jsp?EID=41079), Sep 5,
2000
There is a simpler, though less rigorous, way to do this. Given the assumption that the
FilePermission to read the CD-ROM drive has been granted, the File class method
call canRead() will return true if a CD (data or audio) is in the drive and false
otherwise. Below is code for a CD-ROM drive mapped to a Win32 d: drive:
File f = new File("d:\\");
boolean cdInDrive = false;
try {
cdInDrive = f.canRead();
} catch (SecurityException se) {
}
System.out.println((cdInDrive ? "Can " : "Can't ") + "read data in
drive " + f);
FAQ Manager note: This assumes you know the proper device/drive, which isn't
always the case.

How can I rename a file?


Location: http://www.jguru.com/faq/view.jsp?EID=142111
Created: Sep 5, 2000 Modified: 2001-08-18 18:07:31.398
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Mohamed Abu Zur
(http://www.jguru.com/guru/viewbio.jsp?EID=103782

The File class has a renameTo() method that allows you to rename files, just pass in
an argument of the new name as a File object. A boolean status is returned to report
success or failure.

How can I start reading a file near the end, and not have to read all the
bytes at the start too?
Location: http://www.jguru.com/faq/view.jsp?EID=142234
Created: Sep 5, 2000 Modified: 2000-09-05 08:25:32.422
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Jim Brady
(http://www.jguru.com/guru/viewbio.jsp?EID=142177

The RandomAccessFile class allows you to seek() to a certain position in a file and
read from any spot in the file. Unfortunately, the class isn't part of the IO streams
hierarchies, so you can't do things like buffering.

When do you use the Reader/Writer classes, instead of the


InputStream/OutputStream classes?
Location: http://www.jguru.com/faq/view.jsp?EID=143411
Created: Sep 6, 2000 Modified: 2000-09-06 12:38:00.754
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Kedar Aras
(http://www.jguru.com/guru/viewbio.jsp?EID=80325

The InputStream/OutputStream classes are for reading and writing bytes, while the
Reader/Writer classes are for reading characters / text. If you need to process text,
you use Reader/Writer. If you need to process content at the byte level, either as the
raw bytes, or as higher level data like primitives (through DataInput/Output), objects
(through ObjectInput/Output), or possibly compressed data (GZIPInput/Output),
then you would work with an InputStrem/OutputStream.

How do I set the current working directory to a particular directory, such


that subsequent file opens only need to only use relative file paths?
Location: http://www.jguru.com/faq/view.jsp?EID=203366
Created: Sep 12, 2000 Modified: 2001-08-18 18:59:20.029
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Charles Chen
(http://www.jguru.com/guru/viewbio.jsp?EID=137374

I seem to recall a time where setting the user.dir System property did this for you.
However, that doesn't seem to work any more (if it ever did). There is no standard
way to do this, like a method of the File class or some such. The best you can do is
to create a File object for the new "root" directory, then create new File objects
passing this as the parameter to it:
File root = new File("/foo/bar");
File real = new File(root, "real");
Also, according to David Rees:

Note that setting the "user.dir" in Java doesn't change the working directory - it only
seems to ;). All it really does is update the path that the methods getAbsolute* and
getCanonical* work relative to.

For instance if you start a program in Java in the directory c:\dir1 you will get the
following:

java.io.File aFile;
aFile = new java.io.File("test.txt");
aFile.getAbsolutePath(); // value is c:\temp\test.txt
aFile.createNewFile(); // creates c"\temp\test.txt
System.setProperty("user.dir","c:\\other");
aFile.getAbsolutePath(); // value is c:\other\test.txt
aFile = new java.io.File("test2.txt");
aFile.getAbsolutePath(); // value is c:\other\test2.txt
aFile.createNewFile(); // creates c:\temp\test.txt

There is a RFE for this in with Sun 4045688.

Generally I would suggest avoiding relative file creations - always use File(X,path).
Otherwise a user or other code changing user.dir can break things.

Comments and alternative answers

Unfortunately this is almost impossible when working...


Author: Charles Chen (http://www.jguru.com/guru/viewbio.jsp?EID=137374), Sep
13, 2000
Unfortunately this is almost impossible when working with some other people's
legacy codes.

Someone else also sugguested to me the system property user.dir. I haven't try it yet.
Could you tell me a bit more why you think it is not working any more? If true, since
when? JDK 1.2.2?

[FAQ Manager: I just tested under 1.1.8, 1.2.2, and 1.3 and had no luck. Either it was
way back in the 1.0.2 days or it never worked.]

How can I read or write binary files written in little-endian format?


Location: http://www.jguru.com/faq/view.jsp?EID=205923
Created: Sep 14, 2000 Modified: 2000-10-14 10:57:16.689
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by man sung jun
(http://www.jguru.com/guru/viewbio.jsp?EID=200638

In order to read multi-byte values, where you know the byte order is not in the Java
standard big-endian format, you basically need to read the individual bytes yourself
and rearrange them. For instance, the following will read in a 4 byte int and swap the
byte order around.
// read four bytes
int b1 = is.read();
int b2 = is.read();
int b3 = is.read();
int b4 = is.read();
// combine them
int combined = (b4 && 0xFF) << 24 +
(b3 && 0xFF) << 16 +
(b2 && 0xFF) << 8) +
(b1 && 0xFF);
When working with floating point numbers, the Float.floatToIntBits() and
Float.intBitsToFloat() methods may prove helpful.
Writing is just doing things in the opposite order, splitting apart the int first, then
writing the individual pieces.

How can I make a file writable that is currently read-only?


Location: http://www.jguru.com/faq/view.jsp?EID=211342
Created: Sep 20, 2000 Modified: 2000-09-20 14:02:03.696
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Simon English
(http://www.jguru.com/guru/viewbio.jsp?EID=209980

There is only support in Java to make a writable file read-only. There is no way to go
the other way. I guess someone considered this a security risk so didn't add an
appropriate API to perform.

How to uncompress .Z files 'compress'ed in Unix from Java where the


system might not be Unix?
Location: http://www.jguru.com/faq/view.jsp?EID=212264
Created: Sep 21, 2000 Modified: 2001-08-18 18:17:35.617
Author: Jesper Andersen (http://www.jguru.com/guru/viewbio.jsp?EID=142807)
Question originally posed by Jun Qian
(http://www.jguru.com/guru/viewbio.jsp?EID=90232

I'm going to completely plagiarize Marco Schmidt here and say that your best bet is
to make a system call to an existing utility of your choice or to implement the LZW
algorithm on your own in java (an unattractive task I assume). I too failed to find
any existing Java package to accomplish this. The good news is that if you can live
with the copyright conditions, GNUzip actually does do this, so you could port the
code to Java from that code base fairly easily, I think. But then you would have GPL'd
code, which may be a problem.
Comments and alternative answers

How to uncompress .Z files 'compress'ed in Unix from Java where the system
might not be Unix?
Author: frederic jaar (http://www.jguru.com/guru/viewbio.jsp?EID=1166281), Apr
27, 2004
Hello, Today I have the same problem, I found a LZW.java class to compress and
uncompress files. But It doesn't run with a Unix compressed file .Z. Jesper, do you
have a solution ? Thanks for your help

Re: How to uncompress .Z files 'compress'ed in Unix from Java where the system might not be U
Author: G F (http://www.jguru.com/guru/viewbio.jsp?EID=1216763), Dec 16, 2004
Try this URL:
http://cvs.sf.net/viewcvs.py/skunkdav/skunkdav/HTTPClient/UncompressInputStream.java?sortby=au

How do I communicate with a USB port from Java?


Location: http://www.jguru.com/faq/view.jsp?EID=212301
Created: Sep 21, 2000 Modified: 2000-09-21 12:46:09.437
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Short of writing a JNI library, there is no support for this from Java at this time. You
can watch JSR 000080 to see if / when it becomes real.

How can I find out if a file is a text/ASCII file or binary file using Java?
Location: http://www.jguru.com/faq/view.jsp?EID=214380
Created: Sep 24, 2000 Modified: 2001-08-18 18:19:18.169
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Abdul Aleem
(http://www.jguru.com/guru/viewbio.jsp?EID=114306

There is no easy way to tell since ASCII characters are binary. Depending upon how
you read the file determines how you treat the data. For instance, the text "CAFE" if
read as an int is the value 1128351301. Since Java also deals with Unicode and not
just ASCII, you get to worry about 8-bit vs. 16-bit characters, too.

See also How do I know that a particular file is in binary ...

How do I create a checksum for a file?


Location: http://www.jguru.com/faq/view.jsp?EID=216274
Created: Sep 26, 2000 Modified: 2001-08-18 18:21:07.061
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by h s (http://www.jguru.com/guru/viewbio.jsp?EID=129524

Java has two stream classes which may be used to calculate checksums:
java.util.zip.CheckedInputStream and java.util.zip.CheckedOutputStream.
Both of these streams require a constructor argument, of type
java.util.zip.Checksum, which is used to specify the checksum algorithm. Two
algorithm implementations, Adler32 and CRC32, are provided in the java.util.zip
package, or you may implement the Checksum interface for your own algorithm.

Here's a short example of how to calculate the checksum for a file (specified by a
command-line argument), using the CRC32 algorithm:

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

import java.util.zip.Checksum;
import java.util.zip.CheckedInputStream;
import java.util.zip.CRC32;

public class checksum {

public static void main(String[] args)


throws IOException {

FileInputStream file = new FileInputStream(args[0]);


CheckedInputStream check =
new CheckedInputStream(file, new CRC32());
BufferedInputStream in =
new BufferedInputStream(check);
while (in.read() != -1) {
// Read file in completely
}
System.out.println("Checksum is " +
check.getChecksum().getValue());
}
}
Comments and alternative answers

simple check sum code


Author: Cad Developer (http://www.jguru.com/guru/viewbio.jsp?EID=776790), Feb
28, 2002
import java.security.*;
import java.io.*;

public class jmd5sum


{
public static void main(String []args) throws Exception {
if (args.length != 1) {
System.err.println("Usage: java jmd5sum <file>");
System.exit(1);
}

BufferedInputStream bis = new BufferedInputStream(new


FileInputStream(args[0]));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int c;
while ((c = bis.read()) > -1) {
baos.write(c);
}
bis.close();
byte[] buf = baos.toByteArray();

MessageDigest md = MessageDigest.getInstance("MD5");
md.update(buf);
byte[] digest = md.digest();

int decValue;
for (int i=0; i<digest.length; i++) {
if (digest[i] >= 0)
decValue = digest[i];
else
decValue = 256 + digest[i];

String hexVal = Integer.toHexString(decValue);


if (hexVal.length() == 1) hexVal = "0" + hexVal; //prefix a
zero to look uniformed;
System.out.print(hexVal + " ");
}
System.out.print(" "+ args[0]);
}
}

How do I remove all the content/information in a file?


Location: http://www.jguru.com/faq/view.jsp?EID=220040
Created: Oct 1, 2000 Modified: 2001-08-18 18:21:44.883
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Mark Webb
(http://www.jguru.com/guru/viewbio.jsp?EID=80178

You can change the file length by calling the setLength() method of
RandomAccessFile. Setting the length to zero will effectively free up the rest of the
file content.

How can I do non-blocking I/O in Java?


Location: http://www.jguru.com/faq/view.jsp?EID=225489
Created: Oct 9, 2000 Modified: 2001-08-18 18:23:37.302
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Using the standard, core Java I/O libraries, you can't. The basic idea there is to use
separate threads. Note that there is a JSR in the works that will hopefully add both
asynchronous and bulk I/O operations.

In the meantime, if you really do need to do non-blocking I/O, you can write it
yourself using JNI or use/port a JNI-based wrapper like Mat Welsh's NBIO:
Nonblocking I/O for Java package.

See the java.nio.channels package of Java 1.4 for support in 1.4.

Why can't I use the '\u000a' and '\u000d' Unicode character literals in Java
source code?
Location: http://www.jguru.com/faq/view.jsp?EID=225894
Created: Oct 10, 2000 Modified: 2002-03-25 12:14:31.915
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

This is an unfortunate artifact of the ordering of the processing of the Java source file
into lexemes and tokens by the compiler. Instead, you should use the equivalent
character escape sequences: '\n' and '\r'.

Also see What character escape sequences are available in Java?

For the full scoop on the order of processing, see chapter 3 of the JLS v2 (particularly
3.10.4, 3.2, and 3.3).

How can I trap system-specific key sequences like Ctrl-Alt-Del?


Location: http://www.jguru.com/faq/view.jsp?EID=226070
Created: Oct 10, 2000 Modified: 2000-10-10 17:42:06.158
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Alas, using pure, portable Java, you cannot trap those sorts of system-specific key
sequences.

Are there any good books about Java I/O?


Location: http://www.jguru.com/faq/view.jsp?EID=226700
Created: Oct 11, 2000 Modified: 2000-10-11 09:11:01.087
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Tim Rohaly PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=10

The only book I'm aware of that is dedicated to Java I/O is Elliotte Rusty Harold's
book from O'Reilly: Java I/O. Reviews seem to rate it highly. Most books that offer
coverage just give the topic a chapter or two of coverage.

How can I add Attributes to the MainAttributes section of a Manifest object,


then write the Manifest to a JarFile using JarOutputStream?
Location: http://www.jguru.com/faq/view.jsp?EID=227525
Created: Oct 12, 2000 Modified: 2001-08-18 18:25:20.023
Author: Garth Somerville (http://www.jguru.com/guru/viewbio.jsp?EID=225821)
Question originally posed by Kevin Grey
(http://www.jguru.com/guru/viewbio.jsp?EID=109839

To add main attributes to an existing manifest object, use the read() method of
Manifest like so:

manifest.read( new StringBufferInputStream( "MainAttribute1:


value1\nMainAttribute2: value2\n" ) );

This will leave all existing attributes unchanged in the manifest, and simply add the
ones you specify.

To write the manifest to the Jar file using JarOutputStream, just use the constructor
for JarOutputStream that takes a Manifest as the second argument.

Comments and alternative answers

StringBufferInputStream is deprecated.
Author: Bill Gibbons (http://www.jguru.com/guru/viewbio.jsp?EID=826971), Apr 5,
2002
Given that StringBufferInputStream is deprecated, the suggested code:
manifest.read( new StringBufferInputStream( "MainAttribute1:
value1\nMainAttribute2: value2\n" ) );
is less than ideal. What is the best non-deprecated alternative? I'm using the form:
manifest.read( new ByteArrayInputStream("MainAttribute1:
value1\nMainAttribute2: value2\n".getBytes() ) );
on the assumption that "read" wants its input in the same platform-specific byte
encoding returned by "getBytes"; is this reasonable?

How can I programmatically compress a file using GZIP?


Location: http://www.jguru.com/faq/view.jsp?EID=228412
Created: Oct 13, 2000 Modified: 2001-08-18 18:25:50.295
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10)

The java.util.zip package contains classes which allow you to do this. Here is a
program that uses these classes to GZIP-compress a file:
import java.io.*;
import java.util.zip.*;
public class gzip {

public static void main(String[] args) {


try {
if (args.length != 1) {
System.out.println("Usage: java gzip <inputfile>");
System.exit(1);
}

FileOutputStream zipfile = new


FileOutputStream(args[0]+".gz");
GZIPOutputStream out = new GZIPOutputStream(zipfile);

System.out.println("Writing archive " + args[0] + ".gz");


System.out.println("");

FileInputStream in = new FileInputStream(args[0]);

byte[] data = new byte[2048];


int len;
while ((len = in.read(data)) != -1) {
out.write(data, 0, len);
}
in.close();
out.flush();
out.finish();
out.close();
}
catch (Exception e) {
System.out.println( "Exception is " + e.getMessage() );
e.printStackTrace();
}
}
}

How can I programmatically uncompress a file that has been compressed


using GZIP?
Location: http://www.jguru.com/faq/view.jsp?EID=228417
Created: Oct 13, 2000 Modified: 2001-08-18 18:26:26.545
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10)

The java.util.zip package has classes which let you do this. Here is a program
using these classes that will GZIP-uncompress a file:
import java.io.*;
import java.util.zip.*;

public class gunzip {

public static void main(String[] args) {


try {
if (args.length != 1) {
System.out.println("Usage: java gunzip <inputfile>");
System.exit(1);
}
String filename = null;
if (args[0].endsWith(".gz")) {
filename = args[0].substring(0,
args[0].lastIndexOf(".gz"));
}
else {
System.out.println("Inputfile must have extension .gz");
System.exit(1);
}

FileOutputStream out = new FileOutputStream(filename);

System.out.println("Extracting archive " + args[0]);


System.out.println("");

FileInputStream file = new FileInputStream(args[0]);


GZIPInputStream in = new GZIPInputStream(file);

byte[] data = new byte[2048];


int len;
while ((len = in.read(data)) != -1) {
out.write(data, 0, len);
}
in.close();
out.flush();
out.close();
}
catch (Exception e) {
System.out.println( "Exception is " + e.getMessage() );
e.printStackTrace();
}
}
}

Is there a limit on the size of a file that Java can open?


Location: http://www.jguru.com/faq/view.jsp?EID=232382
Created: Oct 19, 2000 Modified: 2001-08-18 18:27:11.788
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by Qiang Bai (http://www.jguru.com/guru/viewbio.jsp?EID=22135

With the exception of RandomAccessFile, all I/O in Java is done using streams. With
a stream, data is read or written on-the-fly, without buffering (unless you buffer
explicitly via a buffered stream or other means). Because only the portion of the data
you're reading or writing is in memory, the size of the file is irrelevant - Java sets no
limit other than the implicit limit imposed by the size of a long integer which is used
as the file length. This is larger than the file size allowed by most file systems.

Contrary to what you might think, creating a File object does not read the contents
of that file into memory - it merely serves as a container for a file descriptor and
meta-information about the file.

The specification for RandomAccessFile does not mandate any particular


implementation, so it is possible that some implementations do have a limit on the
size of file they can open. But most implementations probably use some sort of
stream internally, so the limitations are as described above.

How do I unzip a file that is password-protected?


Location: http://www.jguru.com/faq/view.jsp?EID=234256
Created: Oct 23, 2000 Modified: 2001-08-18 18:28:00.032
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by Martin Nielsen
(http://www.jguru.com/guru/viewbio.jsp?EID=231973

The Java classes that read Zip files, e.g. ZipInputStream, do not support decrypting
password-protected Zip files. I don't know of any publicly-available code in Java
which will do this, either. But this functionality is straightforward to add yourself. The
decryption algorithm needed is described in ftp://ftp.pkware.com/appnote.zip. You
can subclass the existing Java classes to add support for decryption; you will also
have to define a mechanism for a user of your subclass to enter the appropriate
password, using a dialog box for example. (And if you do so, please make that code
publically available and submit a link to that code as feedback to this question!)

When recursively descending a directory tree, how does one avoid an


infinite loop in the case that a directory entry is actually a symbolic link to a
directory higher up in the tree? I'm using the listFiles() method for File
objects to list the files in a directory, and then isDirectory() to determine
whether I need to recurse.
Location: http://www.jguru.com/faq/view.jsp?EID=235861
Created: Oct 24, 2000 Modified: 2001-08-18 18:28:49.19
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by Michael Ashley
(http://www.jguru.com/guru/viewbio.jsp?EID=230969

Symbolic links are defined at the file system level; they're a bit tricky, because what
you're doing when you make a link is fooling applications into thinking that the file
system has a different structure than it actually has.

For example suppose you had a directory called topgun which contained a directory
called middleearth which in turn contained a symbolic link called bottomman pointing
to topgun. Then the directory hierarchy might look as follows:

/home/topgun
|
+-- /home/middleearth
|
+-- /home/bottomman -> /home/topgun
If you did a cd /home/topgun/middleearth/bottomman then an ls, you would see
its contents as /home/middleearth. This does cause problems when you try to
recurse, and in particular isDirectory() will, and should, report that bottomman is a
directory. Unfortunately, the File class doesn't have a method to check whether that
path is a link.

To disambiguate between a directory and a link to a directory, you will need to use
the concept of an Absolute Path. The absolute path will show the true, fully expanded
path name, whereas the Canonical Path will follow the symbolic link. Consider the
following program:

import java.io.*;

public class Paths {

public static void main(String[] args) throws IOException {


File file = new File(args[0]);

System.out.println("Absolute: " + file.getAbsolutePath());


System.out.println("Canonical: " + file.getCanonicalPath());
}
}
If you run this program using the command
java Paths /home/topgun/middleearth/bottomman
you will see the following output:
Absolute: /home/topgun/middleearth/bottomman
Canonical: /home/topgun
Notice that when you examine the canonical path you can't tell the difference
between the symbolic link and the directory it points to, whereas with the absolute
path you can.

Note that the form of the canonical path is system-dependant - but then again, so is
the ability to create a cyclic hierarchy. This answer applies to Unix.

A solution to your problem might be to keep a graph of directory hierarchy as you


traverse them, and only descend branches you haven't been in before. This can be
done using a Hashtable. First check whether the absolute path of a File is found in
the table - if not, insert the path then recurse. If it is found, you can end your
recursion.

Comments and alternative answers

You have typos in your directory hierachy.


Author: Eryq Ouithaqueue (http://www.jguru.com/guru/viewbio.jsp?EID=811377),
May 30, 2002

Your directory hierarchy picture has too many "/home" strings in it. It should just look
like this:

/home/topgun
|
+-- middleearth
|
+-- bottomman -> /home/topgun

use file.equals(file.getCanonicalFile()) to filter symbolic links on Unix plattforms


Author: Dirk Zoettl (http://www.jguru.com/guru/viewbio.jsp?EID=1203733), Oct 6,
2004
see comment posted here

Where can I find an example of a Java application that communicates with


equipment via an RS232 serial port?
Location: http://www.jguru.com/faq/view.jsp?EID=238135
Created: Oct 26, 2000 Modified: 2000-10-26 22:06:37.986
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by Trung Nguyen Quang
(http://www.jguru.com/guru/viewbio.jsp?EID=237239

There are a number of complete examples that come with the Java Communications
API, which you can download from
http://java.sun.com/products/javacomm/index.html.

How can I specify which characters StreamTokenizer treats as token


delimiters?
Location: http://www.jguru.com/faq/view.jsp?EID=241596
Created: Oct 31, 2000 Modified: 2001-08-18 18:29:35.681
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by Satish Bhakta
(http://www.jguru.com/guru/viewbio.jsp?EID=223736

StreamTokenizer breaks the input stream into tokens using whitespace as a


delimiter. By default, Unicode characters \u0000 through \u0020 are considered
whitespace. This encompasses things like space, tab, newline, etc. If you want to
change this list, you need to invoke the method whitespaceChars(int low, int
high); all characters having Unicode values between low and high will be considered
whitespace, in addition to the default set.

You can call whitespaceChars() any number of times - each invocation will add to
the list of whitespace characters. The only way to clear out the list is to set those
characters to be something other than whitespace - you might use
ordinaryChar(int ch), ordinaryChars(int low, int high), wordChars(int
low, int high), or resetSyntax() to do this.

The following program is a very simple example of using StreamTokenizer to parse


a text file into words, number, and characters. The file to be parsed is taken from the
first argument; the second argument is a string containing all the characters to use
as delimiters.

import java.io.*;

public class TokenizeIt {

public static void main(String[] args) throws FileNotFoundException,


IOException {

FileReader file = new FileReader(args[0]);


BufferedReader in = new BufferedReader(file);
StreamTokenizer st = new StreamTokenizer(in);
char[] c = args[1].toCharArray();
for (int i=0; i<c.length; i++) {
System.out.println("Whitespace will include '" + c[i] +
"'");
st.whitespaceChars(c[i], c[i]);
}

int tokval;
while ((tokval = st.nextToken()) != StreamTokenizer.TT_EOF) {
switch (tokval) {
case StreamTokenizer.TT_WORD:
System.out.println("Word token \"" + st.sval +
"\"");
break;
case StreamTokenizer.TT_NUMBER:
System.out.println("Number token \"" + st.nval +
"\"");
break;
default:
System.out.println("Character '" + (char) tokval
+ "'");
break;
}
}
}
}
For example, if the input is delimited by commas and colons, you would run this
using the command line:
java TokenizeIt ",:"

How do I close a file after accessing it?


Location: http://www.jguru.com/faq/view.jsp?EID=244455
Created: Nov 3, 2000 Modified: 2001-08-18 18:30:09.731
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by Rajasekhar Kanuri
(http://www.jguru.com/guru/viewbio.jsp?EID=243519

Creating a new instance of File doesn't open the file - that's why File doesn't have
a close method. The only way you can access the contents of a file is using
RandomAccessFile, FileInputStream, FileOutputStream. FileReader, or
FileWriter. Each of these classes does have an explicit close() method.

Note that you should always make it a practice to close your file streams after you
have finished using them. It is not enough to set the stream reference to null
because you are likely to run out of available file descriptors long before you run out
of VM memory - and garbage collection is only triggered by memory shortage, not
shortage of descriptors.

How can I get the current working directory with Java?


Location: http://www.jguru.com/faq/view.jsp?EID=252445
Created: Nov 13, 2000 Modified: 2001-08-18 18:30:43.08
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by Isaac Rider Jimenez
(http://www.jguru.com/guru/viewbio.jsp?EID=214761
The current working directory is stored in the system property "user.dir". The
following example shows how to read this system property from your application:
public class userdir {
public static void main(String[] args) {
System.out.println("Working Directory = " +
System.getProperty("user.dir"));
}
}

What is a resource leak?


Location: http://www.jguru.com/faq/view.jsp?EID=262691
Created: Nov 25, 2000 Modified: 2001-07-08 19:36:16.512
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by kaveetha ramanathen
(http://www.jguru.com/guru/viewbio.jsp?EID=261910

Garbage collection manages only memory, not other system resources. If your Java
program has plenty of free memory, garbage collection will not be triggered
automatically. Usually, however, there are other resources that are more limited than
memory. For example, all OSes have limits on the number of sockets, file handles,
etc. that can be open. Sometimes this limit is quite low. This is true even on a
desktop, e.g. if your system has 128KB of memory, your Java program can easily
allocate all the available file handles without coming near to filling up the heap. If
this happens, your Java program will fail. This is what we call a resource leak; the
unintentional maintenence of references to non-memory resources.

This is why it is important in Java to explicitly manage non-memory resources.


Classes which utilize non-memory resources should provide ways to explicitly
allocate/deallocate those resources, independent of garbage collection. For example
Socket, InputStream and OutputStream each provide explicit close() methods for
deallocation of file descriptors, Window provides a dispose() method to free the
window handle, etc. The way to properly use these classes is to allocate using the
constructor, then deallocate using the appropriate method (deallocation is preferably
done in a finally{} block, so it will execute whether or not an exception is thrown
during use). These classes do release these non-memory resources in their
finalize() method, but remember that the finalizer only gets called by the garbage
collector, and if the object is never collected, it will never be finalized, hence will
never release the resources.

How can I create a record-based file data structure in Java?


Location: http://www.jguru.com/faq/view.jsp?EID=264347
Created: Nov 28, 2000 Modified: 2000-11-28 10:12:57.916
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by Alan Cox (http://www.jguru.com/guru/viewbio.jsp?EID=255589

There is an article in JavaWorld which discusses this in detail, complete with


implementation code. It can be found at http://www.javaworld.com/javaworld/jw-
01-1999/jw-01-step.html.

How can I determine the byte length of an object that I serialize to a


stream?
Location: http://www.jguru.com/faq/view.jsp?EID=264462
Created: Nov 28, 2000 Modified: 2001-01-17 20:50:49.845
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by Alan Cox (http://www.jguru.com/guru/viewbio.jsp?EID=255589

There are a couple of things you can do. First, you can pipe the ObjectOutputStream
into a ByteArrayOutputStream, then examine the length of the byte array:

ByteArrayOutputStream baos = new ByteArrayOutputStream();


ObjectOutputStream out = ObjectOutputStream(baos);
out.writeObject(new MyObject());
out.flush();
//
// Subtract 4 bytes from the length, because the serialization
// magic number (2 bytes) and version number (2 bytes) are
// both written to the stream before the object
//
int objectsize = baos.toByteArray().length - 4;
System.out.println("MyObject occupies " + objectsize
+ " bytes when serialized");

Or, if you want to stream to a destination other than a byte array, you can write a
subclass of DataOutputStream which allows you to access the protected variable
written. This subclass can be used to monitor the data sent through the stream to
any destination source:

import java.io.*;

public class ByteCounterOutputStream extends DataOutputStream {


public ByteCounterOutputStream(OutputStream out) {
super(out);
}

public int bytesWrittenSoFar() {


return written;
}
}
To use this to write to a file and count the size of the objects written on-the-fly, you
would do the following:
FileOutputStream file = new FileOutputStream("junk");
ByteCounterOutputStream bcos = new ByteCounterOutputStream(file);
ObjectOutputStream out = new ObjectOutputStream(bcos);
int start = bcos.bytesWrittenSoFar();
out.writeObject(new MyObject());
out.flush();
int objectsize = bcos.bytesWrittenSoFar() - start;
System.out.println("MyObject occupies " + objectsize
+ " bytes when serialized");

Is there a way in Java to find out the available free space on a disk drive?
Location: http://www.jguru.com/faq/view.jsp?EID=270756
Created: Dec 6, 2000 Modified: 2002-05-14 08:29:50.173
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by Prasad DV
(http://www.jguru.com/guru/viewbio.jsp?EID=270694
Short of using JNI, essentially no.

It's not pure Java, but JConfig (http://www.tolstoy.com/samizdat/jconfig.html) is a


supplemental library that relies on native code and is available for multiple platforms.
It allows you to discover this information, among many other things.

Can you change file permissions in Java (i.e. the equivalent of chmod)?
Location: http://www.jguru.com/faq/view.jsp?EID=275215
Created: Dec 11, 2000 Modified: 2001-08-18 18:35:25.777
Author: Erin Mulder (http://www.jguru.com/guru/viewbio.jsp?EID=275205) Question
originally posed by george hart
(http://www.jguru.com/guru/viewbio.jsp?EID=251010

You can restrict file permissions further using a SecurityManager and Policy, but
cannot actually change the file permissions in the native filesystem without a system
call (e.g. Runtime.getRuntime().exec("chmod 644 " + filepath)).
Comments and alternative answers

Sun has promised to address this missing feature in...


Author: Ajay Warrier (http://www.jguru.com/guru/viewbio.jsp?EID=241307), Dec 11,
2000
Sun has promised to address this missing feature in the new I/O work. You can find a
discussion and vote at
http://developer.java.sun.com/developer/bugParade/bugs/4313887.html.

See also How can I set file permissions for files ...
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Dec 11,
2000
See also How can I set file permissions for files created from Java?.

How can I get email addresses out of an MS Outlook database, and add
knew ones?
Location: http://www.jguru.com/faq/view.jsp?EID=276923
Created: Dec 13, 2000 Modified: 2000-12-13 11:50:41.384
Author: Jorge Jordão (http://www.jguru.com/guru/viewbio.jsp?EID=275762)
Question originally posed by nitin dubey
(http://www.jguru.com/guru/viewbio.jsp?EID=249436

You can access MS Outlook via a Java-COM bridge, and use the Outlook COM
interface variables and methods in your Java program.
I know 2 products that can help you with that:

• JIntegra, which is commercial


• JACOB, which is open-source

How would I write the equivalent of a tail -f command in Java?


Location: http://www.jguru.com/faq/view.jsp?EID=286864
Created: Dec 27, 2000 Modified: 2001-08-18 18:36:17.372
Author: Mazda Hewitt (http://www.jguru.com/guru/viewbio.jsp?EID=61973)
Question originally posed by Ben Poweski
(http://www.jguru.com/guru/viewbio.jsp?EID=243690

Here's a program that has similar functionality:


import java.io.*;

public class Tail {

public Tail(File f) throws java.io.IOException,


java.lang.InterruptedException{

int pos = 0;
RandomAccessFile file = new RandomAccessFile(f, "r");
pos = (int)file.length() - (int)Math.min(400, file.length());
file.seek(pos);
for (;true; Thread.currentThread().sleep(2000)){
int l = (int)(file.length()-pos);
if (l <= 0) continue;
byte[] buf = new byte[l];
int read = file.read(buf,0, l);
String out = new String(buf, 0,l);
System.out.print(out);
pos = pos+l;

}
}

public static void main(String[] args) {


try{
Tail tail1 = new Tail(new File(args[0]));
}
catch (ArrayIndexOutOfBoundsException a){
System.out.println("Usage : Tail <file>");
System.exit(1);
}
catch (java.io.IOException io){
System.err.println(io.getMessage());
System.exit(1);
}
catch (Exception xe){
xe.printStackTrace();
System.exit(1);
}
}
}
Comments and alternative answers

How would I write the equivalent of a tail -f command in Java?


Author: Mary Jane Barger (http://www.jguru.com/guru/viewbio.jsp?EID=979710),
Aug 8, 2002
How would you change this code to be equivalent to a tail -1 which reads only the last
line of the file.

Re: How would I write the equivalent of a tail -f command in Java?


Author: Eoin O'Kane (http://www.jguru.com/guru/viewbio.jsp?EID=433977), Dec
19, 2002
Try this
RandomAccessFile file = new RandomAccessFile(filename, "r");

int pos = (int)file.length() - (int)Math.min(numberOfLines,


file.length());

int l = (int)(file.length()-pos);

byte[] buf = new byte[l];

int read = file.read(buf,0, l);

String out = new String(buf,0,l);

Eoin

How can I read a file from the applet's JAR file?


Location: http://www.jguru.com/faq/view.jsp?EID=289142
Created: Dec 29, 2000 Modified: 2001-08-18 18:37:02.658
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Abey Mullassery
(http://www.jguru.com/guru/viewbio.jsp?EID=268841

Use the getResourceAsStream() method to get the file in the JAR as an InputStream.
Then just read it:
import java.io.*;
import java.awt.*;
import java.applet.*;

public class Read extends Applet {

TextArea ta = new TextArea();

public void init() {


setLayout(new BorderLayout());
add(ta, BorderLayout.CENTER);
try {
InputStream in =
getClass().getResourceAsStream("read.txt");
InputStreamReader isr =
new InputStreamReader(in);
BufferedReader br =
new BufferedReader(isr);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
String line;
while ((line = br.readLine()) != null) {
pw.println(line);
}
ta.setText(sw.toString());
} catch (IOException io) {
ta.setText("Ooops");
}
}
}

Is there a way in Java to compress or combine a group of files that will


preserve file permissions and file ownerships? I have tried JarOuputStream
and ZipOutputStream and neither seem to work.
Location: http://www.jguru.com/faq/view.jsp?EID=290088
Created: Dec 31, 2000 Modified: 2001-08-18 18:38:08.836
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by Mark Webb
(http://www.jguru.com/guru/viewbio.jsp?EID=80178

Java has built-in support for compression in the java.util.zip and java.util.jar
packages. These packages provide implementations of several standard and widely
used compression utilities such as Zip, GZip, and Jar. However, none of these utilities
supports preserving permission and ownership - no matter what programming
language is used. In other words, there is no such thing as a Zip file which contains
permission or ownership information.

If you need your archive to contain this meta information, you will need to use a
scheme which explicitly preserves permission and ownership, such as the tar utility
found on Unix. (Note that the standard implementation of tar doesn't do
compression - it just does archiving. You can however GZip your tar archive to
reduce its size.)

Because Java has no built-in support for examining or setting file permissions or
ownership, any Java implementation of tar must use the JNI in order to preserve
this information. There are several Java implementations of tar available, both free
and commercial. I don't know of one that properly preserves this information.

How can I examine or change file permissions and ownership using Java?
Location: http://www.jguru.com/faq/view.jsp?EID=290098
Created: Dec 31, 2000 Modified: 2001-08-18 18:38:47.973
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Tim Rohaly PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=10

Standard Java provides no means to access or change file permissions / ownership.


Short of using JNI, there is no way to access or preserve this information.
Comments and alternative answers

Changing File Permissions without JNI on unix


Author: Eric Herman (http://www.jguru.com/guru/viewbio.jsp?EID=733789), Jan 24,
2002
You may use exec() to perform nearly any OS command you wish.

Here's a sample bit of code:

static public void chmod777(File file) {


if (file == null || !file.exists())
return;
try {
String command = "chmod 777 " + file.getAbsolutePath();
Runtime r = Runtime.getRuntime();
Process p = r.exec(command);
// p.waitfor();

} catch (IOException ioe) {


ioe.printStackTrace();
}
}

The problem with exec() is platform dependency.

A quick and dirty check to see if you're on unix might be to look at the
file.pathSeparatorChar();
and see if it is equal to "/" ... obviously, this isn't perfect.

This example is static so, it could be used from a "helper class" .... You might wish to
return sucess or failure state, or perhaps set the permissions from a parameter.

Are there any third-party Java classes that support reading and interacting
with SVG files?
Location: http://www.jguru.com/faq/view.jsp?EID=305717
Created: Jan 18, 2001 Modified: 2001-08-18 18:40:08.878
Author: Ingo Richter (http://www.jguru.com/guru/viewbio.jsp?EID=89353) Question
originally posed by Rachael Oldmeadow
(http://www.jguru.com/guru/viewbio.jsp?EID=305098

The Batik Toolkit from Apache lets you do this. See http://xml.apache.org/batik/.

How can I print colored text from Java to a terminal such as the Linux
console?
Location: http://www.jguru.com/faq/view.jsp?EID=312906
Created: Jan 25, 2001 Modified: 2001-07-08 21:37:29.856
Author: Nathan Meyers (http://www.jguru.com/guru/viewbio.jsp?EID=138686)
Question originally posed by Borsos Szabolcs
(http://www.jguru.com/guru/viewbio.jsp?EID=311226

Native applications can take advantage of the curses library to use special terminal
capabilities such as color. There is no such capability in the core Java classes, but
here's a library that provides similar capabilities in Java:
http://alpha2.iit.unict.it/JOS/jcurses.html.
Comments and alternative answers
> There is no such capability in the core Java ...
Author: Remus Pereni (http://www.jguru.com/guru/viewbio.jsp?EID=223271), Jan
27, 2001
> There is no such capability in the core Java classes ...

However, you can output the terminal-dependent escape sequences to select colors. If
the terminal has color capabilities and the Java program outputs the right escape
sequences the output will be colored.

Example:

public class ColorTest {

public static void main (String args[]) {


System.out.println( "\u001b[1;44m Hello World \u001b[m" );
}
}

Java does not give you access to the libraries (termcap and terminfo) that tell you
which escape sequences to use for a particular terminal, but choosing the codes for a
common terminal like VT100 will work for many popular terminal emulators.

Another alternative is JNICurses, which accesses the...


Author: Nathan Meyers (http://www.jguru.com/guru/viewbio.jsp?EID=138686), Jan
27, 2001
Another alternative is JNICurses, which accesses the native curses facility through
JNI calls.

The "Charva" package offers another alternative.


Author: Rob Pitman (http://www.jguru.com/guru/viewbio.jsp?EID=110924), Jun 17,
2001
The Charva package offers an alternative way of displaying text on an ASCII
terminal. It allows a Java application to display a "graphical" user interface
(composed of frames, dialogs, menus, buttons, labels, textfields etc) on any terminal
that has a terminfo description file. It uses JNI calls to the ncurses library to
accomplish this. It is licensed with the LGPL license.

How can I read a single character from the keyboard without having to
press the 'enter' button and without using GUI classes like KeyListener?
Location: http://www.jguru.com/faq/view.jsp?EID=317157
Created: Jan 31, 2001 Modified: 2001-08-18 18:54:34.835
Author: Mark Thornton (http://www.jguru.com/guru/viewbio.jsp?EID=276034)
Question originally posed by Ernesto Diaz
(http://www.jguru.com/guru/viewbio.jsp?EID=247557
The solution to this problem is OS dependent. On Win32 you would need to use JNI
to call the SetConsoleMode function to disable the line buffering. For an example of
using this method, see
http://msdn.microsoft.com/library/psdk/winbase/conchar_156b.htm.
Comments and alternative answers

Read a single character (without pressing ENTER) in linux?


Author: J J (http://www.jguru.com/guru/viewbio.jsp?EID=1064222), Mar 7, 2003
How do I do the same in Linux?

How can I write a text document in PDF format?


Location: http://www.jguru.com/faq/view.jsp?EID=329373
Created: Feb 14, 2001 Modified: 2001-02-14 15:04:53.182
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by satya anumolu
(http://www.jguru.com/guru/viewbio.jsp?EID=328520

The only third-party class library that I know of for doing this is called retepPDF. It
can be found at http://www.retep.org.uk/.
Comments and alternative answers

Try this site: http://www.etymon.com . They have an...


Author: Arun Bharathan (http://www.jguru.com/guru/viewbio.jsp?EID=106958), Feb
14, 2001
Try this site: http://www.etymon.com . They have an API with which you can
generate simple PDFs from ASCII text. I haven't really tried to create complex PDFs.

You could also try the Apache FOP project that uses...
Author: Ivo Limmen (http://www.jguru.com/guru/viewbio.jsp?EID=327483), Feb 15,
2001
You could also try the Apache FOP project that uses Xalan for XSL translating to
generate any type of document from a given style sheet. The output of FOP is PDF
but they are working on more output types like RTF, SVG, etc. You can find this
package at http://xml.apache.org/.

I've used iText and found it works quite well for ...
Author: Rodney Gitzel (http://www.jguru.com/guru/viewbio.jsp?EID=99036), Feb
21, 2001
I've used iText and found it works quite well for things like invoices and other table-
based documents. Check it out at http://www.lowagie.com/iText/.

Try PDFLib
Author: Ranjit Mathew (http://www.jguru.com/guru/viewbio.jsp?EID=427636), May
24, 2001
Try PDFLib available at http://www.pdflib.org/pdflib/index.html
What is the correct order of ObjectInputStream/ObjectOutputStream creation
on the client and the server when sending objects over a network
connection?
Location: http://www.jguru.com/faq/view.jsp?EID=333392
Created: Feb 19, 2001 Modified: 2001-08-18 18:55:36.37
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by Joen Moreno
(http://www.jguru.com/guru/viewbio.jsp?EID=134600

According to the API documentation for ObjectInputStream's constructor:

The stream header containing the magic number and version number are read from
the stream and verified. This method will block until the corresponding
ObjectOutputStream has written and flushed the header.
This is a very important point to be aware of when trying to send objects in both
directions over a socket because opening the streams in the wrong order will cause
deadlock.

Consider for example what would happen if both client and server tried to construct
an ObjectInputStream from a socket's input stream, prior to either constructing the
corresponding ObjectOutputStream. The ObjectInputStream constructor on the
client would block, waiting for the magic number and version number to arrive over
the connection, while at the same time the ObjectInputStream constructor on the
server side would also block for the same reason. Hence, deadlock.

Because of this, you should always make it a practice in your code to open the
ObjectOutputStream and flush it first, before you open the ObjectInputStream. The
ObjectOutputStream constructor will not block, and invoking flush() will force the
magic number and version number to travel over the wire. If you follow this practice
in both your client and server, you shouldn't have a problem with deadlock.

Why are there two type of I/O in Java, namely byte streams and character
(Reader/Writer) streams?
Location: http://www.jguru.com/faq/view.jsp?EID=344602
Created: Mar 5, 2001 Modified: 2001-03-05 12:13:36.141
Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985)
Question originally posed by Jaicey Ouseph
(http://www.jguru.com/guru/viewbio.jsp?EID=330921

The Reader and Writer classes were added to JDK 1.1 to support internationalization,
since the existing streams at that time didn't properly support the use of multi-byte
Unicode characters or character encodings other than ASCII. The Reader and Writer
classes make it possible to work with internationalized character streams rather than
byte streams.
Comments and alternative answers

General rules for choosing the right type of I/O s...


Author: Robert Höglund Wanlert
(http://www.jguru.com/guru/viewbio.jsp?EID=62558), Mar 5, 2001
General rules for choosing the right type of I/O stream:
1. Don't read/write a file in a binary format (e.g. .jpeg or .gif) using a
Reader/Writer, it may result in a unwanted outcome
2. Don't read/write a file with textual data (e.g. .txt) with a
OutputStream/InputStream, it may result in a unwanted outcome

Where can I learn (more) about Java's AWT (Abstract Window Toolkit)?
Location: http://www.jguru.com/faq/view.jsp?EID=431184
Created: May 30, 2001 Modified: 2001-06-16 16:04:40.639
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru AWT FAQ.

Where can I learn (more) about Java's suport for internationalization


(I18N)?
Location: http://www.jguru.com/faq/view.jsp?EID=431191
Created: May 30, 2001 Modified: 2001-08-18 19:04:05.76
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru I18N FAQ.

Where can I learn (more) about dealing with 2D (two dimensional) and 3D
(three dimensional) images, sound, speech, telelphony, and the rest of
Java's support for advanced media handling?
Location: http://www.jguru.com/faq/view.jsp?EID=431203
Created: May 30, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru Java Media APIs FAQ.

Where can I learn (more) about Java networking capabilities?


Location: http://www.jguru.com/faq/view.jsp?EID=431237
Created: May 30, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru Networking FAQ.

Where can I learn (more) about Java's support for developing multi-
threaded programs?
Location: http://www.jguru.com/faq/view.jsp?EID=431248
Created: May 30, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru Threads FAQ.

I'm creating a ZIP file using java.util.zip.ZipOutputStream. If the file


names of these files are in any other language other than English (e.g.
Chinese) they get distorted. when I extract the ZIP file using WinZip. How
do I preserve the file names?
Location: http://www.jguru.com/faq/view.jsp?EID=439970
Created: Jun 15, 2001 Modified: 2001-08-18 19:05:03.638
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by Rupinder Lall
(http://www.jguru.com/guru/viewbio.jsp?EID=229112

WinZip, and the ZIP file format in particular, only supports ASCII characters for file
names. The Java class ZipOutputStream can't give you a capabillity which is not
supported by the underlying file format. So, you are stuck using ASCII.
Comments and alternative answers

Use ISO-8859-1 escape style (like HTTP)


Author: Thorsten Giesecke (http://www.jguru.com/guru/viewbio.jsp?EID=322237),
Jul 13, 2001
Use ISO-8859-1 escape style (like HTTP, i. e. %20 for a space and so on) to save non-
latin filenames and later reconvert these names to the required charset for a specific
language. Note: for multi-language data i prefer utf-8. so you can save such data in a
rdbms without truncation of the string data. see also String.getBytes("encoding"), new
String (in, "encoding") and the package description for java.lang.

Re: Use ISO-8859-1 escape style (like HTTP)


Author: Klearchos Klearchou
(http://www.jguru.com/guru/viewbio.jsp?EID=1206325), Oct 20, 2004
And what we will do when we need the user to unzip the file with a third party
program like WinZip ? What he will face ? The file names in an encoded form ?
What is the solution for this ?

How do I write something in the end of a file? Do I have to read the entire
file first putting it into a buffer and then write it all again in a file with the
line I want to write in the end? Or I can directly write in the end of the file?
Location: http://www.jguru.com/faq/view.jsp?EID=447967
Created: Jun 30, 2001
Author: JIA Java Italian Association
(http://www.jguru.com/guru/viewbio.jsp?EID=414973) Question originally posed by
fernando fernandes (http://www.jguru.com/guru/viewbio.jsp?EID=420587

Check out java.lang.FileWriter and java.lang.FileOutputStream. They both


have a constructor that takes a boolean parameter for appending or not the data.

Is there any method in Java that will convert hexadecimal characters to


binary characters?
Location: http://www.jguru.com/faq/view.jsp?EID=451751
Created: Jul 8, 2001 Modified: 2001-08-18 19:07:01.613
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by Sunil R (http://www.jguru.com/guru/viewbio.jsp?EID=446378
You can use Integer.parseInt() or Long.parseLong() to convert a hexadecimal
representation to a 4-byte int or an 8-byte long, respectively. For example, the
Java class file magic number 0xCAFEBABE can be converted to the long value
3405691582 using
long magic = Long.parseLong("CAFEBABE", 16);
where the second argument to the method represents the radix used to encode the
first parameter (in this case, base 16, or hexadecimal).

You can also convert hexadecimal number directly into Integer or Long objects using
the methods Integer.decode() or Long.decode(), respectively.

If you wish to subsequently print out these values as a String in base 2 (binary),
you can use either Integer.toBinaryString() or Long.toBinaryString().

See the API documentation for Integer and Long for more detail.

How can I implement the Unix "cksum" command in Java? I'm using a
CheckedInputStream and creating a new instance of CRC32 to pass it, but I
don't get the same checksum value as cksum give me.
Location: http://www.jguru.com/faq/view.jsp?EID=461810
Created: Jul 25, 2001
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by dale olzer
(http://www.jguru.com/guru/viewbio.jsp?EID=461144

cksum uses the CRC-16 algorithm, not the CRC-32 algorithm. You need to use
another implementation of the Checksum interface for this purpose - it's easy to write
your own or find someone else's code. Here's one, for example:
http://www.mcmanis.com/~cmcmanis/java/encoders/index.html.
Comments and alternative answers

here is another code pure java


Author: Cad Developer (http://www.jguru.com/guru/viewbio.jsp?EID=776790), Feb
28, 2002
import java.security.*;
import java.io.*;

public class jmd5sum


{
public static void main(String []args) throws Exception {
if (args.length != 1) {
System.err.println("Usage: java jmd5sum <file>");
System.exit(1);
}

BufferedInputStream bis = new BufferedInputStream(new


FileInputStream(args[0]));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int c;
while ((c = bis.read()) > -1) {
baos.write(c);
}
bis.close();
byte[] buf = baos.toByteArray();

MessageDigest md = MessageDigest.getInstance("MD5");
md.update(buf);
byte[] digest = md.digest();

int decValue;
for (int i=0; i<digest.length; i++) {
if (digest[i] >= 0)
decValue = digest[i];
else
decValue = 256 + digest[i];

String hexVal = Integer.toHexString(decValue);


if (hexVal.length() == 1) hexVal = "0" + hexVal; //prefix a
zero to look uniformed;
System.out.print(hexVal + " ");
}
System.out.print(" "+ args[0]);
}
}

What's the serialver syntax to get the serialVersionUID of an array?


Location: http://www.jguru.com/faq/view.jsp?EID=468625
Created: Aug 4, 2001 Modified: 2001-08-05 11:25:04.557
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

You need to pass in the array "type" after the [ character, and before a ; character. If
the type is a class, add the letter L and the fully qualified class name. If the type is a
primitive, the type codes are specified in ObjectStreamField.getTypeCode(), you can
almost just capitalize the first letter and place after [. Though, that isn't always the
case. For boolean, use Z instead of B, for long use J since L is already taken for
classes and interfaces.

For instance, for the String class the syntax is

serialver "[Ljava.lang.String;"
For an array of int elements, it is:
serialver "[I;"

How do I set a system property when using an executable jar (one with an
entry of Main-Class: ClassName)?
Location: http://www.jguru.com/faq/view.jsp?EID=469352
Created: Aug 6, 2001 Modified: 2001-08-18 19:08:48.451
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by Cintia Aono
(http://www.jguru.com/guru/viewbio.jsp?EID=231889
Just like with executing a program just use the the -D flag along with the -jar flag.
Here is my test case:
public class property {
public static void main(String[] args) {
System.out.println("User-defined property = " +
System.getProperty("my.property"));
}
}
Compile and run using
java -Dmy.property=test property
and you'll get the results:
User-defined property = test
Now create a manifest (call it manifest.mf) that contains only the line:
Main-Class: property
as the first line, then jar up property.class with this manifest:
jar cvfm property.jar manifest.mf property.class
Now try to run as an executable jar:
java -Dmy.property=test -jar property.jar
and you'll get the same result.

Warning:Be sure the last line of the manifest file has a newline at the end.

I'm creating a zip file using the java.util.zip package. The created zip file
has to be spilt, if it exceeds a size limit. How can I do this splitting of the
file?
Location: http://www.jguru.com/faq/view.jsp?EID=470549
Created: Aug 7, 2001 Modified: 2001-08-18 19:09:21.055
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by Rupinder Lall
(http://www.jguru.com/guru/viewbio.jsp?EID=229112

Java has no built-in support for disk or file spanning. However, it should be easy to
do this on your own. I would suggest subclassing FileOutputStream to perform
checks on the length of the data written so far, and if the data approaches the
maximum allowed, close the underlying file and open a new one for writing. You will
then be able to use your subclass with any of the standard output streams, including
ZipOutputStream.

Also, from Luigi Viggiano:


The directory list of a zip file is located at bottom of the file, that's why zip tools ask
for last disk of the set before to unpack. In a spanneable archive format this is really
uncomfortable, and it can be deduced that, zip format itself, doesn't complain
spanning. Maybe WinZip and other tools, handles zip spanning simply cutting the
output file. And this should be done also in Java to implement spanning.

My C program opens a pipe and gets a file descriptor. Then it start a JVM
with JNI and sends the file descriptor to the Java side. Is it now possible for
me to write data to this pipe using the file descriptor from the Java code?
Location: http://www.jguru.com/faq/view.jsp?EID=470550
Created: Aug 7, 2001 Modified: 2001-08-18 19:09:47.342
Author: Finlay McWalter (http://www.jguru.com/guru/viewbio.jsp?EID=13911)
Question originally posed by Per Desaix
(http://www.jguru.com/guru/viewbio.jsp?EID=412050
Unfortunately, the java.io class that handles file descriptors (java.io.FileDescriptor)
doesn't allow you to construct a new one from an integer (which is really what you
want).

So, the only thing you can do is to create a new, specialized subclass of
java.io.OutputStream (in practice you'd probably subclass BufferedOutputStream)
which would take an integer file descriptor as a constructor argument. You'd then
have to rewrite the functionality of java.io.FileOutputStream yourself, including the
native code and JNI bridge. This is a bit of a pain, but it's not especially difficult.

What are the practical differences, in terms of performance and


functionality, between ZipInputStream/ZipOutputStream and
GZIPInputStream/GZIPOutputStream?
Location: http://www.jguru.com/faq/view.jsp?EID=472103
Created: Aug 8, 2001 Modified: 2001-08-18 19:10:17.975
Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985)
Question originally posed by Barry Wythoff
(http://www.jguru.com/guru/viewbio.jsp?EID=222348

The compression algorithm is the same (Lempel-Ziv derivative LZ-77-deflate). The


difference is that GZIP format is used to compress a single file, and ZIP is used to
compress many files in a single archive. In Unix world you can find files using GZIP
algorithm containing more than 1 file: it's done grouping files with tar utility before,
then compressing the stream in a "tar.gz" file (tarball).

If you have to compress a single file, it's better to use GZIP I/O classes, because
there isn't multi-file archive handling and shall be faster than ZIP I/O classes. Vice
versa, if you have to create an archive of more than 1 file, it's better to use ZIP I/O
classes.

For more info, see the zLib homepage.

Is there an easy way of counting line numbers? Or do you have to go


through the entire file?
Location: http://www.jguru.com/faq/view.jsp?EID=478972
Created: Aug 17, 2001
Author: Shahram Khorsand (http://www.jguru.com/guru/viewbio.jsp?EID=3357)
Question originally posed by Shahram Khorsand
(http://www.jguru.com/guru/viewbio.jsp?EID=3357

You have to go through the entire file.


try {
LineNumberReader lnr = new LineNumberReader(new FileReader(filename));
String s;
while ((s = lnr.readLine()) != null);
System.out.println("Lines: " + lnr.getLineNumber());
Comments and alternative answers

faster solution
Author: Gary Hobson (http://www.jguru.com/guru/viewbio.jsp?EID=530249), Oct
25, 2001
This should be faster....
try
{
FileInputStream vIn = new FileInputStream(filename);
int i = vIn.read();
int vLines = 0;
while(i != -1)
{
if(i == 10) // '\n'
vLines++;
i = vIn.read();
}
vIn.close();
}
catch(Exception e)
{
e.printStackTrace();
}
Editor Note: Keep in mind that \n is not the only EOL character... on Macs, you just
need/get a \r.

What is piped I/O used for?


Location: http://www.jguru.com/faq/view.jsp?EID=478975
Created: Aug 17, 2001 Modified: 2001-08-18 17:21:38.816
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by sona s (http://www.jguru.com/guru/viewbio.jsp?EID=431321

The piped I/O streams are for inter-thread communication. They manage the
synchronization across thread boundaries of the buffer.

See Is there any way to communicate between two classes... for an example.

Comments and alternative answers

Alternatives
Author: Stephen Ostermiller (http://www.jguru.com/guru/viewbio.jsp?EID=576685),
Apr 17, 2002
Circular buffers are an alternative to using pipes. I find them easier to use because
you have one object from which you get streams rather than multiple pipes that need
to be connected. You can also control the size of the buffer that is used.

Circular character buffer implementation: (Instead of piped Readers and Writers)


http://ostermiller.org/utils/CircularCharBuffer.html

Circular byte buffer implementation: (Instead of piped InputStreams and


OutputStreams)
http://ostermiller.org/utils/CircularByteBuffer.html
Re: Alternatives
Author: Stephen Ostermiller
(http://www.jguru.com/guru/viewbio.jsp?EID=576685), Aug 8, 2002
Circular Object buffer implementation:
http://ostermiller.org/utils/CircularObjectBuffer.html

Consider using this instead of Readers and Writers when passing Strings around.
It will only pass references to the strings rather than copying the data. It can of
course be used for Objects as well.

How do I create a zip file and add more than one entry to the zip file?
Location: http://www.jguru.com/faq/view.jsp?EID=478978
Created: Aug 17, 2001 Modified: 2001-08-18 12:53:18.951
Author: Finlay McWalter (http://www.jguru.com/guru/viewbio.jsp?EID=13911)
Question originally posed by Matthew Harris
(http://www.jguru.com/guru/viewbio.jsp?EID=245383

You need to use the facilities of java.util.zip.ZipOutputStream and


java.util.zip.ZipEntry. Here's a simple example that makes a zip file and writes three
tiny text files into it.
import java.io.*;
import java.util.zip.*;

public class zipper {


public static final void main(String [] args){
try {
ZipOutputStream outStream = new ZipOutputStream (new
FileOutputStream("out.zip"));

writeEntry(outStream, "f1.txt", "this is some text");


writeEntry(outStream, "f2.txt", "more text");
writeEntry(outStream, "f3.txt", "text, text, and yet more
text");

outStream.close();
}
catch(Exception e){
e.printStackTrace();
}
}

static void writeEntry(ZipOutputStream stream,


String filename,
String text){
try {
ZipEntry e1 = new ZipEntry(filename);
e1.setMethod(ZipEntry.DEFLATED);
stream.putNextEntry(e1);
stream.write(text.getBytes());
stream.closeEntry();
}
catch(IOException e){
e.printStackTrace();
}
}
}

Why aren't printing-related topics covered in the I/O FAQ? It seems like an
I/O issue.
Location: http://www.jguru.com/faq/view.jsp?EID=478981
Created: Aug 17, 2001 Modified: 2001-08-18 09:37:02.026
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Printing is done with AWT classes and thus covered in the AWT FAQ. See How do I
print a multi-page text document? for one example, though the API has changed
with every release of Java.

How do I display the Euro symbol?


Location: http://www.jguru.com/faq/view.jsp?EID=479171
Created: Aug 18, 2001 Modified: 2002-03-25 14:11:57.388
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

You can use the Unicode symbol:

\u20AC

Keep in mind that when you use System.out, it strips the high order byte from the
output. In other words, you can't use System.out.println("\u20AC") to get a Euro to
the console.

Comments and alternative answers

It is possible to use the Euro sign on the console.


Author: dirk zoettl (http://www.jguru.com/guru/viewbio.jsp?EID=82237), Mar 7,
2003
If your console font supports the Euro sign, it can be used from Java too. (tested on
WinNT, don't know about Win9x)

1. Switch your console code page to windows encoding with:


chcp 1252

2. Test with Alt-128 you should get a euro sign.

3. Use the following:

import java.io.*;

public class WinEuro {

public static final int WIN_EURO_CHAR_CODE = 128;

public static final char EURO_CHAR = '\u20AC';


public static void main(String[] args) throws Exception {
//--- write character code directly ---
System.out.println("Euro code on Cp1252 is 128 == 0x80.");
System.out.print("the normal price is 3.50 ");
System.out.write(WIN_EURO_CHAR_CODE);
System.out.println();
//--- create PrintWriter with Windows encoding ---
PrintWriter con = new PrintWriter(new
OutputStreamWriter(System.out, "Cp1252"), true);
con.println("your special price 2.33 " + EURO_CHAR);
}

How do I get a listing of all the files in a directory and its sub-directories?
Location: http://www.jguru.com/faq/view.jsp?EID=479174
Created: Aug 18, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

To recursively get all files under a specific directory, just keep calling listFiles() on the
File that is returned, if it is a directory (isDirectory() returns true).

Here is what it looks like... From vineet bhatia

/**
* list all files in a directory and its sub-directories
* @param directory to be scanned
* @return vector of the files in all the sub-directories
*/
private Vector listAllFiles(File directory)
{
String[] fileList = null;
Vector vectList = new Vector();

if(directory.isDirectory())
fileList = directory.list();

String path = directory.getAbsolutePath();

for(int i=0; i<fileList.length;i++)


{
File f = new File(path + File.separator + fileList[i]);
if(!f.isDirectory())
vectList.addElement(fileList[i]);
else
{
Vector subList = listAllFiles(f);
Enumeration enum = subList.elements();
while(enum.hasMoreElements())
vectList.addElement(enum.nextElement());
}
}
return vectList;
}

How do you filter the result of the list() method of the File object?
Location: http://www.jguru.com/faq/view.jsp?EID=480039
Created: Aug 20, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
fernando fernandes (http://www.jguru.com/guru/viewbio.jsp?EID=400255

Create a new class (there are people that consider this a waste and use anonymous
classes) that implements the FilenameFilter.
This is an example for filtering all the XML files in a directory:
import java.io.*;

public class FilterXMLFile implements FilenameFilter {

/**
* you just need to implement the accept method
*/
public boolean accept(File dir, String name) {
return name.endsWith(".xml");
}
}
Then, in your code, you can do something like this:
File myDir = new File(<the directory>);
File[] xmlFiles = myDir.listFiles(new FilterXMLFile());
You can do the same thing with a FileFilter.

How can I detect if there is a floppy in the floppy drive using Java?

javaw.exe takes over with the "No disk" dialog, even when I catch a
Security Exception. How does one suppress this dialog?????
Location: http://www.jguru.com/faq/view.jsp?EID=488755
Created: Sep 2, 2001 Modified: 2002-03-25 14:17:01.599
Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985)
Question originally posed by D. Garda
(http://www.jguru.com/guru/viewbio.jsp?EID=315216

I've seen lot of very well written Java application, that does not deal very well with
the floppy problems. I found that also zip, tapes drives, and other removable mass
storages get same problems. For CD-ROMs, if no cd is available it just seems as an
empty filesystem, and no system messages are shown if the drive is not ready.
Check this code:

File fileFloppy = new File("A:/dummy.txt");


File fileCDROM = new File("E:/dummy.txt");

if (fileFloppy.exists())
System.out.println("file on floppy exists");
else
System.out.println("file on floppy doesn't exists");

if (fileCDROM.exists())
System.out.println("file on cd exists");
else
System.out.println("file on cd doesn't exists");

On my PC, the check on the floppy shows the system message asking to insert
floppy; on the CD this not happens, and the output on my system (Sun JDK 1.3.1)
is:

file on floppy doesn't exists


file on cd doesn't exists
I believe that this behaviour can change on different implementations of JVMs.

In Unix, a removable disk can be mounted or not, but no problem arise because the
OS deals with those devices differently; with Windows the operating system shows
the message dialog saying that the disk is not ready. This cannot be handled or
trapped by a Java Application, because the OS comes first and handle it its own. The
only way, is to write a low level code to check if the disk is present and interface it
with Java thru JNI.
In other words, to the best of my knowledge, you cannot do anything to manage the
problem with Java code, it is a platform dependent problem / requires JNI.

How do I read a zip file over the network from a URL through a
ZipInputStream?
Location: http://www.jguru.com/faq/view.jsp?EID=488756
Created: Sep 2, 2001
Author: Bogdan Sheptunov (http://www.jguru.com/guru/viewbio.jsp?EID=310126)
Question originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

This piece uncompresses every entry of a ZIP file and puts them into a Vector.
ZipEntry anEntry = null;
Vector entriesList = new Vector();
try
{
URL aURL = new URL ("http://localhost/wwwroot.zip");
URLConnection aConnection = aURL.openConnection();
aConnection.setDoInput(true);
aConnection.setDoOutput(false);
aConnection.setUseCaches (false);
aConnection.setDefaultUseCaches (false);
aConnection.connect();
ZipInputStream inputStream = new
ZipInputStream(aConnection.getInputStream());
anEntry = inputStream.getNextEntry();
while (anEntry != null)
{
long decompressedSize = anEntry.getSize();
byte[] uncompressedBuf = new byte[(int)decompressedSize];
inputStream.read(uncompressedBuf);
entriesList.add(uncompressedBuf);
anEntry = inputStream.getNextEntry();
}
inputStream.close();
}
catch (Exception e)
{
System.out.println("Oops: " + e.getMessage());
}

How are the mark() and reset() methods used with InputStream classes?
Location: http://www.jguru.com/faq/view.jsp?EID=504771
Created: Sep 26, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
arul senthil (http://www.jguru.com/guru/viewbio.jsp?EID=490540

Using the mark() and reset() method of the InputStream classes is pretty easy.
First of all you need to be sure that the InputStream that you are working with
supports the mark() and reset() functionality. For this you need to use the
markSupported() method.

Once you know that the stream supports those methods (when markSupport()
returns true), you can use the mark(int readlimit) method to 'mark' a position in the
stream. The javadoc for this method is very clear:

[...] the stream somehow remembers all the bytes read after the call to mark and
stands ready to supply those same bytes again if and whenever the method reset is
called. However, the stream is not required to remember any data at all if more than
readlimit bytes are read from the stream before reset is called.
The reset() method will allow you to reposition the stream pointer to the position
where the mark() method was called.

The following code snippet doesn't really make any sense, but it will show you how to
use the markSupported(), mark() and reset() methods.

InputStream is = null;
try {
is = new FileInputStream(new File("/tmp/testfile.tmp"));

// check if the stream supports mark/reset methods


if (!is.markSupported()) {
throw new RuntimeException("Mark/Reset not supported!");
}

int ch;
int readings = 0;
boolean marked = false;

// read until EOF


while ((ch = is.read()) != -1) {

System.out.print("." + ch);

// the first time you hit char 128, mark this position
if ((ch == 128) && !marked) {
is.mark(64);
marked = true;
}

// for 3 times, every time the file reaches char 200, reset
// and restart reading from the marked position (char 128)
if ((ch == 200) && (readings < 3)) {
is.reset();
readings++;
}
}
}
finally {
try {
is.close();
}
catch (Throwable t) {
// do nothing
}
}
To make it running you should create a file containing all the char from 0 to 255. The
output should read up to 128, then for three times read the chars 129->200 and
finally read the remaining.
sorry, but I haven't tested this code, but I've changed a piece of code I've used long
time ago, but it should work... hopefully

How do I map a file into memory using the New I/O capabilities in Java 1.4?
Location: http://www.jguru.com/faq/view.jsp?EID=507235
Created: Sep 30, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

FileInputStream input = new FileInputStream(filename);


FileChannel channel = input.getChannel();
int fileLength = (int)channel.size();
MappedByteBuffer buffer =
channel.map(FileChannel.MAP_RO, 0, fileLength);

How do I convert between ByteBuffer and a CharBuffer using Java 1.4?


Location: http://www.jguru.com/faq/view.jsp?EID=507237
Created: Sep 30, 2001 Modified: 2002-03-25 14:23:27.589
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

The java.nio.charset package include character set converters for you. To go from
ByteBuffer to CharBuffer, you would do something like the following:
ByteBuffer buffer = ...
Charset charset = Charset.forName("ISO-8859-1");
CharsetDecoder decoder = charset.newDecoder();
CharBuffer charBuffer = decoder.decode(buffer);
For different character sets, provide a different name to the forName() call.

How can I redirect the output of session.setDebug(true) so that I can


capture it in the program that uses it?
Location: http://www.jguru.com/faq/view.jsp?EID=523526
Created: Oct 17, 2001 Modified: 2001-10-18 08:11:03.415
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Andrew Cao
(http://www.jguru.com/guru/viewbio.jsp?EID=523514

The messages are hardcoded to go to System.out. The best you can do is redirect
System.out to a ByteArrayOutputStream:
session.setDebug(true);
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(os);
// save output
PrintStream old = System.out;
// change output
System.setOut(ps);
// send
...
// reset output
System.setOut(old);
System.out.println(os);

Do I have to synchronize read-only access to a text file?


Location: http://www.jguru.com/faq/view.jsp?EID=531243
Created: Oct 26, 2001 Modified: 2001-10-27 08:18:32.688
Author: Bozidar Dangubic (http://www.jguru.com/guru/viewbio.jsp?EID=433955)
Question originally posed by Tony Fagan
(http://www.jguru.com/guru/viewbio.jsp?EID=226421

My servlet reads the contents of a text file which I access using a File object.

What issues are involved when this file is read concurrently by several different
threads? Do I have to synchronize access to the file, or does it not matter when
access is read-only?

Should not matter if the file is only for reading. Make sure that you close the file
when you are done using it.
Comments and alternative answers

Do I have to synchronize read-only access to a text file?


Author: Serge Borodai (http://www.jguru.com/guru/viewbio.jsp?EID=1135393), Dec
22, 2003
So, I have to synchronize read-only access to a text file?

How can I save an image to disk in a standard image format?


Location: http://www.jguru.com/faq/view.jsp?EID=532225
Created: Oct 28, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by pranesh sharma
(http://www.jguru.com/guru/viewbio.jsp?EID=321734
The javax.imageio package provides this for you in Java 1.4. Previousl versions had
no standard support, though you could add third party libraries to standard Java for
this.
BufferedImage output = new BufferedImage (width, height,
BufferedImage.TYPE_INT_ARGB);
// fill image
// Save
File outputFile = new File("image.png");
ImageIO.write(output, "PNG", outputFile);

How do I create a Selector (java.nio.channels)?


Location: http://www.jguru.com/faq/view.jsp?EID=533145
Created: Oct 29, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

While the Selector class is abstract, you can create one by calling the static open()
method. This will create an instance of a Selector subclass. Behind the scenes, this is
done through the selector provider:
SelectorProvider.provider().openSelector()

Where can I learn to use the Java 1.4 regular expression package?
Location: http://www.jguru.com/faq/view.jsp?EID=533149
Created: Oct 29, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The Java Developer Connection provides a tutorial on the package at


http://java.sun.com/jdc/technicalArticles/releases/1.4regex/.

How can I show a progress bar while reading a file?


Location: http://www.jguru.com/faq/view.jsp?EID=534271
Created: Oct 30, 2001
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11)
Question originally posed by Sanjeev Dhiman
(http://www.jguru.com/guru/viewbio.jsp?EID=447087

Here's a simple example of monitoring file read progress

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.InputStream;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.ProgressMonitorInputStream;

public class Test {


public static void main(String[] args) {
// create a test frame with a "press me" button
final JFrame f = new JFrame("Sample");
f.getContentPane().setLayout(new FlowLayout());
JButton b = new JButton("Press me");
f.getContentPane().add(b);
f.pack();

// set up the file read action


b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// when button is pressed, start a new thread
// to read the file. A new thread is needed because we
// need to free the GUI update thread to paint the
// progress monitor
new Thread() {
public void run() {
try {
// open the file, wrapping it in a
ProgressMonitorInputStream
InputStream in = new FileInputStream("c:\\bigfile.bin");
ProgressMonitorInputStream pm =
new ProgressMonitorInputStream(f,"Reading the big
file",in);
// read the file. If it's taking too long, the progress
// monitor will appear. The amount of time is roughly
// 1/100th of the estimated read time (based on how long
// it took to read the first 1/100th of the file.)
// Note that by default, the dialog won't appear unless
// the overall estimate is over 2 seconds.
int c;
while((c=pm.read()) != -1) {
// do something
}
pm.close(); // needs better error handling, of course...
}
catch(Exception ex) {
ex.printStackTrace();
}
}
}.start();
}});

// display the frame


f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}

None of the NIO examples that use character buffers work with 1.4 beta 3.
What's up?
Location: http://www.jguru.com/faq/view.jsp?EID=550325
Created: Nov 16, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

This is bug 4510323. You'll need to wait to see when it get fixed...

How do I initialize a JTextArea from an input file?


Location: http://www.jguru.com/faq/view.jsp?EID=550961
Created: Nov 18, 2001 Modified: 2002-07-29 21:16:52.027
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

The JTextComponent provides a read() method to initialize the text component:


JTextArea ta = new JTextArea();
Reader reader = new FileReader(filename);
ta.read(reader, null);
The second parameter is a description.

What's up with the CharSequence/CharBuffer in 1.4 beta 3? None of the


examples work any more.
Location: http://www.jguru.com/faq/view.jsp?EID=554376
Created: Nov 20, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The beta 3 release of Java 1.4 broke the class. See bug 4510323 for a description of
the problem. Hopefully, this will be fixed for the first non-beta release.

How to make a file read only?


Location: http://www.jguru.com/faq/view.jsp?EID=567157
Created: Nov 29, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by chami sen
(http://www.jguru.com/guru/viewbio.jsp?EID=536787

For any type of file, just use the setReadOnly() method of File to mark a file as read-
only. There is no argument to make it writable once it is read-only.

How can I read an Microsoft Excel file from Java?


Location: http://www.jguru.com/faq/view.jsp?EID=567234
Created: Nov 29, 2001
Author: Brett Porter (http://www.jguru.com/guru/viewbio.jsp?EID=544812)
Question originally posed by Nagurva Reddy
(http://www.jguru.com/guru/viewbio.jsp?EID=542797

There is no built in support for this. While you can create an ODBC DSN and use the
JDBC bridge to the file, this can be a nuisance to do. Instead try the open source
ExcelRead package, which allows you to display the contents as comma-separated
values or a well-formed XML document.
Comments and alternative answers

Re:
Author: abhay k (http://www.jguru.com/guru/viewbio.jsp?EID=561576), Nov 29,
2001
Use jacob Java to COM bridge
It allows you to open and read from Excel COM object.
You will find more information on
http://danadler.com/jacob/
Re: Re:
Author: Aniruddh Mishra (http://www.jguru.com/guru/viewbio.jsp?EID=36169),
Apr 4, 2002
Use Jintegra bridge driver from www.linar.com.. It is good I have tried this..

Several Options
Author: Stephen Ostermiller (http://www.jguru.com/guru/viewbio.jsp?EID=576685),
Apr 17, 2002
Export your data to Comma Separated Value (CSV) format and use libraries to read
and write this format:
http://ostermiller.org/utils/ExcelCSV.html

Use excelread by Andy Khan to get excel data into your java program:
http://www.andykhan.com/excelread/

The apache project has a library which called POI that can read and write the HSSF
(Horrible Spread Sheet Format) that excel uses.
http://jakarta.apache.org/poi/hssf/

Connect to an Excel spreadsheet file using jdbc.


http://www.jguru.com/faq/view.jsp?EID=32876

Use Jexcel (Site opened from 11:00am to 7pm daily, new york time zone.)
http://stareyes.homeip.net:8888/

use POI
Author: Pradeep Kanwar (http://www.jguru.com/guru/viewbio.jsp?EID=544776), Feb
11, 2004
browse POI for excel. Its an apache project with good documentation and API

How to parse a CSV (Comma Separated Value) file in Java?


Location: http://www.jguru.com/faq/view.jsp?EID=568300
Created: Nov 30, 2001
Author: Naveed Azhar (http://www.jguru.com/guru/viewbio.jsp?EID=64653)
Question originally posed by kavitha mahadevan
(http://www.jguru.com/guru/viewbio.jsp?EID=542549

Comma Separated Values (CSV) in Java is an available library to help. It supports


reading and writing the files.
Comments and alternative answers

JDBC driver for CSV


Author: olivier refalo (http://www.jguru.com/guru/viewbio.jsp?EID=78203), Nov 30,
2001
That's the most portable way.... a full JDBC compliant interface.
http://sourceforge.net/projects/csvjdbc/ Regards, OR
How do I load property settings with the Properties class?
Location: http://www.jguru.com/faq/view.jsp?EID=581608
Created: Dec 12, 2001 Modified: 2005-08-02 18:31:05.958
Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985)
Question originally posed by tyris d
(http://www.jguru.com/guru/viewbio.jsp?EID=401666

java.util.Properties objects can load values from a file using the method
load(InputStream).

Here is the code you need:

Properties props = new Properties();


props.load(new FileInputStream("propertyfile.properties"));
String value = props.getProperty("propertyname");
//Just a trick: in a web archive (war) you can get the InputStream
inside the war archive using
ClassLoader cl = this.getClass().getClassLoader();
InputStream is =
cl.getResourceAsStream("it/package/application.properties");

This is better than using a FileInputStream, because you are loading the file within
the archive as it was a resource. You should use this.getClass().getClassLoader() to
use the same ClassLoader as the one used the servlet container to load your
JSP/Servlet. This code is snipped from a JSP page inside Tomcat.

How do I write a value to the registry of a computer?


Location: http://www.jguru.com/faq/view.jsp?EID=705548
Created: Dec 30, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by sabu vs PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=476248

Prior to the 1.4 release, there is no built in support of this, short of using native
code. With the 1.4 release, you can do this.

First get the root node for either the system or user:

// Fetching a Preferences object from non-static method


Preferences userPrefs = Preferences.userNodeForPackage(this);
Preferences sysPrefs = Preferences.systemNodeForPackage(this);
// Fetching Preferences object from static method
Preferences userPrefs = Preferences.userRoot().node("/net/zukowski");
Preferences sysPrefs = Preferences.systemRoot().node("/net/zukowski");
Then write to it with one of the following:

• put(String key, String value)


• putBoolean(String key, boolean value)
• putByteArray(String key, byte value[])
• putDouble(String key, double value)
• putFloat(String key, float value)
• putInt(String key, int value)
• putLong(String key, long value)

All the put() methods return a void. If the storage mechanism is unavailable, a
BackingStoreException will be thrown.

Comments and alternative answers

where i can found the preference class


Author: Zur Pozner (http://www.jguru.com/guru/viewbio.jsp?EID=1128097), Aug 11,
2004
where i can found the preference class

Re: where i can found the preference class


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Aug 11,
2004
import java.util.prefs.Preferences;

How do I read a value from the registry of a computer?


Location: http://www.jguru.com/faq/view.jsp?EID=705549
Created: Dec 30, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Prior to the 1.4 release, there is no built in support of this, short of using native
code. With the 1.4 release, you can do this.

First get the root node for either the system or user:

// Fetching a Preferences object from non-static method


Preferences userPrefs = Preferences.userNodeForPackage(this);
Preferences sysPrefs = Preferences.systemNodeForPackage(this);
// Fetching Preferences object from static method
Preferences userPrefs = Preferences.userRoot().node("/net/zukowski");
Preferences sysPrefs = Preferences.systemRoot().node("/net/zukowski");
Then read from it with one of the following:

• get(String key, String default)


• getBoolean(String key, boolean default)
• getByteArray(String key, byte default[])
• getDouble(String key, double default)
• getFloat(String key, float default)
• getInt(String key, int default)
• getLong(String key, long default)

If you're not sure of the preference names, you can find a list of the keys associated
with a node with the keys() method. This method returns a String[] of nodes.

How do I save properties settings with the Properties class?


Location: http://www.jguru.com/faq/view.jsp?EID=705567
Created: Dec 30, 2001 Modified: 2002-02-05 10:46:16.46
Author: Kenneth Tennek (http://www.jguru.com/guru/viewbio.jsp?EID=414359)
Question originally posed by tyris d
(http://www.jguru.com/guru/viewbio.jsp?EID=401666

Try this:
Properties prop = new Properties();
FileOutputStream output = new FileOutputStream("Test.properties");
prop.store(output,"my testproperties");
output.flush();
output.close();
You'll need to catch an IOException.

How do I delete a directory that isn't empty?


Location: http://www.jguru.com/faq/view.jsp?EID=705646
Created: Dec 30, 2001
Author: Christopher Schultz (http://www.jguru.com/guru/viewbio.jsp?EID=138382)
Question originally posed by daniela popescu
(http://www.jguru.com/guru/viewbio.jsp?EID=452516

It's got to be a recursive-like method (in that it recurses the subdirs and deletes
their contents, too). Something like this will probably work (off the top of my head):
import java.io.File;
.
.
.

public void nuke(File path)


throws IOException
{
File[] files = path.listFiles();

for(int i=0; i<files.length; ++i)


{
if(files[i].isDirectory())
nuke(files[i]);

files[i].delete();
}
}
You may want to do some more error checking, etc. but that should basically work.

How can I convert GIFs to PNGs using Java?


Location: http://www.jguru.com/faq/view.jsp?EID=730341
Created: Jan 22, 2002 Modified: 2002-10-21 13:52:16.679
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Nigel Johnson
(http://www.jguru.com/guru/viewbio.jsp?EID=729849

The Image I/O libraries added to Java 1.4 perform this for you:
File inputFile = new File(filename);
BufferedImage input = ImageIO.read(inputFile);
File outputFile = new File(outfilename);
ImageIO.write(input, "PNG", outputFile);
To get a list of available format one can read, use
ImageIO.getReaderFormatNames(). (gif, jpg, png)

To get the list of available writable formats, use getWriterFormatNames() (jpg, png).

How do you delete a entry from a ZIP file?


Location: http://www.jguru.com/faq/view.jsp?EID=730377
Created: Jan 22, 2002
Author: Stephen Welch (http://www.jguru.com/guru/viewbio.jsp?EID=421160)
Question originally posed by Rupinder Lall
(http://www.jguru.com/guru/viewbio.jsp?EID=229112

I'm afraid you'll have to extract all the contents you want to preserve and create a
new zip file, removing the entries you want deleted.

How do I check/set for hidden files?


Location: http://www.jguru.com/faq/view.jsp?EID=741064
Created: Jan 30, 2002
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
uwe geercken (http://www.jguru.com/guru/viewbio.jsp?EID=731524

Setting a file "hidden" is a system-specific operation and, often, the way to do this is
completely different depending upon the platform.

In Unix, for example, this can be done by simply renaming the file to a name that
starts with the ".". As you can see, on this operating system, setting a file to hidden
can be done with the renameTo() method.

On Windows, you'd have to execute a system call or use JNI to change attributes.

As far as checking goes, just call File.isHidden() to check.

How can I open a file in a way that it prevents other application from
reading or writing to the same file?
Location: http://www.jguru.com/faq/view.jsp?EID=741069
Created: Jan 30, 2002
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Tuan Truong
(http://www.jguru.com/guru/viewbio.jsp?EID=32991

Use the lock() of the FileChannel class. Prior to Java 1.4, there was no standard way.

I am trying to add a file to existing zip archive. Using java.util.zip, I am able


to add the file. But the only file in the archive is the file I just added. The
method putNextEntry in ZipOutputStream class is losing the existing file in
the archive.

Any work around for this? thanks for your help. Sat
Location: http://www.jguru.com/faq/view.jsp?EID=741070
Created: Jan 30, 2002 Modified: 2002-01-30 18:59:32.023
Author: Dhiren Bhatia (http://www.jguru.com/guru/viewbio.jsp?EID=468024)
Question originally posed by Sat Jeej
(http://www.jguru.com/guru/viewbio.jsp?EID=728973

You will have to save the existing zip file in a temporary file, add the contents of the
existing zip file to the temporary file and then add the new contents you want to
update the zip file with.

The java.util.zip api's do not provide random access to zip files.

How to get lastModified time of a file within a jar file on the classpath?
Location: http://www.jguru.com/faq/view.jsp?EID=773187
Created: Feb 26, 2002
Author: Jens Dibbern (http://www.jguru.com/guru/viewbio.jsp?EID=9896) Question
originally posed by Alan Gault
(http://www.jguru.com/guru/viewbio.jsp?EID=131380

If you know the jar file, you can open it as a java.util.jar.JarFile object and use
getJarEntry to retrieve the file in question as a java.util.jar.JarEntry object.
After that you can call getTime.
If you do not know the jar file, you have to get the classpath by String classPath
= System.getProperty("java.class.path"); and try every jar file included.
Sorry about the last bit - I know it looks quite clumsy.
Comments and alternative answers

using URL and URI


Author: Chantal Ackermann (http://www.jguru.com/guru/viewbio.jsp?EID=88569),
May 7, 2002

I have to use the ClassLoader to retrieve the location of the jar as the application shall
be deployed with JavaWebStart. The ClassLoader returns an URL to allocate the jar.

How can I instantiate a File object from an URL - that is: how can I convert the URL
to an URI or extract the absolute pathname?

I am thinking of a solution similar to:

ClassLoader cl = this.getClass().getClassLoader();
URL url = cl.getResource("filename");
URI uri;
// convert somehow the url to uri, e.g
File jarFile = new File(uri);

Can someone fill in the missing part?

Re: using URL and URI


Author: Chantal Ackermann
(http://www.jguru.com/guru/viewbio.jsp?EID=88569), May 7, 2002
I found the method URLConnection.getLastModified() that might do exactly what
I want. If it works I won't have to get a reference to the jarfile just to check out if it
has been reloaded.

Re: using URL and URI


Author: Denn Denn (http://www.jguru.com/guru/viewbio.jsp?EID=1232633), Mar
15, 2005
just use :- URL url = cl.getResource("filename"); URI uri=url.toURI(); File jarFile
= new File(uri);

How do you programmatically create a JAR file?


Location: http://www.jguru.com/faq/view.jsp?EID=774741
Created: Feb 27, 2002 Modified: 2004-10-22 21:21:52.869
Author: Heinrich Soebke (http://www.jguru.com/guru/viewbio.jsp?EID=428663)
Question originally posed by Dinkoh Lee
(http://www.jguru.com/guru/viewbio.jsp?EID=416944

File outFile = new File(outPath);

BufferedOutputStream bo = new BufferedOutputStream(new


FileOutputStream(outPath));
JarOutputStream jo = new JarOutputStream(bo);

String act = f.getPath();


BufferedInputStream bi = new BufferedInputStream(new
FileInputStream(act));

JarEntry je = new JarEntry(act);


jo.putNextEntry(je);

byte[] buf = new byte[1024];


int anz;

while ((anz = bi.read(buf)) != -1) {


jo.write(buf, 0, anz);
}

bi.close();
jo.close();
bo.close();
See also
http://developer.java.sun.com/developer/technicalArticles/Programming/compression
/.
Comments and alternative answers

Jar creation
Author: chazz chazz (http://www.jguru.com/guru/viewbio.jsp?EID=1227122), Feb
14, 2005
The code does seem to do the trick. It does create a jar file and all but the jarfile it
creates is unusealbe by java. I created a jarfile from the same files this way and then
from the command line with VERY different results. the file created commandline
style was about 10K bigger than the one creaded programmatically. the one created
commandline worked with my java app (with jarfile in class path) but the one created
programatically does not work at all, java cant find the class inside the jar. Is there
something special i need to do to the jar or is that code missing something to make it
useable by java? -ChazZ

Can I read individual keystrokes from System.in?


Location: http://www.jguru.com/faq/view.jsp?EID=777612
Created: Feb 28, 2002
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by George Carey
(http://www.jguru.com/guru/viewbio.jsp?EID=777550

Short of using JNI, you cannot.

When would I ever need to use a FileDescriptor object?


Location: http://www.jguru.com/faq/view.jsp?EID=777684
Created: Feb 28, 2002
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

Short of using JNI, there seems to be no use for them in pure Java programs.
Comments and alternative answers

Forcing synchronization
Author: Tom Rons (http://www.jguru.com/guru/viewbio.jsp?EID=1017891), Oct 26,
2002
You might want to use a FileDescriptor object when you want to force
synchronization of, for example, a FileOutputStream, with the underlying media.
Unless you explicitly force synchronization through a file descriptor, data will remain
in a buffer until the JVM thinks it should be written to the underlying device. That
might not be feasible when writing such programs as persistant object-oriented
databases, where you would want to make sure all data is written to disk, so no data
can get lost in the event of a crash.

Does the StreamTokenizer close the underlying Reader when it reaches end of
stream or do I have to close it manually?
Location: http://www.jguru.com/faq/view.jsp?EID=777686
Created: Feb 28, 2002
Author: Bozidar Dangubic (http://www.jguru.com/guru/viewbio.jsp?EID=433955)
Question originally posed by Artur de Sousa Rocha
(http://www.jguru.com/guru/viewbio.jsp?EID=70489
You should close it manually, always.

How can I get the path of a JarEnrty?


Location: http://www.jguru.com/faq/view.jsp?EID=797757
Created: Mar 14, 2002
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Enrico Varagnolo (http://www.jguru.com/guru/viewbio.jsp?EID=736782

java.util.jar.JarEntry is a subclass of java.util.zip.ZipEntry. If you use the


getName() method on your JarEntry object, you will get the full name of the entry,
including its path (relative or absolute depending on how it was created). If the entru
is a directory, the isDirectory() method will return true.

Try this piece of code:

...
JarFile file = new JarFile(<path of a jar file>);
for (Enumeration enum=file.entries(); enum.hasMoreElements();) {
JarEntry entry = (JarEntry)enum.nextElement();
System.out.println("Name = " + entry.getName());
System.out.println("is directory = " + entry.isDirectory());
System.out.println();
}
file.close();
Remember to add some try/catch blocks... ;-)

How can I correctly parse CSV ( comma separated values ) files?


StringTokenizer doesn't seem to fit many conditions.
Location: http://www.jguru.com/faq/view.jsp?EID=809266
Created: Mar 23, 2002
Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)
Question originally posed by steven mccartey
(http://www.jguru.com/guru/viewbio.jsp?EID=792888

Ian Darwin has two classes ( CSV.java and CSVRE.java ) to handle CSV files in his
Java Cookbook, including a way with regular expressions. You can download the code
from his site, probably best to do so from the examples by chapter ( see Chapter 3,
"Strings and Things" ) page. Not a bad idea to buy the book, either.
Comments and alternative answers

use this class


Author: Amardeep Singh (http://www.jguru.com/guru/viewbio.jsp?EID=811616),
Mar 25, 2002
import java.util.*;

public class WStringTokenizer extends StringTokenizer


{
private String tbt;
private String d;
private int startpos=0;
public WStringTokenizer(String str,String delim)
{
super(str,delim);
tbt=new String(str);
d=new String(delim);
}
public int countTokens()
{
int tokens=0;
int temp=startpos;
while(true)
{
try
{
nextToken();
tokens++;
}
catch(NoSuchElementException e) {break;}
}
startpos=temp;
return tokens;
}

public boolean hasMoreElements() {


return hasMoreTokens();
}

public boolean hasMoreTokens() {


if(countTokens()>0) return true;
else return false;
}

public Object nextElement() {


return (Object) d;
}

public String nextToken() throws NoSuchElementException {


int result=0;
String s;

if(startpos>tbt.length()) throw(new NoSuchElementException


());
result=tbt.indexOf(d,startpos);
if(result<0) result=tbt.length();
s=new String(tbt.substring(startpos,result));
startpos=result+d.length();
return s;
}

public String nextToken (String delim) throws


NoSuchElementException {
d=delim;
return nextToken();
}
}
Another CSVReader
Author: Roshan Shrestha (http://www.jguru.com/guru/viewbio.jsp?EID=130068),
Mar 26, 2002
Ian Darwin's class parses the file one line at a time. Many times, a field may span
multiple lines. I think a better class is the CSVReader described in
http://www.objectmentor.com/resources/articles/tfd.pdf. As an added bonus, it also
desscribes unit testing with JUnit!

CSV Libraries
Author: Stephen Ostermiller (http://www.jguru.com/guru/viewbio.jsp?EID=576685),
Apr 17, 2002
There are free open source libraries for parsing and printing CSV files available here:
http://ostermiller.org/utils/CSVLexer.html

Re: CSV Libraries


Author: Anjan Bacchu (http://www.jguru.com/guru/viewbio.jsp?EID=283891), Jun
1, 2004
FYI,
The library from ostermiller.org is licensed with GPL. This prevents usage of this
library in commercial products (unless they are themselves GPL compatible). So,
effectively you cannot use them unless your open source product is also GPL
compatible.

BR,
~A

CSV Libraries for commercial use


Author: Richard Rodger
(http://www.jguru.com/guru/viewbio.jsp?EID=1220174), Jan 7, 2005
There are commercial CSV parsers available, including:
StelsCSV (a JDBC driver for CSV), and
Ricebridge Java CSV Parser (my own).

I am not currently aware of any open source CSV Java parsers that are under
BSD or similar licenses that allow commercial use, but I could be wrong.

Library
Author: davide consonni (http://www.jguru.com/guru/viewbio.jsp?EID=1190420),
Aug 3, 2004
can use csvToSql (http://sourceforge.net/projects/csvtosql/)

Re: Library
Author: azad kans (http://www.jguru.com/guru/viewbio.jsp?EID=1249830), Jun
22, 2005
using
WStringTokenizer
as an implementation of
StringTokenizer(String,deleimter)
is a good implementation and we have used it successfully in our projects
.Another approach is to use
String[] values = String.split(delimiter,no. Of Fields)

.This is effective when you know that each row will have fixed no. of
columns(delimter separated values). The value returned is an array and each field
can be retrieved by
values[i]

which is very handy compared to StringTokenizer.I think this was introduced in


1.4 version of java

CSVFile classes
Author: Fabrizio Fazzino (http://www.jguru.com/guru/viewbio.jsp?EID=1255529),
Jul 28, 2005
I've modified Ian Darwin's classes (preserving the copyright message) and created a
new project on SourceForge:

SF Project Summary is at http://sourceforge.net/projects/csvfile


and the documentation is at http://csvfile.sourceforge.net/.

There are 3 classes, CSVFile (abstract), CSVFileReader (that makes use of Ian's code)
and CSVFileWriter; they are very easy to use since the fields are handles as
Vector<String> variables.

I also made it possible to customize the text qualifier (e.g. can be a tick or backtick
rather than double quote) and the filed separator (e.g. can be a dot rather than a
comma or semicolon).

Re: CSVFile classes


Author: Paul Zepernick (http://www.jguru.com/guru/viewbio.jsp?EID=1032221),
Aug 5, 2005
I have a java project for parsing delimited and fixed length txt files. It is licensed
under the apache 2 license. It can be downloaded from:

http://sourceforge.net/projects/pzfilereader

Paul Zepernick

What options are available for creating and editing PDF files?
Location: http://www.jguru.com/faq/view.jsp?EID=810102
Created: Mar 24, 2002
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Pablo Lucas (http://www.jguru.com/guru/viewbio.jsp?EID=786424

This is a list of some PDF Libraries:

• PJ free by Ethymon
• iText free by B.Lowagie &P.Soares
• retepPDF free by P.T.Mount
• PDFLib by PDFlib GmbH
• Faceless PDF library by Faceless.Org

Obviously, if the file to edit is protected, I don't know how much it can be done
without unprotecting it first.
Comments and alternative answers

Others
Author: Enrico Varagnolo (http://www.jguru.com/guru/viewbio.jsp?EID=736782),
Mar 24, 2002
There are also:
FOP by xml.apache.org
DRE by IBM Alphaworks
Hope this helps .....

Re: Others
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727), Mar 25, 2002
Ciao Enrico,
Thanks for adding those names.

The reason I didn't included in my original message was that they are both more
of PDF generators rather than PDF Editing libraries.
I mean that (and please, correct me if I'm wrong) are libraries that allows the user
to generate a PDF but not to edit that.

Thanks anyway

Re[2]: Others
Author: Bruno Lowagie
(http://www.jguru.com/guru/viewbio.jsp?EID=492448), Mar 25, 2002
This is because PDF is a format that can only be used for READ ONLY
presentation of documents. For instance: you will never find software that
allows you to include a paragraph into an existing PDF file. You need the
source of the document in some other format to be able to do this.

The only things you can edit when you have an existing PDF document are
'cosmetic changes' such as adding a Watermark, adding pagenumbers, headers,
footers,... You can't replace words (unless you 'paint' another word with the
same dimensions over the existing words).

If you don't believe me, just read the PDF reference manual and try to
understand how a PDF document is constructed. You will see: PDF documents
are very hard to edit BY DESIGN!!!

Re[3]: Others
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727), Mar 25, 2002
Bruno,
The fact that something it's hard, doesn't make it impossible.

Have you tried those libraries to create or change a document?

Re[4]: Others
Author: Bruno Lowagie
(http://www.jguru.com/guru/viewbio.jsp?EID=492448), Mar 25, 2002
I am the Original Developer of iText, so I think I know what I say if I
tell you iText is only suited for the 'cosmetic changes' I mentioned in
my earlier reply.

I'm also convinced that there is NO PRODUCT that is able to edit an


existing PDF file ONLY BY PARSING IT. What you need is a product
that is able to make some internal VISUALISATION of the PDF,
retrieve the text with something like OCR (some algorythm that is able
to judge which letters belong to the same word and which words belong
to the same sentence). You would then have to store the text in some
other format that is more suited to edit and convert the edited text to
PDF.

Re: If you need to read text out of PDF files...


Author: Chas Emerick (http://www.jguru.com/guru/viewbio.jsp?EID=1194801),
Aug 23, 2004
... you may want to consider PDFTextStream. It is designed specifically for high-
performance extraction of text and metadata out of PDF documents. It's 100%
Java, so it will work in any Java application or web service.

I recommend iText
Author: Ivo Limmen (http://www.jguru.com/guru/viewbio.jsp?EID=327483), Mar 26,
2002
I have been working for a while with PDF libraries and used the iText and Ethymon
package. Ethymon had a significant flaw, after I sloved the bug myself and send them
the sollution to the creators of Ethymon I discovered that they do not support it
anymore. Then I moved to iText and stress-tested it using more that 300 PDF's to test
it. It works very well. While testing I worked closely with the creators of iText to
reslove all the bugs. It is a really stable product at the moment.
What API to use for datamining a PDF?
Author: Per Bovbjerg (http://www.jguru.com/guru/viewbio.jsp?EID=841967), Apr
17, 2002
Hi. Im new to jGuru, but just joined after reading this thread on PDF editing.
Which of the API's mantioned in this thread, would be best to use if I want to
datamine some PDF files for certain keywords, parse the line's around those
keywords, collect the data, and the write them to another format? (Not PDF). I
have been looking on iText, but the documentaion says iText is mostly for creating
PDF's. Any help/advices would be very apreciated. Thanks

Re: What API to use for datamining a PDF?


Author: Ivo Limmen (http://www.jguru.com/guru/viewbio.jsp?EID=327483),
Apr 18, 2002
The new versions of iText can parse PDF files as well. New versions will
probably be able to do more. Reading PDF is very complex, you will probably
need a commercial product to do it well.

Re[2]: What API to use for datamining a PDF?


Author: Per Bovbjerg
(http://www.jguru.com/guru/viewbio.jsp?EID=841967), Apr 22, 2002
Hi Ivo.
I have looked through the doc and tutorials from the iText packages, and
from what I can see, it is not posible to use iText to parse an existing PDF
document.
This is from the iText FAQ:
Is it possible to parse an existing PDF-document and convert it to
another format (HTML, DOC, EXCEL)?
No, the pdf format is just a canvas where text and graphics are placed
without any structure information. As such there aren't any 'iText-objects' in
a PDF file. For instance: you can't retrieve a table object from a PDF file.
Tables are formed by placing text and lines at selected places.

So Im still looking for some way to maybe read a line in a PDF doc, and
parse it.
Any sugestions to what other PDF parsing packages I could use, would be
very apreciated.

Re[3]: What API to use for datamining a PDF?


Author: Ivo Limmen
(http://www.jguru.com/guru/viewbio.jsp?EID=327483), Apr 22, 2002
Correct: converting is not possible but you can read the PDF file in
order to merge it.

Re[3]: What API to use for datamining a PDF?


Author: Michael Cavalier
(http://www.jguru.com/guru/viewbio.jsp?EID=915569), Jun 16, 2002
You might want to look at:
http://sourceforge.net/projects/jpedal

Project Description:
Java Pdf Extraction Decoding Access Library is a java class library to
extract images and text from pdf files as well as to access the more basic
pdf object tree. It also provides a pdf rasterizer to generate an image of
the page.

jPDF
Author: olivier refalo (http://www.jguru.com/guru/viewbio.jsp?EID=78203), Feb 4,
2003
Well, depending on your edition needs you may want to check the jPDF products line
at http://www.crionics.com They also have a split/merger module available. Regards,
OR

Re: jPDF
Author: David Mybizz (http://www.jguru.com/guru/viewbio.jsp?EID=1143448),
Feb 4, 2004
Hi,

Maybe it´s too late to answer, but just in case someone finds this interesting...

I have successfully used Etymon PJ to EDIT text in a PDF document. I couldn´t


use PJX because our web app was running on JVM 1.3.

Our users have predefined PDF templates with special tokens that are replaced in
runtime with information from a database and, so far, it works.

How it works:

for (int i = 0; i < pdf.getMaxObjectNumber(); i++) {

po = pdf.getObject(i);

if (po != null && po instanceof PjStream) {

stream = this.decodeStream(po);

newStream = this.replaceTokens(stream);

if (newStream != stream) {

stream = newStream.flateCompress();

pdf.registerObject(stream, i);

}
decodeStream(), performs stream.flateDecompress();
replaceTokens() is a simple state machine to get the strings in the stream (you
MUST read chapters 3 & 5 of the PDF Reference to know how to do this).
When the token is found, just replace it with some text, enlarging the buffer if
required (if the text is shorter than the token string, blank spaces are left after it).

It doesn´t work when the PDF is encripted, password protected or compressed


with LZW. Besides, in Adobe PDF conversion settings, "Subset embedded fonts
when percent of characters used is less than x%" must be switched off and
"Embed all fonts" must be on(otherwise your glyps could overlap).

Thanks to the Etymon PJ team for their useful library.


You should improve (*add* in some cases) the documentation though.

Re[2]: jPDF
Author: Santosh M (http://www.jguru.com/guru/viewbio.jsp?EID=1151825),
May 24, 2004
Java PDF generation API is freely available for you at
http://www.activetree.com You can use the Java RTF editor application from
www.activetree.com to edit the RTF documents and create PDF again after its
correction if necessary. Look at the online DEMO that generates PDF instantly
to generate MS Word kind of PDF documents. The Smart JPrint classes is free
and you can use its for printing and PDF generation of Swing components
such as JTable, JTextPane, JEditorPane, JTextArea. Generate PDF from your
J2EE application using by throwing lines of text to the PDF generation class.

Modifying a PDF document


Author: p123 k (http://www.jguru.com/guru/viewbio.jsp?EID=1189900), Aug 1,
2004
Hi David, Your posting has been very helpful to me. However, i ran into a few
problems while trying to modify a PDF document. I'm using PJ to do the same.
When i open the modified document using Adobe Acrobat 6.0 everthing looks
good. But when i open it using Adobe Acrobat 5.0 it doesn't display some of the
pages properly. Any thoughts ? Do u have a sample program which replaces a
particular string in a PDF using PJ or PJX ? Thanks, P

Re: Modifying a PDF document


Author: varma padmaraju
(http://www.jguru.com/guru/viewbio.jsp?EID=1192171), Aug 11, 2004

Looking for the Java APIs to search and snapshot the pdf document.

Hi
I am looking for the java APIs to perform the following tasks.

1.Search the existing PDF document to find the text.

2.Take a snapshot of the page for the copying purpose

Please let me know if somebody knew about the right product(s) for me.

Thanks, -Varma.

Converting an existing .html or .txt file to .pdf


Author: Navin Keswani (http://www.jguru.com/guru/viewbio.jsp?EID=1176976),
Aug 31, 2004
Hi Guys. Is it possible to convert an existing .html or .txt file to a .pdf file. I do not
want to create a pdf file right from scratch. I already have a file in .html or .txt and
just want to convert it to .pdf Regards, Navin Keswani.

Re: Converting an existing .html or .txt file to .pdf


Author: Santosh M (http://www.jguru.com/guru/viewbio.jsp?EID=1151825), Sep
27, 2004
Smart JPrint allows you to do this. If you have the .txt read all text and populate a
JTextArea and then pass it to the Smart JPrint AtDocumentPrinter.print(...)
methods or preview() methods for print and preview etc. It does format the text,
images, etc automatically so you do not have to break the lines to fit into the page.
you can output or print it as styled text as well. Smart JPrint API also supports to
generate PDF, TIFF, JPEG and PNG for each page of output. Try it here:
http://www.activetree.com

Re[2]: Converting an existing .html or .txt file to .pdf


Author: Jan Lao (http://www.jguru.com/guru/viewbio.jsp?EID=1228366), Feb
21, 2005
I was just wondering, is there a way for a java library to automatically detect url
and convert into active hyperlink in a PDF file. If there is, can anyone help or
teach me? I would really appreciate it. I just wanted to know how to modify an
existing PDF file so that it can detect and convert url into active hyperlink.

How do I use the java.nio.channels package to do non-blocking I/O


operations in Java 1.4?
Location: http://www.jguru.com/faq/view.jsp?EID=957291
Created: Jul 19, 2002
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

See New I/O Functionality for Java 2 Standard Edition 1.4 and Master Merlin's new
I/O classes for examples of using the new capabilities.
How do I print a PDF file using the new JDK 1.4 printing API?
Location: http://www.jguru.com/faq/view.jsp?EID=959950
Created: Jul 22, 2002 Modified: 2002-08-06 07:11:23.673
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Until someone provides a PDF print service, you can't. The standard runtime does
not provide one. Just because you can specify a DocFlavor of PDF
(DocFlavor.STRING.INPUT_STREAM.PDF) doesn't mean you can print one.

From Ivo Limmen:


You could use GhostScript to print the PDF using Process and Runtime.exec(). The
tool is available for several platforms with the same command line options so
portability isn't a large problem. (Be sure to check the license though.)

Comments and alternative answers

PDF Printing.
Author: Mark Nuttall (http://www.jguru.com/guru/viewbio.jsp?EID=462679), Jul 23,
2002
I have extensively researched this. The ONLY way I have found to print PDFs is via
Adobe's tools (visually or programmically). You can use the Java Viewer to print but
it has limited functionality. And according to the EULAs for Acrobat and Acrobat
Reader they are not to be used in a server way (i.e. shared drop directory).

One's best bet is to convert the PDF to another format and print that. And the only
way I have found to do this is with ImageMagick and Ghostscript. PDFs should be
treated as a final output not a data storage.

Anyone with other ideas, let me know.

Re: PDF Printing.


Author: Sachin Sonawane (http://www.jguru.com/guru/viewbio.jsp?EID=984715),
Aug 18, 2002
Hi, Printing of PDF can be done as follows : 1. Download pdftops.exe from net for
converting the PDF file to postscript 2. Register a LPT port to a network printer
using net use command i.e net use LPT1: \\st11\itgm3 3. Use copy command to
copy the postscript file generated to the assigned port LPT1 copy /b demo.ps LPT1
Its simple is it !!!!!!! Cheers, Sachin Sonawane

Actually, there is a few free packages for that purpose.


Author: Alex Kobyakov (http://www.jguru.com/guru/viewbio.jsp?EID=961249), Nov
7, 2002
There is two packages for creating and printing PDF files, based on retepPDF
package.
1. First is gnujpdf, available on http://sourceforge.net/projects/gnujpdf/
2. Second is Retep PDF II, available on http://www.retep.org.uk/
Second option seems to be more mature, but your mileage may vary.
Re: Actually, there is a few free packages for that purpose.
Author: accipiter zou (http://www.jguru.com/guru/viewbio.jsp?EID=1022067),
Nov 7, 2002
where can i get a better reference of reteppdf-2? the handbook in the package -
"reteppdf-2-2-1.pdf" is too empty.

Re[2]: Actually, there is a few free packages for that purpose.


Author: Peter Mount (http://www.jguru.com/guru/viewbio.jsp?EID=1144381),
Mar 19, 2004
There's more online docs now on the website (things have been too busy
recently for me to get the docs done).

However I'm restarting more development on it as there's a few commercial


projects that are now paying for new features.

However, most people tend to email me when they need help.

Java PDF solution JPDFPrinter


Author: Leila Rhaouti (http://www.jguru.com/guru/viewbio.jsp?EID=1048985), Jan
22, 2003
Take a look at JDFPrinter at www.qoppa.com.

It generates PDF documents from java programs.

It' behaving like a PrinterJob object. You can reuse existing code and it presents an
interface that java developers are already used to. It is not free though.

Retep PDF II has supported a print service since JDK1.4 came out...
Author: Peter Mount (http://www.jguru.com/guru/viewbio.jsp?EID=1144381), Mar
19, 2004
I added Print service support shortly after JDK1.4 was released, and it works pretty
well.

On most Operating systems, applications automatically see it in their print dialogs as


well (Windows and Mac's don't - not a bug, it's how the JDK works).

Simply installing the jar file in to the classpath is in theory all that's needed to install
it.

http://retep.org/retep/pdf/

Re: Retep PDF II has supported a print service since JDK1.4 came out...
Author: James Gough (http://www.jguru.com/guru/viewbio.jsp?EID=1182882), Jul
22, 2004
For printing TO PDF, right?
Your Test.java makes it very easy to print an image to a PDF, but after hunting
around for awhile in your API (the third or fourth api of the day, so maybe I'm not
seeing it) there doesn't seem to be a means to load an existing PDF and print that to
a printer. Am I missing it?

Use Smart JPrint for Printing, PDF creation and previewing output for Swing
GUI and J2EE
Author: Santosh M (http://www.jguru.com/guru/viewbio.jsp?EID=1151825), Aug 9,
2004

I recently downloaded the Smart JPrint Java classes from http://www.activetree.com


for printing multiple Swing components. I have multiple JTable, JTextArea, and
JTextPane in my GUI that I wanted to print by combining the output of all of them
together. The JPrint did that so wanderfully. I understand tha the JPrint can be also
used in the J2EE environment.

I also noticed that it PDF generates the same and shows a very good preview window.
The preview window also allows to print and PDF generate the output.

What you do is that generate a PDF if desired and then pass the same output pages to
a printer to print at the same time. If you do not want to PDF generate, then send the
output pages to the printer to just print it.

You can check out their online demo applets to try things online.

Re: Use Smart JPrint for Printing, PDF creation and previewing output for
Swing GUI and J2EE-going a little offtopic, sorry!
Author: James Gough (http://www.jguru.com/guru/viewbio.jsp?EID=1182882),
Aug 10, 2004
One quick thing, you misspelled "wonderful" (as "wanderful") in your message,
which is curious because in the ActiveTree description of the product on thier
webpage, they also misspell wonderful the same way. Sorry to go offtopic, I just
found the similarity curious.

PDF Printing versus creating PDFs


Author: James Gough (http://www.jguru.com/guru/viewbio.jsp?EID=1182882), Aug
10, 2004
I think that there is some confusion on this issue, as I have been researching this for
several weeks now, and really have found that many discussions of this topic go
slightly off topic because of terminology.

There are 2 seperate and distinct actions that one may want to perform concerning
PDFs that involve the word "print".

1. Creating a PDF - Your desired end product is a PDF file, and you can create it
programatically or via a print service. This is not "printing a PDF", it is at best
"printing to a PDF". If you wish to create it with a Java program, I suggest Bruno
Lowagie's IText which can be found at www.lowagie.com, I have used it for 2 years
and it's really a very good package. As for a print service I checked out Retep II, and
it looked good, but I have no practical experience with it.

2. PRINTING a PDF - Your desired end product is a piece of paper with the contents
of a PDF file on it. It appears as if the only way anyone does this is with a
commandline call to Acrobat (so much for platform independence!), use of
ghostscript (which has to be installed), or a commercial product such as JPedal which
to me seems very expensive when all I want to do is print.

It's quite distressing that there really seems to be no way to print a PDF using pure
Java (even 2 years after the 1.4 Print Service was introduced with a PDF DocFlavor!).
Use of Adobe's unmaintained Reader Bean has produced mixed results, and I cannot
afford to have blank pages printed half the time my customers want to print
something.

Have I fogotten anything?

Re: PDF Printing versus creating PDFs


Author: Daniel Lévy (http://www.jguru.com/guru/viewbio.jsp?EID=1194341),
Aug 20, 2004
If you dont bother that the application would start a browser, try PdfPrint 3.5.2
from activepdf.com. I have tried out this solution, since it is an unexpensive
plugin. The support for evaluators is very good. It works fine, but be careful, it
doesnt work yet with the new Adobe Reader 6.0 and you have to do some minor
patches if you use Internet Explorer 5.5 with SP2 or 6.0. Hope this is helpful for
somebody. Regards, - Daniel

Pure Java Solution et al. Re[2]: PDF Printing versus creating PDFs
Author: Zhou Wu (http://www.jguru.com/guru/viewbio.jsp?EID=409114), Aug
25, 2004
See this link: http://www.mycgiserver.com/~zhouwu/pdf/readme.html

Re: Pure Java Solution et al. Re[2]: PDF Printing versus creating
PDFs
Author: dwight smith
(http://www.jguru.com/guru/viewbio.jsp?EID=1202496), Sep 29, 2004
I tried the example shown on the link, but I get a null pointer exception
when it calls printAll(). Is there something else I need to do that is not
talked about in the example? Has anyone else seen this error?
Print PDF from Java using Adobe Reader 6
Author: Ingo Jobling (http://www.jguru.com/guru/viewbio.jsp?EID=1199343), Sep 15, 2004
After many hours of sweat and tears, here is my solution. It uses Adobe Reader 6.
Regards,
Ingo
/********************************************************************************
**
*
* printPDF
*
* Prints a PDF using Adobe Reader "/t" (print and terminate)
*
* @param File File to be printed, for example, C:\MYFILE.PDF
* @param Printer Printer, for example, \\MYSERVER\MYPRINTER
*
*********************************************************************************
***/

public static void printPDF(String pFile, String pPrinter)


{
final String PATH_ADOBE_READER = "C:\\Program Files\\Adobe\\Acrobat
6.0\\Reader\\AcroRd32.exe";
final String ADOBE_READER_PRINT_COMMAND = "/t";
final String SLASH = "/";
final String QUOTE = "\"";
final String SPACE = " ";

// Command to be executed
String lCommand = QUOTE + PATH_ADOBE_READER + QUOTE + SPACE +
ADOBE_READER_PRINT_COMMAND + SPACE +
QUOTE + pFile + QUOTE + SPACE +
QUOTE + pPrinter + QUOTE;

System.out.println("[printPDF] Command to be executed : " + lCommand);

Process lAdobeBackGroundProcess = null;


Process lAdobeProcess = null;

try
{
// Must create a background Adobe Reader process (don't ask why, just do
lAdobeBackGroundProcess = Runtime.getRuntime().exec(PATH_ADOBE_READER);

// Execute the Adobe Reader command "/t" (print and terminate)


lAdobeProcess = Runtime.getRuntime().exec(lCommand);

// Wait for Adobe Reader to complete


int exitVal = lAdobeProcess.waitFor();
if ( exitVal != 0 )
{
throw new Exception("[printPDF] Adobe Reader process exitVal : " + ex
}
}
catch (Exception e)
{
System.err.println("[printPDF] Error printing PDF : " + pFile);
e.printStackTrace();
}
finally
{
if (lAdobeBackGroundProcess != null)
{
lAdobeBackGroundProcess.destroy();
lAdobeBackGroundProcess = null;
}
}
}

Re: Print PDF from Java using Adobe Reader 6


Author: Pepe Caballero (http://www.jguru.com/guru/viewbio.jsp?EID=1203377),
Oct 5, 2004
Whats happen if you use the program in Windows XP and Windows 98 or you
install Adobe in differents directories. I found a utility called printpdf that allow
you to use adobe from diferente OS and diferents installed directories but it doesn
´t allow to use option s (like \t) for adobe reader. I would like to know (too) if
exist any option to print diferents pages of a pdf documents. Any help? thanks
Pepe Caballero

Re[2]: Print PDF from Java using Adobe Reader 6


Author: Kilian Braune
(http://www.jguru.com/guru/viewbio.jsp?EID=1214068), Dec 1, 2004
Hola Pepe!

There is a very easy way to extract (but unfortunately not to print(!)) defined
pages of a pdf file under java.

see>> http://www.lowagie.com/iText/tutorial/ch13.html and there have a look


at >> com.lowagie.tools.split_pdf.

you might aswell just leave out "destfile2" and u will get the defined page you
want to have from a pdf!

rgds, Kilian

Re[3]: Print PDF from Java using Adobe Reader 6


Author: Santosh M
(http://www.jguru.com/guru/viewbio.jsp?EID=1151825), Jan 20, 2005
The question was about "availability of Java APIs for existing PDF file
printing?"

I know Smart JPrint does this. I mean you can use SmartJPrint pure Java
APIs for printing and viewing PDF documents (silently or with user
intervention):

• PDF file from local file system


• PDF file from remote web location using the document URL.
• PDF data bytes in program memory

In addition SmartJPrint is a printing, report generation and previewing


tools for any kind of Java program.

Re[4]: Print PDF from Java using Adobe Reader 6


Author: Jens Moller
(http://www.jguru.com/guru/viewbio.jsp?EID=1236516), Apr 4, 2005
I use Adobe Reader 4 in this application. Its for Windows with Java 1.4
of later. Complete with a GUI.

http://b2b-securesite.com/PDFPrinter.zip

Complete source code provided in the src sub directory.

I used parts of one of the sample Java functions to resolve the execution
of AcroRd32.exe, but found it unreliable unless it was called via a
Batch File.

It should work with V 6.0 too (or even 5.0).

Re: Print PDF from Java using Adobe Reader 6


Author: Krishna Prasad (http://www.jguru.com/guru/viewbio.jsp?EID=1245550),
May 24, 2005

This code snippet does not seem to work fine.I get the following exception:

java.lang.Exception: [printPDF] Adobe Reader process exitVal : 1

Though the program runs and prints the document succesfully, I get the above
error once i close the Acrobat reader. Can someone help me with this.

Also, is it possible to print the document silently without having the acrobat reader
opened (something that is seen in Smart JPrint)?

I have tried the Smart JPrint, but it is licenced.I want to know if there is any API
that is a freeware.

Thank you,

Krishna

What's the difference between a StringBuffer and StringBuilder?


Location: http://www.jguru.com/faq/view.jsp?EID=1251263
Created: Jun 30, 2005
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The StringBuilder class was introduced with JDK 5.0. Essentially, a StringBuffer is a
thread-safe version of StringBuilder. If you are only adding/removing characters from
a single-thread, the StringBuilder implementation will be faster. If you are using
multiple threads to add and remove characters, use StringBuffer.

How do I do C-style formatted printing, like with printf?


Location: http://www.jguru.com/faq/view.jsp?EID=1251264
Created: Jun 30, 2005
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The java.util.Formatter class was introduced in JDK 5.0 and offers locale-
sensitive formatting of numbers and strings.

How do I use the java.util.Formatter class to format output?


Location: http://www.jguru.com/faq/view.jsp?EID=1251265
Created: Jun 30, 2005
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

There are at least three ways to generate formatted output:

• Use the format() method of an instance of Formatter.


• Use the format()/printf method of an OutputStream, as in
System.out.format("The time is %tT.", Calendar.getInstance());
• Use the format() method of String, as in String.format("Today is %1$tm
%1$te,%1$tY", Calendar.getInstance());

How do I print a JTable?


Location: http://www.jguru.com/faq/view.jsp?EID=1251266
Created: Jun 30, 2005
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

JDK 5.0 provides built in support for printing tables. Just call the print() method of
JTable. Here's an example of such.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.print.*;
import java.text.*;

public class TablePrint {


public static void main(String args[]) {
final Object rows[][] = {
{"one", "ichi - \u4E00"},
{"two", "ni - \u4E8C"},
{"three", "san - \u4E09"},
{"four", "shi - \u56DB"},
{"five", "go - \u4E94"},
{"six", "roku - \u516D"},
{"seven", "shichi - \u4E03"},
{"eight", "hachi - \u516B"},
{"nine", "kyu - \u4E5D"},
{"ten", "ju - \u5341"},
{"one", "ichi - \u4E00"},
{"two", "ni - \u4E8C"},
{"three", "san - \u4E09"},
{"four", "shi - \u56DB"},
{"five", "go - \u4E94"},
{"six", "roku - \u516D"},
{"seven", "shichi - \u4E03"},
{"eight", "hachi - \u516B"},
{"nine", "kyu - \u4E5D"},
{"ten", "ju - \u5341"},
{"one", "ichi - \u4E00"},
{"two", "ni - \u4E8C"},
{"three", "san - \u4E09"},
{"four", "shi - \u56DB"},
{"five", "go - \u4E94"},
{"six", "roku - \u516D"},
{"seven", "shichi - \u4E03"},
{"eight", "hachi - \u516B"},
{"nine", "kyu - \u4E5D"},
{"ten", "ju - \u5341"},
{"one", "ichi - \u4E00"},
{"two", "ni - \u4E8C"},
{"three", "san - \u4E09"},
{"four", "shi - \u56DB"},
{"five", "go - \u4E94"},
{"six", "roku - \u516D"},
{"seven", "shichi - \u4E03"},
{"eight", "hachi - \u516B"},
{"nine", "kyu - \u4E5D"},
{"ten", "ju - \u5341"},
{"one", "ichi - \u4E00"},
{"two", "ni - \u4E8C"},
{"three", "san - \u4E09"},
{"four", "shi - \u56DB"},
{"five", "go - \u4E94"},
{"six", "roku - \u516D"},
{"seven", "shichi - \u4E03"},
{"eight", "hachi - \u516B"},
{"nine", "kyu - \u4E5D"},
{"ten", "ju - \u5341"},
{"one", "ichi - \u4E00"},
{"two", "ni - \u4E8C"},
{"three", "san - \u4E09"},
{"four", "shi - \u56DB"},
{"five", "go - \u4E94"},
{"six", "roku - \u516D"},
{"seven", "shichi - \u4E03"},
{"eight", "hachi - \u516B"},
{"nine", "kyu - \u4E5D"},
{"ten", "ju - \u5341"},
{"one", "ichi - \u4E00"},
{"two", "ni - \u4E8C"},
{"three", "san - \u4E09"},
{"four", "shi - \u56DB"},
{"five", "go - \u4E94"},
{"six", "roku - \u516D"},
{"seven", "shichi - \u4E03"},
{"eight", "hachi - \u516B"},
{"nine", "kyu - \u4E5D"},
{"ten", "ju - \u5341"},
{"one", "ichi - \u4E00"},
{"two", "ni - \u4E8C"},
{"three", "san - \u4E09"},
{"four", "shi - \u56DB"},
{"five", "go - \u4E94"},
{"six", "roku - \u516D"},
{"seven", "shichi - \u4E03"},
{"eight", "hachi - \u516B"},
{"nine", "kyu - \u4E5D"},
{"ten", "ju - \u5341"},
{"one", "ichi - \u4E00"},
{"two", "ni - \u4E8C"},
{"three", "san - \u4E09"},
{"four", "shi - \u56DB"},
{"five", "go - \u4E94"},
{"six", "roku - \u516D"},
{"seven", "shichi - \u4E03"},
{"eight", "hachi - \u516B"},
{"nine", "kyu - \u4E5D"},
{"ten", "ju - \u5341"},
{"one", "ichi - \u4E00"},
{"two", "ni - \u4E8C"},
{"three", "san - \u4E09"},
{"four", "shi - \u56DB"},
{"five", "go - \u4E94"},
{"six", "roku - \u516D"},
{"seven", "shichi - \u4E03"},
{"eight", "hachi - \u516B"},
{"nine", "kyu - \u4E5D"},
{"ten", "ju - \u5341"},
};
final Object headers[] = {"English", "Japanese"};
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("Table Printing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTable table = new JTable(rows, headers);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
JButton button = new JButton("Print");
ActionListener printAction = new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
MessageFormat headerFormat = new MessageFormat("Page
{0}");
MessageFormat footerFormat = new MessageFormat("- {0} -");
table.print(JTable.PrintMode.FIT_WIDTH, headerFormat,
footerFormat);
} catch (PrinterException pe) {
System.err.println("Error printing: " + pe.getMessage());
}
}
};
button.addActionListener(printAction);
frame.add(button, BorderLayout.SOUTH);
frame.setSize(300, 150);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
}

How do I read formatted input from the command line?


Location: http://www.jguru.com/faq/view.jsp?EID=1251268
Created: Jun 30, 2005
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The java.util.Scanner constructor takes a file, channel, input stream, or


reader as an argument and lets you read an int (with nextInt()), read a line (with
nextLine()), or any other data type with an aptly named next*() method.

Why can't I use Unicode supplementary characters in JDK 1.4?


Location: http://www.jguru.com/faq/view.jsp?EID=1251269
Created: Jun 30, 2005
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

JDK 5.0 added support for code points above U+FFFF. Additional information is
available from Supplementary Characters in the Java Platform.

What is the deal with the Closeable and Flushable interfaces?


Location: http://www.jguru.com/faq/view.jsp?EID=1255936
Created: Jul 31, 2005
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The ability to close() or flush() an object (typeically a stream) has been factored out
into single method interfaces, Closeable and Flushable, respectively. Given that you
sometimes need to operate on different types of objects, like InputStream,
OutputStream, RandomAccessFile, and Formatter, when your done working with the
class, you don't always care what it was you operated on. Thus, instead of having
different "done" like methods to close or fLush the object, you can deal with just one
for all types, as long as they implement Closeable or Flushable.

Why would I want to use the Appendable interface?


Location: http://www.jguru.com/faq/view.jsp?EID=1255937
Created: Jul 31, 2005
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The Appendable interface and its append() methods are implemented in classes that
support adding characters to the end of an object, typically a stream. Indirectly used
through the Formatter class, you can attach a character, CharSequence, or
CharSequence subset. The classes that implement Appendable are BufferedWriter,
CharArrayWriter, CharBuffer, FileWriter, FilterWriter, LogStream, OutputStreamWriter,
PipedWriter, PrintStream, PrintWriter, StringBuffer, StringBuilder, StringWriter, and
Writer.

How do I print to a file?


Location: http://www.jguru.com/faq/view.jsp?EID=1255946
Created: Jul 31, 2005
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Typically, you would create a FileOutputStream and pass it to the PrintStream


constructor. Starting with 5.0, you can pass the File or String name for file directory
to the PrintStream constructor.

How do I find out the default character set for the JVM?
Location: http://www.jguru.com/faq/view.jsp?EID=1255948
Created: Jul 31, 2005
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Added to JDK 5.0, you can call the defaultCharset() method of the CharSet class,
found in the java.nio.charset package. This is apt to depend upon the locale and
character set of the underlying system.

You might also like