wpjr2’s Weblog

Artigos e tutoriais úteis

Arquivo para Maio 3rd, 2008

Infograma das classes do Java IO

Escrito por wpjr2 em Maio 3, 2008

Enviado em Curso de Programação Java | Tagged: | Nenhum comentário »

Resumo dos Fluxos de Dados em Java (2)

Escrito por wpjr2 em Maio 3, 2008

Type of I/O Streams Description
Memory CharArrayReader
CharArrayWriter
ByteArrayInputStream
ByteArrayOutputStream
Read from and write to memory. Create on an existing array and then use the read and write methods to read from or write to the array.
Memory StringReader
StringWriter
StringBufferInputStream
top>StringReader reads characters from a String in memory.StringWriter writes to a String, collecting characters written to it in a StringBuffer, which can then be converted to a String.StringBufferInputStream is similar to StringReader, except that it reads bytes from a StringBuffer.
Pipe PipedReader
PipedWriter
PipedInputStream
PipedOutputStream
Implement the input and output components of a pipe. Pipes are used to channel the output from one thread into the input of another.
File FileReader
FileWriter
FileInputStream
FileOutputStream
Collectively called file streams, these streams are used to read from or write to a file on the native file system.
Concatenation N/A
SequenceInputStream
Concatenates multiple input streams into one input stream.
Object Serialization N/A
ObjectInputStream
ObjectOutputStream
Used to serialize objects.
Data
Conversion
N/A
DataInputStream
DataOutputStream
Read or write primitive data types in a machine-independent format.
Counting LineNumberReader
LineNumberInputStream
Keeps track of line numbers while reading.
Peeking Ahead PushbackReader
PushbackInputStream
These input streams each have a pushback buffer. When reading data from a stream, it is sometimes useful to peek at the next few bytes or characters in the stream to decide what to do next.
Printing PrintWriter
PrintStream
Contain convenient printing methods. These are the easiest streams to write to, so you will often see other writable streams wrapped in one of these.
Buffering BufferedReader
BufferedWriter
BufferedInputStream
BufferedOutputStream
Buffer data while reading or writing, thereby reducing the number of accesses required on the original data source. Buffered streams are typically more efficient than similar nonbuffered streams and are often used with other streams.
Filters FilterReader
FilterWriter
FilterInputStream
FilterOutputStream
These abstract classes define the interface for filter streams, which filter data as it’s being read or written.
Convert InputStreamReader
OutputStreamWriter
Convert byte streams to character streams, and vice-versa.InputStreamReaders read bytes from InputStreams and convert them to characters. OutputStreamWriters convert characters to bytes and write to an OutputStream. Default character encodings are stored in System.getProperty(”file.encoding”).

Enviado em Curso de Programação Java, Uncategorized | Tagged: , , | Nenhum comentário »

Resumo dos Fluxos de Dados em Java

Escrito por wpjr2 em Maio 3, 2008

How to choose/use Streams

Choosing IO Streams

(1) Memory IO
Array : create these streams on an existing array and then use the read and write methods to read from or write to the array.

CharArrayReader, CharArrayWriter
ByteArrayInputStream, ByteArrayOutputStream

String : to read/write characters from/to a String in memory.

StringReader, StringWriter
StringBufferInputStream

(2) Pipe IO

Pipe : Pipes are used to channel the output from one thread into the input of another.

PipedReader, PipedWriter
PipedInputStream, PipedOutputStream

(3) File IO

File : to read from or write to a file on the native file system.

FileReader, FileWriter
FileInputStream, FileOutputStream

(4) Concatenation

Concatenation : concatenates multiple input streams into one input stream.

N/A
SequenceInputStream

(5) Object Serialization

Object Serialization : used to serialize objects.

N/A
ObjectInputStream, ObjectOutputStream

(6) Data Conversion

Data Conversion : Read or write primitive data types in a machine-independent format.

N/A
DataInputStream, DataOutputStream

(7) Counting

Counting : keeps track of line numbers while reading.

LineNumberReader
LineNumberInputStream

( 8) Peeking Ahead

Peeking Ahead : These input streams each have a pushback buffer. When reading data from a stream, it is sometimes useful to peek at the next few bytes or characters in the stream to decide what to do next.

PushbackReader
PushbackInputStream

(9) Printing

Printing : contain convenient printing methods.

PrintWriter
PrintStream

(10) Buffering

Buffering : buffer data while reading or writing, thereby reducing the number of accesses required on the original data source.

BufferedReader, BufferedWriter
BufferedInputStream, BufferedOutputStream

(11) Filtering

Filtering : These abstract classes define the interface for filter streams, which filter data as it’s being read or written.

FilterReader, FilterWriter
FilterInputStream, FilterOutputStream

(12) Converting between Bytes and Characters

Converting : A reader and writer pair that forms the bridge between byte streams and character streams.

InputStreamReader, OutputStreamWriter

File Streams

The file streams– FileReader, FileWriter, FileInputStream, and FileOutputStream– read or write from/to a file on the native file system.

1.Create File Object - optional
2.Create File Stream Object using File Obejct or String file name
3.read from / write to the stream
4.close the stream

File f = new File(”data.txt”)
FileReader fr = new FileReader(f)
int c = fr.read();
close(fr);

File f = new File(”data.txt”)
FileWriter fw = new FileWriter(f)
fw.write(c);
close(fw);

Pipe Streams

Pipes are used to channel the output from one thread into the input of another. PipedReader and PipedWriter (PipedInputStream and PipedOutputStream) implement the input and output components of a pipe.
A piped input stream should be connected to a piped output stream. Typically, data is read from a PipedInputStream(PipedReader) object by one thread and data is written to the corresponding PipedOutputStream(PipedWriter) by some other thread. Attempting to use both objects from a single thread is not recommended, as it may deadlock the thread.

To make Pipe Connections, Use constructor or connect method. There are 4 ways to connects pipe streams.

PipedWriter pipeOut = new PipedWriter();
PipedReader pipeIn = new PipedReader(pipeOut);

PipedReader pipeIn = new PipedReader();
PipedWriter pipeOut = new PipedWriter(pipeIn);

PipedWriter pipeOut = new PipedWriter();
PipedReader pipeIn = new PipedReader();
pipeOut.connect(pipeIn);

PipedWriter pipeOut = new PipedWriter();
PipedReader pipeIn = new PipedReader();
pipeIn.connect(pipeOut);

Concatenation

The SequenceInputStream creates a single input stream from multiple input sources. It represents the logical concatenation of other input streams,

SequenceInputStream has 2 kinds of constructors.

public SequenceInputStream(Enumeration e)
publicSequenceInputStream(InputStream s1, InputStream s2)

Example - Concatenating Files

1.Make the list of files to be concatenated using Enumeration.
2.Creating the SequenceInputStream
3.Read data from the SequenceInputStream
4.Write them to the file

Enviado em Curso de Programação Java | Tagged: , , , , , | Nenhum comentário »

Arquivos de Acesso Aleatório (Tutorial Oficial da Sun)

Escrito por wpjr2 em Maio 3, 2008

Random Access Files

Random access files permit nonsequential, or random, access to a file’s contents.Consider the archive format known as ZIP. A ZIP archive contains files and is typically compressed to save space. It also contains a directory entry at the end that indicates where the various files contained within the ZIP archive begin, as shown in the following figure.

A ZIP archive.

A ZIP archive.

Suppose that you want to extract a specific file from a ZIP archive. If you use a sequential access stream, you have to:

  1. Open the ZIP archive.
  2. Search through the ZIP archive until you locate the file you want to extract.
  3. Extract the file.
  4. Close the ZIP archive.

Using this procedure, on average, you’d have to read half the ZIP archive before finding the file that you want to extract. You can extract the same file from the ZIP archive more efficiently by using the seek feature of a random access file and following these steps:

  • Open the ZIP archive.
  • Seek to the directory entry and locate the entry for the file you want to extract from the ZIP archive.
  • Seek (backward) within the ZIP archive to the position of the file to extract.
  • Extract the file.
  • Close the ZIP archive.

This algorithm is more efficient because you read only the directory entry and the file that you want to extract.The java.io.RandomAccessFile class implements both the DataInput and DataOutput interfaces and therefore can be used for both reading and writing. RandomAccessFile is similar to FileInputStream and FileOutputStream in that you specify a file on the native file system to open when you create it. When you create a RandomAccessFile, you must indicate whether you will be just reading the file or also writing to it. (You have to be able to read a file in order to write it.) The following code creates a RandomAccessFile to read the file named xanadu.txt:

new RandomAccessFile("xanadu.txt", "r");

And this one opens the same file for both reading and writing:

new RandomAccessFile("xanadu.txt", "rw");

After the file has been opened, you can use the common read or write methods defined in the DataInput and DataOutput interfaces to perform I/O on the file.RandomAccessFile supports the notion of a file pointer. The file pointer indicates the current location in the file. When the file is first created, the file pointer is set to 0, indicating the beginning of the file. Calls to the read and write methods adjust the file pointer by the number of bytes read or written.

A ZIP file has the notion of a current file pointer.

A ZIP file has the notion of a current file pointer.

In addition to the normal file I/O methods that implicitly move the file pointer when the operation occurs, RandomAccessFile contains three methods for explicitly manipulating the file pointer.

  • int skipBytes(int) — Moves the file pointer forward the specified number of bytes
  • void seek(long) — Positions the file pointer just before the specified byte
  • long getFilePointer() — Returns the current byte location of the file pointer

Enviado em Curso de Programação Java | Tagged: , , | Nenhum comentário »

Classe File (Tutorial Oficial da Sun)

Escrito por wpjr2 em Maio 3, 2008

File Objects

The File class makes it easier to write platform-independent code that examines and manipulates files. The name of this class is misleading: File instances represent file names, not files. The file corresponding to the file name might not even exist.Why create a File object for a file that doesn’t exist? A program can use the object to parse a file name. Also, the file can be created by passing the File object to the constructor of some classes, such as FileWriter.

If the file does exist, a program can examine its attributes and perform various operations on the file, such as renaming it, deleting it, or changing its permissions.

A File Has Many Names

A File object contains the file name string used to construct it. That string never changes throughout the lifetime of the object. A program can use the File object to obtain other versions of the file name, some of which may or may not be the same as the original file name string passed to the constructor.Suppose a program creates a File object with the constructor invocation

File a = new File("xanadu.txt");

The program invokes a number of methods to obtain different versions of the file name. The program is then run both on a Microsoft Windows system (in directory c:\java\examples) and a Solaris system (in directory /home/cafe/java/examples). Here is what the methods would return:

Method Invoked Returns on Microsoft Windows Returns on Solaris
a.toString() xanadu.txt xanadu.txt
a.getName() xanadu.txt xanadu.txt
b.getParent() NULL NULL
a.getAbsolutePath() c:\java\examples\xanadu.txt /home/cafe/java/examples/xanadu.txt
a.getCanonicalPath() c:\java\examples\xanadu.txt /home/cafe/java/examples/xanadu.txt

Then the same program constructs a File object from a more complicated file name, using File.separator to specify the file name in a platform-independent way.

File b = new File(".." + File.separator + "examples" + File.separator + "xanadu.txt");

Although b refers to the same file as a, the methods return slightly different values:

Method Invoked Returns on Microsoft Windows Returns on Solaris
b.toString() ..\examples\xanadu.txt ../examples/xanadu.txt
b.getName() xanadu.txt xanadu.txt
b.getParent() ..\examples ../examples
b.getAbsolutePath() c:\java\examples\..\examples\xanadu.txt /home/cafe/java/examples/../examples/xanadu.txt
b.getCanonicalPath() c:\java\examples\xanadu.txt /home/cafe/java/examples/xanadu.txt

Running the same program on a Linux system would give results similar to those on the Solaris system.

It’s worth mentioning that File.compareTo()would not consider a and b to be the same. Even though they refer to the same file, the names used to construct them are different.

The FileStuff example creates File objects from names passed from the command line and exercises various information methods on them. You’ll find it instructive to run FileStuff on a variety of file names. Be sure to include directory names as well as the names of files that don’t actually exist. Try passing FileStuff a variety of relative and absolute path names.

Manipulating Files

If a File object names an actual file, a program can use it to perform a number of useful operations on the file. These include passing the object to the constructor for a stream to open the file for reading or writing.The delete method deletes the file immediately, while the deleteOnExit method deletes the file when the virtual machine terminates.

The setLastModified sets the modification date/time for the file. For example, to set the modification time of xanadu.txt to the current time, a program could do

new File("xanadu.txt").setLastModified(new Date().getTime());

The renameTo() method renames the file. Note that the file name string behind the File object remains unchanged, so the File object will not refer to the renamed file.

Working with Directories

File has some useful methods for working with directories.The mkdir method creates a directory. The mkdirs method does the same thing, after first creating any parent directories that don’t yet exist.

The list and listFiles methods list the contents of a directory. The list method returns an array of String file names, while listFiles returns an array of File objects.

Static Methods

File contains some useful static methods.The createTempFile method creates a new file with a unique name and returns a File object referring to it

The listRoots returns a list of file system root names. On Microsoft Windows, this will be the root directories of mounted drives, such as a:\ and c:\. On UNIX and Linux systems, this will be the root directory, /.

Enviado em Curso de Programação Java | Tagged: , , | Nenhum comentário »