import java.io.*;
public class EntradaTeclado{
public static void main(String[] args) throws IOException{
InputStreamReader isr;
BufferedReader teclado;
String linea;
byte b;
int i;
double d;
boolean leido;
isr = new InputStreamReader(System.in);
teclado = new BufferedReader(isr);
System.out.print("Introduzca un byte");
linea = teclado.readLine();
b = Byte.parseByte(linea);
System.out.println("Byte introducido: " + b);
System.out.print("Introduzca un entero");
linea = teclado.readLine();
i = Integer.parseInt(linea);
System.out.println("Entero introducido: " + i);
System.out.print("Introduzca un real");
linea = teclado.readLine();
d = Double.parseDouble(linea);
System.out.println("Real introducido: " + d);
do{
try{
System.out.print("Introduzca un entero:");
linea = teclado.readLine();
i = Integer.parseInt(linea);
leido = true;
}
catch(NumberFormatException e){
System.out.println("Entero no correcto, inténtelo de nuevo");
leido = false;
}
}while(!leido);
System.out.println("Entero introducido: " + i);
}
}
Lectura del teclado
BufferedReader teclado = new BufferedReader(new InputStreamReader(System.in)); String entrada = teclado.readLine();
Escribir un fichero
FileOutputStream fos = new FileOutputStream("fichero.txt");
PrintWriter pr = new PrintWriter(fos);
...
pr.println("Escribimos texto");
Otro método de escribir un fichero
FileWriter fw = new FileWriter("fichero.txt");
PrintWriter pr = new PrintWriter(fos);
...
pr.println("Escribimos texto");
Lectura de líneas
FileInputStream fis = new FileInputStream("fichero.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader buffer = new BufferedReader(isr);
...
String linea = buffer.readLine();
Otro método de leer ficheros.
Podemos cambiar FileInputStream por FileReader en cuyo caso el buffer sería un char[].
FileReader fr = new FileReader("fichero.txt");
BufferedReader buffer = new BufferedReader(fr);
...
String linea = buffer.readLine();
Escritura en modo datos
FileOutputStream fos = new FileOutputStream("salida.dat");
DataOutputStream dos = new DataOutputStream(fos);
dos.writeInt(5);
Lectura en modo datos
FileInputStream fis = new FileInputStream("salida.dat");
DataInputStream dis = new DataInputStream(fis);
int entero = dis.readInt();
0 comentarios:
Publicar un comentario