Beruflich Dokumente
Kultur Dokumente
De
Archivos
En Java
V4.0
Julio 2014
Ferreiras
InputStream
ó Reader
Fuente Programa
Conceptos Básicos
Conceptos Básicos
• Un programa que necesita escribir datos hacia un destino
requiere un output stream o Writer ( a ver más adelante ):
OutputStream
ó Writer
Programa Destino
Conceptos Básicos
Conceptos Básicos
Conceptos Básicos
• El procesamiento de archivos, vía la java.io, puede ser realizado de
diferentes maneras:
• Escritura/Lectura secuencial
• Escritura/Lectura aleatoria
• Acceder a la información de un archivo o directorio
• Una vez que se establece una conexión de red entre dos procesos,
estos se comunican entre sí a través de dicha conexión al igual que lo
harían con un archivo: El uso de un InputStream para leer los datos, y un
OutputStream para escribir datos. En otras palabras, Java IO se utiliza
para pasar los datos a enviar a la API de red de Java. Ese tema esta fuera
del alcance de este curso.
Conceptos Básicos
• Las clases IO de Java consisten principalmente de streams y de
readers/witers.
• Los propósitos de las clases IO de Java son:
• File Access
• Network Access
• Internal Memory Buffer Access
• Inter-Thread Communication (Pipes)
• Buffering
• Filtering
• Parsing
• Reading and Writing Text (Readers / Writers)
• Reading and Writing Primitive Data (long, int etc.)
• Reading and Writing Objects
Conceptos Básicos
• El procesamiento de archivos ocurre dentro del contexto
de un sistema de archivos.
• Un sistema de archivos es una cosa muy diferente a un
dispositivo de almacenamiento masivo y permanente,
DAMyP.
• Los DAMyP son dispositivos del hardware que no saben
nada acerca de la semántica de los archivos.
• Los DAMyP simplemente proporcionan un medio donde los
datos pueden ser almacenados.
Conceptos Básicos
• Un sistema de archivos es una abstracción de alto nivel.
Es un método particular de organización e interpretación de
los datos almacenados en un DAMyP. .
Un campo Es un grupo de
caracteres.
F o f i Campo ( 4 caracteres)
Luisa 35 3 5.45
Archivo ( 3 registros)
Tania` 25 1 6.33
Maria 55 12 6.77
nombre
identificadores de
edad
hijos
los campos.
altura
Creación de registros
...
A nivel de bytes ;
A nivel de campos.
Método de creación
En formato de texto
‘1’ ‘2’ ‘3’ ‘4’ ‘5’ ‘@’ ‘f’ ‘o’ ‘F’ ‘i’
En formato binario
01010110110011101110101010111...
Reader
InputStreamReader
FileReader
Writer
OutputStreamWriter PrintWriter
FileWriter
void write(int c)
Writes a single character. Ver ejemplo
FileTextWrite0.java
void write(String str)
Writes a string.
void println(boolean x)
Prints a boolean value and then terminates the line.
Ver ejemplo
void println(char x) FileTextWrite0d.java
Prints a character and then terminates the line.
void println(char[ ] x)
Prints an array of characters and then terminates the line.
void println(double x)
Prints a double-precision floating-point number and then terminates the line.
void println(float x)
Prints a floating-point number and then terminates the line.
void println(int x)
Prints an integer and then terminates the line.
void println(long x)
Prints a long integer and then terminates the line.
FileInputStream ObjectInputStream
OutputStream
• Is the file I/O mechanism introduced in the JDK 7 release. This API
may be used to overcome many of the limitations of the java.io.File
• Since: 1.4
• See on http://docs.oracle.com/javase/7/docs/api/index.html
• The Path class is the primary entry point for the package.
• The Buffer classes are the linkage between regular Java classes
and channels.
• Provides for system input and output through data streams, serialization and the file system.
• Unless otherwise noted, passing a null argument to a constructor or method in any class or
interface in this package will cause a NullPointerException to be thrown.
Methods to access the character-based console device, if any, associated with the current Java
virtual machine.
Whether a virtual machine has a console is dependent upon the underlying platform and also upon
the manner in which the virtual machine is invoked. If the virtual machine is started from an
interactive command line without redirecting the standard input and output streams then its console
will exist and will typically be connected to the keyboard and display from which the virtual machine
was launched. If the virtual machine is started automatically, for example by a background job
scheduler, then it will typically not have a console.
If this virtual machine has a console then it is represented by a unique instance of this class which
can be obtained by invoking the System.console() method. If no console device is available then an
invocation of that method will return null.
Read and write operations are synchronized to guarantee the atomic completion of critical
operations; therefore invoking methods readLine(), readPassword(), format(), printf() as well as the
read, format and write operations on the objects returned by reader() and writer() may block in
multithreaded scenarios.: Ver Console en http://download.oracle.com/javase/7/docs/api/
Ejemplos
*/
C:\Archivos de programa\Java\jdk1.7.0\bin>
C:\Archivos de programa\Java\jdk1.7.0\bin>
*/
java.util.Scanner
java.util.Console
java.io.File
java.io.FileWriter
java.io.PrintWriter
java.io.IOException
*/
* Sobreescribirlo.... S
* Agregar.... A
=> Su seleccion ( S o A ) : S
C:\Archivos de programa\Java\jdk1.7.0\bin>
Ejemplos
FilebyteLectura0b.java
jdk1.7.0
*/
try {
// Crear un objeto File con el archivo en args [ 0 ]
File objetoFile =new File( args [0] );
// Construir un objeto FileInputStream con el objeto File
FileInputStream flujoEntrada = new FileInputStream ( objetoFile ) ;
// Leer los bytes y mostrarlos
System.out.println( "\n\t=> La informacion en el archivo " +
objetoFile.getName() + " son como sigue:\n");
while ( ( unByte = flujoEntrada.read( ) ) != -1 ) {
System.out.print ( (char) unByte );
}
flujoEntrada.close( );
}
catch( IOException fofi ) {
System.out.println (fofi ) ; Obsérvese: Conversión explicita
}
} del byte leido a un carácter ASCII-
} extended.
*/
Class ImageIO
java.lang.Object
javax.imageio.ImageIO
*/
try {
catch (IOException e) {
}
C:\Program Files\Java\jdk1.7.0\bin>
*/
try {
catch (IOException e) {
}
C:\Program Files\Java\jdk1.7.0\bin>
Value Meaning
"r" Open for reading only. Invoking any of the write methods of the
resulting object will cause an IOException to be thrown.
"rw" Open for reading and writing. If the file does not already exist
then an attempt will be made to create it.
"rws" Open for reading and writing, as with "rw", and also require that
every update to the file's content or metadata be written
synchronously to the underlying storage device.
"rwd" Open for reading and writing, as with "rw", and also require that
every update to the file's content be written synchronously to the
underlying storage device.
Reads the next line of text from this file. This method successively reads bytes from the file,
starting at the current file pointer, until it reaches a line terminator or the end of the file. Each
byte is converted into a character by taking the byte's value for the lower eight bits of the
character and setting the high eight bits of the character to zero. This method does not,
therefore, support the full Unicode character set.
This method blocks until a newline character is read, a carriage return and the byte following
it are read (to see if it is a newline), the end of the file is reached, or an exception is thrown.
*/
import java.io.*;
Bayte 0 Byte 32
FileRandomWriteRead0.java
jdk1.7.0
*/
r0 r1 r2 r3 r4 r5 r6 r7
C:\Program Files\Java\jdk1.7.0\bin>
*/
intdoubleintdoubleintdoubleintdoubleintdoubleintdoubleintdouble
*/
Ver en el grupo.
*/
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.IOException;
import java.util.Scanner;
Ver completo en el
grupo.
*/
* Archivo original
* Archivo modificado
C:\Archivos de programa\Java\jdk1.7.0\bin>
ObjectInputStream
Es la clase para leer un objeto completo desde un archivo:
obj0
obj1 oos.writeObject( contenedor );
obj2
*/
import java.io.Serializable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public Exportables( long cedula, String nombre, int edad, String sexo) {
this.cedula = cedula;
this.nombre = nombre;
this.edad = edad;
this.sexo = sexo;
}
@SuppressWarnings("unchecked")
C:\Program Files\Java\jdk1.7.0\bin>
*/
obj0
obj1 (contenedor) ois.readObject( );
obj2
*/
import java.io.Serializable;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
public Exportables( long cedula, String nombre, int edad, String sexo) {
this.cedula = cedula;
this.nombre = nombre;
this.edad = edad;
this.sexo = sexo;
}
@SuppressWarnings("unchecked")
System.out.println();
}
}
C:\Program Files\Java\jdk1.7.0\bin>
*/
Profundizar este tema esta fuera del alcance de este curso. Sorry.
INF512_JAVA_Archivos_Ejem.zip
FileTextWrite0.java
FileTextWritingExistingFile0.java
FilebyteLectura0b.java
FileImage0c.java
FileImage0d.java
FileRandomWriteRead0.java
FileRandomWriteRead0a.java
FileRandom1b.java
FileRandomWriteReadRegistros.java
FileObjectStream0a.java
FileObjectStream0b.java
INF512_JAVA_Archivos_Ejerc.doc