Ejemplos de entrada/salida Argumentos de línea de comando public class Factorial { public static void main (String [] args){ int n, f; n = Integer.parseInt(args[0]); f = 1; for (int i = 2; i<=n; i++) { f *= i; // equivalente a f = f * i } System.out.print("El factorial de " + n); System.out.println(" es: " + f); } } Ingreso de un carácter por teclado import java.io.*; public class Pregunta { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Ingrese s/n: "); char ans = (char) in.read(); if (ans=='s') System.out.println ("escribio s"); else System.out.println ("escribio otra cosa"); } } // cierra main Ingreso de datos por teclado import java.io.*; public class Ejercicio { public static void main(String[] args)throws IOException { BufferedReader lee = new BufferedReader(new InputStreamReader(System.in)); String nombre; String apellido; int edad; System.out.println("Ingrese su nombre:"); nombre = lee.readLine(); System.out.println("Ingrese su apellido:"); apellido = lee.readLine(); System.out.println("Ingrese su edad:"); edad = Integer.parseInt(lee.readLine()); System.out.println("Su nombre es:"+nombre); System.out.println("Su apellido es:"+apellido); System.out.println("Su edad es:"+edad); if (edad >=18){ System.out.println("Usted es mayor de edad"); } else { System.out.println("Usted no es mayor de edad"); }}} Ingreso de datos por teclado import java.io.*; public class Sueldo1{ public static void main(String args []) throws IOException{ String respuesta; double sue; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Intrudusca el sueldo del trabajador"); respuesta=br.readLine(); sue=Double.parseDouble(respuesta); if(sue>=1000){ sue=sue*1.12; }else if(sue>0 && sue<1000){ sue=sue*1.15; }if(sue<0){ System.out.println("El sueldo no puede ser negativo"); }else{ System.out.println("El sueldo con aunmento incorporado es= "+sue);}}} Serialización/Deserialización public abstract class Figura implements java.io.Serializable{ protected int x; protected int y; public Figura(int x, int y) { this.x=x; this.y=y; } public abstract double area(); } Serialización/Deserialización class Circulo extends Figura{ //hereda Serializable protected double radio; private static final double PI=3.1416; public Circulo(int x, int y, double radio){ super(x,y); this.radio=radio; } public double area(){ return PI*radio*radio; } } class Rectangulo extends Figura{ //hereda Serializable protected double ancho, alto; public Rectangulo(int x, int y, double ancho, double alto){ super(x,y); this.ancho=ancho; this.alto=alto; } public double area(){ return ancho*alto; } } import java.io.*; public class ArchivoApp8 { public static void main(String[] args) throws Exception{ Figura fig1=new Rectangulo(10,15, 30, 60); Figura fig2=new Circulo(12,19, 60); ObjectOutputStream salida=new ObjectOutputStream(new FileOutputStream("figura.obj")); salida.writeObject("guardar un objeto de una clase derivada\n"); salida.writeObject(fig1); salida.writeObject(fig2); salida.close(); ObjectInputStream entrada=new ObjectInputStream(new FileInputStream("figura.obj")); String str=(String)entrada.readObject(); Figura obj1=(Figura)entrada.readObject(); Figura obj2=(Figura)entrada.readObject(); System.out.println("------------------------------"); System.out.println(obj1.getClass().getName()+" origen ("+obj1.x+", "+obj1.y+")"+" area="+obj1.area()); System.out.println(obj2.getClass().getName()+" origen ("+obj2.x+", "+obj2.y+")"+" area="+obj2.area()); System.out.println("------------------------------"); entrada.close(); }} Serialización/Deserialización public class Punto implements java.io.Serializable {//ambas clases Serializable private int x; private int y; public Punto(int x, int y) { this.x = x; this.y = y; } public Punto() { x=0; y=0; } public void desplazar(int dx, int dy){ x+=dx; y+=dy; } public String toString(){ return new String("("+x+", "+y+")"); }} Serialización/Deserialización public class Rectangulo implements java.io.Serializable{ private int ancho ; private int alto ; private Punto origen; public Rectangulo() { origen = new Punto(0, 0); ancho=0; alto=0; } public Rectangulo(Punto p) { this(p, 0, 0); } public Rectangulo(int w, int h) {this(new Punto(0, 0), w, h); public Rectangulo(Punto p, int w, int h) { origen = p; ancho = w; alto = h; } public void desplazar(int dx, int dy) { origen.desplazar(dx, dy); } public int calcularArea() { return ancho * alto; } public String toString(){ String texto=origen+" w:"+ancho+" h:"+alto; return texto; }} } Serialización/Deserialización import java.io.*; public class ArchivoApp5 {//hay otro tipo de excepción public static void main(String[] args) throws Exception{ Rectangulo rect=new Rectangulo(new Punto(10,10), 30, 60); ObjectOutputStream salida=new ObjectOutputStream(new FileOutputStream("figura.obj")); salida.writeObject("guardar un objeto compuesto\n"); salida.writeObject(rect); salida.close(); ObjectInputStream entrada=new ObjectInputStream(new FileInputStream("figura.obj")); String str=(String)entrada.readObject(); Rectangulo obj1=(Rectangulo)entrada.readObject(); System.out.println("------------------------------"); System.out.println(str+obj1); System.out.println("------------------------------"); entrada.close(); }} Marca de fin de archivo/Deserialización import java.util.*; public class Person implements java.io.Serializable protected String name; protected int id; protected List aList; public Person() { name = "none"; id = 0; } public Person(String s, int n, List l) { name = s; id = n; aList = l; } public String getName() { return name; } public int getID() { return id; } public List getList() { return aList; } public void modPerson() { name = name.concat("<-- changed"); id++; }} { Marca de fin de archivo/Deserialización import java.io.*; public class Prueba {public static void main(String[] args){ //se supone que se grabaron datos de Personas y se desconoce el número de datos grabados ObjectInputStream entrada=null; Person person=null; try{ entrada=new ObjectInputStream(new FileInputStream("Personas.obj"));} catch (IOException ioe){ System.out.println("i/o exception creating stream" + ioe.getMessage()); } while (true) {try{ person = (Person) entrada.readObject(); } catch (EOFException eof) {//seguir este orden!!! System.out.println("eof encountered" + eof.getMessage()); break; } catch (IOException ioe) { System.out.println("IOException on read object"); System.out.println(ioe.getMessage()); System.out.println(ioe.toString()); } catch (ClassNotFoundException cnf) { System.out.println("ClassNotFoundException"); } }}} Contar líneas de archivo texto import java.io.*; public class DemoChanning { public static void main(String[] args) throws IOException{ String s; FileReader fr = new FileReader("DemoChanning.java"); BufferedReader br = new BufferedReader(fr); LineNumberReader lr = new LineNumberReader(br); while ((s = lr.readLine()) != null) //readLine retorna null cuando llega al fin del flujo System.out.println(lr.getLineNumber() + " " + s); }} Copia línea por línea archivo texto import java.io.*; public class CopyLines { public static void main(String[] args) throws IOException { BufferedReader inputStream = null; PrintWriter outputStream = null; inputStream =new BufferedReader(new FileReader("CopyLines.java")); outputStream =new PrintWriter(new FileWriter("Copiaeficiente")); String l; while ((l = inputStream.readLine()) != null) { outputStream.println(l); } if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } }} Lectura y escritura de tipos de datos primitivos //ejecutar primero esta aplicación pasando un nombre de archivocomo línea de comando import java.io.*; public class BinFileOutput { //paso de argumetntos a main: nombre del archivo donde grabo datos public static void main(String f[]) throws IOException{ FileOutputStream fos; DataOutputStream ds; fos = new FileOutputStream(f[0]); ds = new DataOutputStream( fos ); int a[] = {0,1,2,3,4,5,6,7,8,9}; for (int i=0; i<a.length; i++) { ds.writeInt(a[i]); } }} Lectura y escritura de tipos de datos primitivos import java.io.*; public class BinFileInput { public static void main(String f[]) { FileInputStream fis; DataInputStream dis; //uso bloque try y adentro pongo todas las operaciones de lecturaso el bloque catch para detectar cuándo llegó al final del archivo, cuando //esto ocurre el control de la ejecución dentro del while(true) se transfiere al bloque //catch y se finaliza el while infinito al llegar al final del archivo Lectura y escritura de tipos de datos primitivos try { fis = new FileInputStream(f[0]); //si hubiese leído de teclado paso al constructor de dis System.in dis = new DataInputStream( fis ); System.out.println( "archivo: " + f[0] ); int i; //supongo que no conozco cuántos datos grabé entonces detecto marca de fin de archivo while ( true ) { i = dis.readInt(); //lee dato System.out.println( "lee: " + i ); } } catch (EOFException eof) {System.out.println( "EOF alcanzado " ); } //este último bloque atraparía cualquier otro posible error de entrada salida, por ejemplo no encontrar o poder //leer el archivo saca mensaje error catch (IOException ioe) {System.out.println( "IO error: " + ioe );} }} Lectura y escritura de datos en forma tabular import java.io.*; public class DataIODemo { public static void main(String[] args) throws IOException { /*tabla en formato: 19.99 12 Java T-shirt 9.99 8 Java Mug*/ DataOutputStream out = new DataOutputStream(new FileOutputStream("invoice1.txt")); double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 }; int[] units = { 12, 8, 13, 29, 50 }; String[] descs = { "Java T-shirt","Java Mug","Duke Juggling Dolls", "Java Pin","Java Key Chain" }; for (int i = 0; i < prices.length; i ++) { out.writeDouble(prices[i]); out.writeChar('\t'); out.writeInt(units[i]); out.writeChar('\t'); out.writeChars(descs[i]); out.writeChar('\n');//salto de línea después de descs } out.close(); Lectura y escritura de datos en forma tabular DataInputStream in = new DataInputStream(new FileInputStream("invoice1.txt")); double price; int unit; String desc=""; double total = 0.0; String lineSepString = System.getProperty("line.separator");//identifica salto línea //último caracter del separador de línea ("\r\n") char lineSep = lineSepString.charAt(lineSepString.length()1);//’\n’ try { while (true) { price = in.readDouble(); in.readChar(); // lee tabulado unit = in.readInt(); in.readChar(); // lee tabulado Lectura y escritura de datos en forma tabular char chr;//tiene desc y salto de línea while ((chr = in.readChar()) != lineSep) desc+=chr; System.out.println("You've ordered " + unit + " units of " + desc + " at $" + price); total = total + unit * price; }} catch (EOFException e) { } System.out.println("For a TOTAL of: $" + total); in.close(); }} String split public class PruebaSplit { public static void main(String []args) { //elementos separados por comas. Por ejemplo: String colores = "rojo,amarillo,verde,azul,morado,ma rrón"; String[] arrayColores = colores.split(","); // En este momento tenemos un array en el que cada elemento es un color. for (int i = 0; i < arrayColores.length; i++) { System.out.println(arrayColores[i]) ; }}} Polinomio de interpolación de Lagrange import java.io.*; public class InterpLagrange { public static void main(String[] args)throws IOException { double xi=1;//ingresar por teclado //cargar datos según ejercicio 15, en este ejemplo //cargado: 2;5 // 4;6 // 5;3 BufferedReader in=new BufferedReader(new FileReader("datos.txt")); String l; double []x; double []y; int i=0; String[] numeros=new String[100]; while ((l = in.readLine()) != null) { numeros[i++]=l;//en i queda longitud de x e y } String[]par=new String[2]; x=new double[i]; y=new double[i]; Polinomio de interpolación de Lagrange for(int j=0;j<i;j++){ par=numeros[j].split(";");//separo cada par de x e y x[j]=Double.parseDouble(par[0]); y[j]=Double.parseDouble(par[1]); } System.out.println("El valor obtenido al interpolar en x="+xi+" es:"+metodo(xi,x,y)); }//fin main Polinomio de interpolación de Lagrange public static double metodo(double xi,double[]x,double[]y){ //Metodo de interpolacion de Lagrange if(xi!=0){ double yi; double[] L=new double[x.length]; for(int i=0;i<x.length;i++){ L[i]=1; for(int j=0;j<x.length;j++){ if(j!=i) L[i]*=(xi-x[j])/(x[i]-x[j]);}} yi=0; for(int i=0;i<x.length;i++) yi+=L[i]*y[i]; return yi; }else{ return 0.0;}}}