16/11/05
|
||||||
|
Continuamos con la gestión de ficheros que hace Java Sea un objeto de la clase File File f = new File("ud:/camino/.../fichero.txt"); // podemos indicar un directorio Para crearlo: try{
f.createNewFile();
System.out.println("se ha creado el fichero :" + f.getName());
}
catch(Exception e){
System.out.println("Error ...");
}
finally {return;}
}
Veamos un ejemplo: Este programa copia un fichero "original.txt" en otro "outagain.txt" import java.io.*;
class FileStreamsTest {
public static void main(String[] args) {
try {
File inputFile = new File("original.txt");
File outputFile = new File("outagain.txt");
//Creamos entradas y salidas por cónsola
FileInputStream fis = new FileInputStream(inputFile);
FileOutputStream fos = new FileOutputStream(outputFile);
int c;
//Mientras el valor del método read() del objeto fis sea != -1 --> ejecuta metodo
//write del objeto fos // traduciendo: mientras no termine de leer el fichero // inputfile, copialo ( y si no existe lo crea y si existe lo sobreescribe) // en el fichero outputfile
while ((c = fis.read()) != -1) {
//lee byte a byte de fis y lo vuelca en fos
fos.write(c);
}
// en realidad trabaja entre la ram(FileInputStream y FileOutputStream) y el HD
// (inputFile , outputFile) fis.close(); fos.close();//importante , no dejarse abierto canales } catch (FileNotFoundException e) { //la excepción provendria de no encontrar original.txt // originada en la linea FileInputStream fis = new FileInputStream(inputFile); // java exige recoger la excepcion al usar este canal ( try{..} catch{..} )
// el fichero de salida no genera excepción , ya que se va a crear o sobreescribir
System.err.println("FileStreamsTest: " + e);
} catch (IOException e) {
// excepción más genérica de entrada / salida
System.err.println("FileStreamsTest: " + e);
}
}
}
Concepto de canal: En un flujo de datos se establecen canales ,es decir caminos, de entrada / salida .
|
||||||
|
Ejercicios: 1.- Crea una aplicación de forma que pida 2 nºs y calcule la suma, usando los canales de entrada y salida estándar, siguiendo este ejemplo: import java.io.*;
public class BufferedReaderTest {
// Throw exceptions to console:
public static void main(String[] args)
throws IOException {
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));
System.out.print("Enter a line:");
System.out.println(stdin.readLine());
}
}
Solución:
import java.io.*;
public class BufferedReaderTest {
// Throw exceptions to console:
public static void main(String[] args)
throws IOException {
Integer suma;
//Veamos en las API que es cada cosa
// BufferedReader stdin1 = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Introduzca un nº entero:");
suma=Integer.parseInt(stdin1.readLine());
System.out.print("Introduzca otro nº entero:");
suma=suma+Integer.parseInt(stdin1.readLine());
System.out.println("La suma es = "+suma);
//cerramos
stdin1.close();
}
}
//n seria de
tipo int,
c de char
y en la salida por pantalla un objeto de tipo
char
traslada su valor numérico a caracter BufferedReader
public class BufferedReader Read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes. In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example, BufferedReader in
= new BufferedReader(new FileReader("foo.in"));
will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient. Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.
public class FileReader Convenience class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream.
|
||||||