E / S Leer de teclado

¡Por fin! Pues como ves. Es un poco como lo de leer de fichero. La entrada normal, para nosotros el teclado, lee una cadena de datos (InputStreamReader) que después hemos de meter en el espacio de almacenamiento intermedio (BufferedReader) para poder hacer una lectura linea a linea.

//Echo.java
// como leer de teclado
import java.io.*;
public class Echo{
	public static void main(String[] args) throws IOException{
		BufferedReader in = new BufferedReader( new InputStreamReader(System.in) );
		String s;
		while(  ( (s = in.readLine()) != null) && (s.length() != 0) ){
			System.out.println(s);
		}
	}
}

bueno… tambien puedes hacerlo directamente sin el BufferedReader pero entonces lo que lees son bytes. tienes que manipularlo luego. fijate:

// AbrirArchivo.java
// Como abrir y manejar archivos de texto
import java.io.*;
public class AbrirArchivo{
public static void main(String args[]) throws IOException{
	int c;
		FileOutputStream f = new FileOutputStream("carta.txt");
		System.out.println("escribe hasta que pongas una c");
		while((c=System.in.read()) != 'c')
			f.write((char)c);
		f.close();
		System.out.println("s'acabó");
	}
}
 
java/24.txt · Última modificación: 2008/05/13 10:00 (editor externo)
 
Excepto donde se indique lo contrario, el contenido de esta wiki se autoriza bajo la siguiente licencia:CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki