Professional Documents
Culture Documents
Location: http://www.jguru.com/faq/IO
Ownership: http://www.jguru.com/misc/user-agree.jsp#ownership.
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
Yes. In fact, it is recommended that you buffer all your input and output unless you
have a good reason not to.
...
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?
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.
0.0
10,000.0
100,000,000.0
25.25
-10.12
For additional formatting options, see the description of the DecimalFormat class.
The System class allows you to reassign where these streams go to with either the
static setOut(PrintStream) method or the setErr(PrintStream) method.
The JFileDialog provides a better alternative that supports filters, if you can use the
Swing component set.
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.
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.
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'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;
}
}
}
}
// .....
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.
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.
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
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
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.
--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.
[Updated Nov 20, 2002 to remove old description and point at some articles. TJP]
jGuru.com Case-Study.
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
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.*;
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);
while(enum.hasNext())
{
ZipEntry zEntry =(ZipEntry)enum.next();
if (isZipFile(zEntry)==true)
{
InputStream is =
zFile.getInputStream(zEntry);
ZipInputStream zIs = mew
ZipInputStream(is);
if(ze==null) {
break; //no more entries
}
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 }
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. :-)))))
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\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).
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.
The following example demonstrates their usage and was taken from my Mastering
Java 2 book:
import java.io.*;
public OilRefinery() {
start(); // Start the thread
}
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!");
}
}
}
try {
crudePipe.write (oilToBeRefined);
crudePipe.close();
// class with main entry point. Creates the refinery and tanker(s).
public class Pipeline
{
public static void main (String args[])
{
OilRefinery.create();
class Request
{
String message;
Requestor requestor;
interface Requestor
{
void response( String responseMessage );
}
private OilRefinery()
{
mConnectQue = new LinkedList();
keepRefining = true;
return cRefinery;
}
while (keepRefining)
{
Request request;
synchronized ( mConnectQue )
{
while ( mConnectQue.size() == 0 )
{
try
{
mConnectQue.wait();
}
catch ( InterruptedException e )
{
}
}
processRequest( request );
processRequest( request );
}
if ( request.message.equalsIgnoreCase("shutdown") )
{
keepRefining = false;
return;
}
if ( request.requestor != null)
{
String responseMessage = request.message.toUpperCase();
request.requestor.response( responseMessage );
}
}
}
String name;
public SuperTanker(String name)
{
this.name = name;
setDaemon( true );
start();
}
(...or any other IO method that wraps read(), like BufferedReader.readLine(). Calling
thread.interrupt() does nothing.)
See the new (Java 1.4) java.nio.channels package for non-blocking I/O
support.
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:
It's not fancy, but I think when you want speed simple is good.
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.*;
// Initialize a flag that will indicate that the jar was updated.
try {
// Create a temp jar file with no manifest. (The manifest will
// be copied when the entries are copied.)
try {
// Open the given file.
// Loop through the jar entries and add them to the temp
jar,
// skipping the entry that was added to the temp jar
already.
if (! entry.getName().equals(fileName)) {
// Get an input stream for the entry.
tempJar.putNextEntry(entry);
jarUpdated = true;
}
catch (Exception ex) {
System.out.println(ex);
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:
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
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();
} // 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
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.
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=...
• 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
How can I store and retrieve Unicode or Double Byte data in a file using the java.io
libraries?
Regexp is a 100% Pure Java Regular Expression package. It can be downloaded from
http://jakarta.apache.org/regexp/
Also note that as of version 2.0, the ORO regexp package has been turned over to
the Jakarta project as well.
import java.io.*;
import java.net.*;
import java.util.zip.*;
The following table demonstrates the compression results. Depending upon the type
of input, the results can vary considerably.
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
http://java.sun.com/products/jdk/1.2/docs/guide/internat/encoding.doc.html
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.
File f = File.createTempFile("TMP","DAT");
See How do I create a temporary file? for more info.
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.
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.
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/
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.
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
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
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];
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
String sourceFileAddress;
String destinationFileAddress;
try{
java.io.FileInputStream SourceFile=new
java.io.FileInputStream(sourceFileAddress);
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();
DestinationFile.close();
}catch(Exception e)
//Happy copying
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.
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.
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.
Can you throw some more light on this ??? Any references /
articles / explanation...highly appreciated.
Sam
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
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
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.
UTF stands for UCS Transformation Format, where UCS stands for Universal
Character Set.
Comments and alternative answers
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.
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);
}
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
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?
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
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
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
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:
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
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.
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.*;
System.out.println("\n");
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);
}
}
} // End class EncString
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:
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.
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.
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
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.
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.
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
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.
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.]
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.
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.
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 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.
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;
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];
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.
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.
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'.
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).
Alas, using pure, portable Java, you cannot trap those sorts of system-specific key
sequences.
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.
To add main attributes to an existing manifest object, use the read() method of
Manifest like so:
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.
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?
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 {
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.*;
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 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!)
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.*;
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.
Your directory hierarchy picture has too many "/home" strings in it. It should just look
like this:
/home/topgun
|
+-- middleearth
|
+-- bottomman -> /home/topgun
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.
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.
import java.io.*;
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 ",:"
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.
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.
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:
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.*;
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.
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
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:
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;
}
}
int l = (int)(file.length()-pos);
Eoin
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.*;
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
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:
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.
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
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
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
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
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)
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)
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)
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
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
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
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];
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.
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.
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.
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.
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.
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.
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.
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
outStream.close();
}
catch(Exception 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.
\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.
import java.io.*;
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).
/**
* 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();
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.*;
/**
* 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:
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:
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"));
int ch;
int readings = 0;
boolean marked = false;
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
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.
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);
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
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)
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;
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...
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.
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.
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/
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
java.util.Properties objects can load values from a file using the method
load(InputStream).
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.
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:
All the put() methods return a void. If the storage mechanism is unavailable, a
BackingStoreException will be thrown.
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:
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.
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.
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;
.
.
.
files[i].delete();
}
}
You may want to do some more error checking, etc. but that should basically work.
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).
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.
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.
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.
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.
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
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?
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);
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
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.
...
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... ;-)
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
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
BR,
~A
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]
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:
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).
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
• 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.
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 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
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.
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...
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:
po = pdf.getObject(i);
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).
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.
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.
Please let me know if somebody knew about the right product(s) for me.
Thanks, -Varma.
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.
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.
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.
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 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.
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.
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
*
*********************************************************************************
***/
// Command to be executed
String lCommand = QUOTE + PATH_ADOBE_READER + QUOTE + SPACE +
ADOBE_READER_PRINT_COMMAND + SPACE +
QUOTE + pFile + QUOTE + SPACE +
QUOTE + pPrinter + QUOTE;
try
{
// Must create a background Adobe Reader process (don't ask why, just do
lAdobeBackGroundProcess = Runtime.getRuntime().exec(PATH_ADOBE_READER);
There is a very easy way to extract (but unfortunately not to print(!)) defined
pages of a pdf file under java.
you might aswell just leave out "destfile2" and u will get the defined page you
want to have from a pdf!
rgds, Kilian
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):
http://b2b-securesite.com/PDFPrinter.zip
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.
This code snippet does not seem to work fine.I get the following exception:
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
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.
The java.util.Formatter class was introduced in JDK 5.0 and offers locale-
sensitive formatting of numbers and strings.
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.*;
JDK 5.0 added support for code points above U+FFFF. Additional information is
available from Supplementary Characters in the Java Platform.
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.
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 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.