
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: Java IO | Nenhum comentário »
Resumo dos Fluxos de Dados em Java (2)
Escrito por wpjr2 em Maio 3, 2008
Enviado em Curso de Programação Java, Uncategorized | Tagged: E/S, IO, Streams | 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
(
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: E/S, InputStream, IO, OutputStream, Reader, Writer | Nenhum comentário »
Arquivos de Acesso Aleatório (Tutorial Oficial da Sun)
Escrito por wpjr2 em Maio 3, 2008
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.
Suppose that you want to extract a specific file from a ZIP archive. If you use a sequential access stream, you have to:
- Open the ZIP archive.
- Search through the ZIP archive until you locate the file you want to extract.
- Extract the file.
- 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.RandomAccessFileclass implements both theDataInputandDataOutputinterfaces and therefore can be used for both reading and writing.RandomAccessFileis similar toFileInputStreamandFileOutputStreamin that you specify a file on the native file system to open when you create it. When you create aRandomAccessFile, 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 aRandomAccessFileto read the file namedxanadu.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
readorwritemethods defined in theDataInputandDataOutputinterfaces to perform I/O on the file.RandomAccessFilesupports 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 thereadandwritemethods adjust the file pointer by the number of bytes read or written.
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,
RandomAccessFilecontains three methods for explicitly manipulating the file pointer.
int skipBytes(int)— Moves the file pointer forward the specified number of bytesvoid seek(long)— Positions the file pointer just before the specified bytelong getFilePointer()— Returns the current byte location of the file pointer
Enviado em Curso de Programação Java | Tagged: E/S, IO, RandomAccessFile | Nenhum comentário »
Classe File (Tutorial Oficial da Sun)
Escrito por wpjr2 em Maio 3, 2008
The
Fileclass makes it easier to write platform-independent code that examines and manipulates files. The name of this class is misleading:Fileinstances represent file names, not files. The file corresponding to the file name might not even exist.Why create aFileobject 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 theFileobject to the constructor of some classes, such asFileWriter.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
Fileobject contains the file name string used to construct it. That string never changes throughout the lifetime of the object. A program can use theFileobject 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 aFileobject with the constructor invocationFile 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.txtxanadu.txta.getName()xanadu.txtxanadu.txtb.getParent()NULLNULLa.getAbsolutePath()c:\java\examples\xanadu.txt/home/cafe/java/examples/xanadu.txta.getCanonicalPath()c:\java\examples\xanadu.txt/home/cafe/java/examples/xanadu.txtThen the same program constructs a
Fileobject from a more complicated file name, usingFile.separatorto specify the file name in a platform-independent way.File b = new File(".." + File.separator + "examples" + File.separator + "xanadu.txt");Although
brefers to the same file asa, the methods return slightly different values:
Method Invoked Returns on Microsoft Windows Returns on Solaris b.toString()..\examples\xanadu.txt../examples/xanadu.txtb.getName()xanadu.txtxanadu.txtb.getParent()..\examples../examplesb.getAbsolutePath()c:\java\examples\..\examples\xanadu.txt/home/cafe/java/examples/../examples/xanadu.txtb.getCanonicalPath()c:\java\examples\xanadu.txt/home/cafe/java/examples/xanadu.txtRunning 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 consideraandbto be the same. Even though they refer to the same file, the names used to construct them are different.The
FileStuffexample createsFileobjects from names passed from the command line and exercises various information methods on them. You’ll find it instructive to runFileStuffon a variety of file names. Be sure to include directory names as well as the names of files that don’t actually exist. Try passingFileStuffa variety of relative and absolute path names.Manipulating Files
If a
Fileobject 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.Thedeletemethod deletes the file immediately, while thedeleteOnExitmethod deletes the file when the virtual machine terminates.The
setLastModifiedsets the modification date/time for the file. For example, to set the modification time ofxanadu.txtto the current time, a program could donew File("xanadu.txt").setLastModified(new Date().getTime());The
renameTo()method renames the file. Note that the file name string behind theFileobject remains unchanged, so theFileobject will not refer to the renamed file.Working with Directories
Filehas some useful methods for working with directories.Themkdirmethod creates a directory. Themkdirsmethod does the same thing, after first creating any parent directories that don’t yet exist.The
listandlistFilesmethods list the contents of a directory. Thelistmethod returns an array ofStringfile names, whilelistFilesreturns an array ofFileobjects.Static Methods
Filecontains some useful static methods.ThecreateTempFilemethod creates a new file with a unique name and returns aFileobject referring to itThe
listRootsreturns a list of file system root names. On Microsoft Windows, this will be the root directories of mounted drives, such asa:\andc:\. On UNIX and Linux systems, this will be the root directory,/.
Enviado em Curso de Programação Java | Tagged: E/S, File, IO | Nenhum comentário »

