I/o Input / Output

1) How can I compress my data to save bandwidth when sending across a socket?
The GZIPInputStream and GZIPOutputStream classes found in the java.util.zip package compress data with the GZIP file format, as defined by RFC 1952
2) How do I append to end of a file in Java?
You can use java.io.RandomAccessFile and something like the following:

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

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

3) How can I see from an applet the names of files and directories that are in the server?

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.
4) How can I read .zip and .jar file using standard Java classes?

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

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

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

5) How do I check for end-of-file when reading from a stream?

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.
6) Under what circumstances would I use random access I/O over sequential, buffered I/O?

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.
7) How do I get a listing of the files in a directory?

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.

8) Where can I store temporary files?

The java.io.tmpdir system property defines an appropriate area:
String tempPath = System.getProperty("java.io.tmpdir");
File f = new File(tempPath, "test.out");
9) How can I change time and date of a file?

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.
10) How do I create a temporary file?

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");
// use temp like any other File
11) How do I delete a file / directory?

Use the delete() method of the File class.
12) How do I read text from standard input?

System.in is the InputStream for standard input. The following demonstrating reading from it a line at a time:
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(isr);
String line = null;
while ((line = reader.readLine()) != null) {
// Process line
13) How do I write text to a file?

Writing text involves writing strings, so you would use a FileWriter.
FileWriter fw = new FileWriter(filename);
PrintWriter pw = new PrintWriter(fw);
pw.println("Hello, World");
14) How do I copy a file?

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.
15) What is a stream?

Basically, a stream is an ordered look at a sequence of bytes for input or output.
Low-level streams provide direct access to the underlying bytes, like a FileInputStream, FileOutputStream, or CharArrayWriter, where reading and writing work directly with the underlying input/output device. High-level streams, or filters, instead build upon the low-level streams to provide additional capabilities, like buffering, counting lines, compressing data, or reading/writing higher-level data members like primitives or objects. You can chain multiple filters together to get multiple higher-level operations on a single low-level stream.
16) How can I open the same file for reading as well as writing?

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.
17) How do I list all drives/filesystem roots on my system?

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 System.out.println("Root["+i+"]:" + roots[i]);
18) How to insert content into the middle of a file without overwriting the existing content?

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.
19) How do I get the creation date and time of a file?

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.
20) How can you combine multiple input streams to be treated as one?

The SequenceInputStream class in the standard java.io package allows you to combine multiple input streams into one. You can either create a vector of streams, passing the elements() to the constructor, or combine two directly in a constructor.
21) How can I rename a file?

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.
22) When do you use the Reader/Writer classes, instead of the InputStream/OutputStream classes?

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.
23) How can I make a file writable that is currently read-only?

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.
24) How can I trap system-specific key sequences like Ctrl-Alt-Del?

Alas, using pure, portable Java, you cannot trap those sorts of system-specific key sequences.
25) How can I get the current working directory with Java?

The current working directory is stored in the system property "user.dir". The following example shows how to read this system property from your application:
public class userdir {
public static void main(String[] args) {
System.out.println("Working Directory = " +
26) What is a resource leak?

Garbage collection manages only memory, not other system resources. If your Java program has plenty of free memory, garbage collection will not be triggered automatically. Usually, however, there are other resources that are more limited than memory. For example, all OSes have limits on the number of sockets, file handles, etc. that can be open. Sometimes this limit is quite low. This is true even on a desktop, e.g. if your system has 128KB of memory, your Java program can easily allocate all the available file handles without coming near to filling up the heap. If this happens, your Java program will fail. This is what we call a resource leak; the unintentional maintenence of references to non-memory resources.
This is why it is important in Java to explicitly manage non-memory resources. Classes which utilize non-memory resources should provide ways to explicitly allocate/deallocate those resources, independent of garbage collection. For example Socket, InputStream and OutputStream each provide explicit close() methods for deallocation of file descriptors, Window provides a dispose() method to free the window handle, etc. The way to properly use these classes is to allocate using the constructor, then deallocate using the appropriate method (deallocation is preferably done in a finally{} block, so it will execute whether or not an exception is thrown during use). These classes do release these non-memory resources in their finalize() method, but remember that the finalizer only gets called by the garbage collector, and if the object is never collected, it will never be finalized, hence will never release the resources.
27) Why are there two type of I/O in Java, namely byte streams and character (Reader/Writer) streams?

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.
28) Is there an easy way of counting line numbers? Or do you have to go through the entire file?

You have to go through the entire file.
try {
LineNumberReader lnr = new LineNumberReader(new FileReader(filename));
String s;
while ((s = lnr.readLine()) != null);
System.out.println("Lines: " + lnr.getLineNumber());
29) What is piped I/O used for?

The piped I/O streams are for inter-thread communication. They manage the synchronization across thread boundaries of the buffer.
30) How can I show a progress bar while reading a file?

Here's a simple example of monitoring file read progress
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.InputStream;

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

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

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

// display the frame
31) How do I initialize a JTextArea from an input file?

The JTextComponent provides a read() method to initialize the text component:
JTextArea ta = new JTextArea();
Reader reader = new FileReader(filename);
ta.read(reader, null);
The second parameter is a description.
32) How to make a file read only?

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.

No comments: