Está en la página 1de 176

Universidad Complutense de Madrid

Facultad de Informática
Grado en Ingeniería Informática, Grupo A

Tecnología de la Programación

Introducción a la Programación
Orientada a Objetos
Simon Pickin,
Alberto Díaz, Puri Arenas
variables de programa
Goto statement considered harmful

secuencia selección iteración


Encapsulación ocultación de información
encapsulación ocultación de información

atributos

campos variables miembro

método

funciones miembro
propiedades

get set

Programación imperativa
encapsulación ocultación de información

la noción de ID de objeto

Clases como tipos


Herencia
Polimorfismo de subtipo

inculación dinámica
Universidad Complutense de Madrid
Facultad de Informática
Grado en Ingeniería Informática, Grupo B

Tecnología de la Programación

Introducción a Java

Simon Pickin,
Alberto Díaz, Puri Arenas, Yolanda García

o
o
o

o
o
o
o

o
o
o

2-2
o
o

o
o

o
2-3

o
sin modificación alguna

Write Once, Run Anywhere

o
2-4
sandbox

2-5

2-6
-7

§2 - 8
Java Standard Edition
o Java Runtime Environment

o Java Development Kit

javac java
jdb javadoc

o Java Micro Edition

o Java Enterprise Edition

o
2-9

java.lang String
java.io java.nio

java.net
java.util

java.awt

javax.swing

2 - 10
o
o

o javac javac MiClase.java


.class MiClase.class
.class

o java java MiClase

2 - 11

package nombrePaquete;

// Importación de otras clases o paquetes


import java.util.Vector;
import java.util.Date;

// Declaración e implementación de la clase


public class NombreClase
{

}

o
o

2 - 12
o public static void main(String[] args)

o
.java
o
o public
o public

.class
o

2 - 13

.class .o .obj

o
.h

java.lang
import <nombrePaquete>.<nombreClase> import <nombrePaquete>.

interface

o
o CLASSPATH
o –classpath -cp java javac
2 - 14
o
o
o

o
o

2 - 15

HolaMundo.java
// Este es mi primer progama en Java

public class HolaMundo


{
public static void main(String[] args)
{
System.out.println("Hola Mundo");
}
}

2 - 16
HolaMundo
o public

main
o public static
o
println
PrintStream java.io
out
static System
java.lang
o out

2 - 17

javac -d <a_dir> -cp <a_classpath> myPaquete.HolaMundo.java


o a_dir .class
o a_classpath

java -cp <classpath> miPaquete.HolaMundo


o HolaMundo main

o main

main

2 - 18
Universidad Complutense de Madrid
Facultad de Informática
Grado en Ingeniería Informática, Grupo B

Tecnología de la Programación

Clases y objetos

Simon Pickin,
Alberto Díaz, Puri Arenas, Yolanda García

public class NombreClase {


// atributos
// constructores
// métodos
};

3-2
o

o public
o protected:

o package private

o private:

o private
o protected

3-3

private int x = 2;
private String cadena = "setze jutges d'un jutjat";
private boolean fin = true;

this
public class A {
private int x;
private int y;

public int suma(){ return this.x + this.y;}


public incr(int z){
this.x = this.x + z;
this.y = this.y + z;
}
}
3-4
public class ClassExample { // Una variable local no debería tener el mismo nombre que un atributo
private int integerVar = 1;

private void exampleOfMethod1() {


this.integerVar = 2; // Asignar el valor 2 al atributo integerVar
integerVar = 3; // Asignar el valor 3 al atributo integerVar
}

private void exampleOfMethod2() {


int integerVar; // Definir una variable local integerVar y asignarle el valor 2
integerVar = 2; // Modificar la variable local, no el atributo
}

private void exampleOfMethod3(){


int integerVar = 2; // Definir una variable local integerVar y asignarle el valor 2
this.integerVar = integerVar; // Asignar el valor de la variable local al atributo
}

§3 - 5

final
o
static
o

public
o

3-6
o
o

o
o void
o

3-7

public class Rational {


private int num;
private int den;

// constructor sin argumentos (valores por defecto)


public Rational(){
this.num = 0;
this.den = 1;
}

// constructor con argumentos


public Rational(int n, int d){
this.num = n;
this.den = d;
}
...
}
3-8
Rational r1 = new Rational(); // 0/1

Rational r2 = new Rational(3,4); // 3/4

3-9

o
o

o Object
o
Object

3 - 10
o

o public:
o protected
o package-private
o private:

3 - 11

modificadores tipoRetorno nombre(Lista_Parámetros){


// cuerpo
}

o static
sobrecarga de métodos
o

void

3 - 12
public class A {
private int x;
// constructor "package-private": poco habitual
// (aquí solo para mostrar que es posible)
A(){this.x=0;}

int incr(int z){return this.x + z;}


int incr(){return this.x + 1;}
int incr(double z){return 1;}
}

public class Main {


public static void main(String[] args) {
A a = new A();
a.incr(2); // ejecuta el primer método
a.incr(2.0); // ejecuta el tercer método
}
}
3 - 13

Inicializadores

De acceso
o get
o de tipo primitivo

o getters

Mutadores
set
setters

Computadores

3 - 14
public class Rational {

// attributos
private int num;
private int den;

// constructores
public Rational(int n, int d){
this.num = n;
this.den = d;
}

public Rational(){
this(0,1)
}

3 - 15

// métodos accesores

public int getNum(){


return this.num;
}
public int getDen(){
return this.den;
}

// métodos mutadores

public void setNum(int n){


this.num = n;
}
public void setDen(int d){
this.den = d;
}

3 - 16
// métodos computadores

public void ProductoEscalar(int n){


this.num = this.num * n;
}

public void simplificar(){


int mcd = mcd(this.num,this.den);
this.num = this.num / mcd;
this.den = this.den / mcd;
}

3 - 17

// Este método se utiliza como ejemplo de un método privado.


// En realidad, probablemente sería major como public y static
// y dentro de una clase de utilidades, siendo private el
// método "simplificar"
private int mcd(int a, int b){
while (a != b)
if (a > b) a = a -b; else b = b -a;
return a;
}

public String toString(){


return this.num + "/" + this.den;
}

}
3 - 18
nombreObjeto.nombreMetodo(valores-de-parámetros-separados-por-comas)

nombreObjeto
o

Rational r1 = new Rational(4,8);


Rational r2 = new Rational(2,6);
r1.multiply(r2);

3 - 19

main

public static void main( String[] args ){


...
}

signature
o public static void main( String[] args )
o

Main

3 - 20
o public:

o package-private

o private protected

3 - 21

public class Primitiva {


// atributo
private int x;
// constructor
public Primitiva(int iniX){ x = iniX; }
// métodos accesor y mutador
public int getX(){ return x; }
public void setX(int nuevoX){ x = nuevoX; }
}

public class Compleja {


// atributo
private Primitiva p;
// constructor
public Compleja(Primitiva iniP){ p = iniP; }
// metodo accesor (warning: ¡devuelve tipo no primitivo!)
public Primitiva getP(){ return p; }
}
3 - 22
main
public static void main( String[] args ){
Primitiva pr1 = new Primitiva(3);
Compleja c = new Compleja(pr1);
Primitiva pr2 = c.getP();
pr2.setX(7);
System.out.println(pr1.getX());
c.getP().setX(4); // encadenamiento de métodos
System.out.println(pr1.getX());
}

o
x
p p private
o getP() una copia del
objeto p
3 - 23
Universidad Complutense de Madrid
Facultad de Informática
Grado en Ingeniería Informática, Grupo B

Tecnología de la Programación

Igualdad y copias

Simon Pickin,
Alberto Díaz, Puri Arenas, Yolanda García

o ==

o equals Object
==

4-2
public class A {
private int x; private int y;
public A(int x, int y){ this.x = x; this.y = y; }
}

public class Main


public static void main(String[] args) {
A a1 = new A(2,2);
A a2 = new A(2,2);
if (a1==a2) System.out.println("Cierto");
else System.out.println("Falso");
}
}

4-3

public class A {
private int x; private int y;
public A(int x, int y){ this.x = x; this.y = y; }
}

public class Main {


public static void main(String[] args) {
A a1 = new A(2,2);
A a2 = a1;
if (a1==a2) System.out.println("Cierto");
else System.out.println("Falso");
}
}

4-4
public class A {
private int x; private int y;
public A(int x, int y){ this.x = x; this.y = y; }
}

public class Main {


public static void main(String[] args) {
A a1 = new A(2,2);
A a2 = new A(2,2);
if (a1.equals(a2)) System.out.println("Cierto");
else System.out.println("Falso");
}
}

4-5

public class A {
private int x; private int y;
public A(int x, int y){ this.x = x; this.y = y; }
public boolean equals(A a){
return (this.x == a.x && this.y == a.y);
}
}

public class Main {


public static void main(String[] args) {
A a1 = new A(2,2);
A a2 = new A(2,2);
if (a1.equals(a2)) System.out.println("Cierto");
else System.out.println("Falso");
}
}

4-6
public class A {
private int x; private int y;
public A(int x, int y){ this.x = x; this.y = y; }
public boolean equals(A x){
return (this.x == a.x && this.y == a.y);
}
}

public class Main {


public static void main(String[] args) {
A a1 = new A(2,2);
A a2 = a1;
if (a1.equals(a2)) System.out.println("Cierto");
else System.out.println("Falso");
}
}

4-7

public class B public class A {

private int z; private int x;


private B b;
public B(int z){
this.z=z; public A(int x, B b){
} this.x = x;
this.b = b;
} }

public boolean equals(A a){


return (this.x==a.x
&& this.b == a.b);
}

4-8
public class Main {

public static void main(String[] args) {


B b1 = new B(2);
B b2 = new B(2);
A a1 = new A(3,b1);
A a2 = new A(3,b2);
if (a1.equals(a2)) System.out.println("Cierto");
else System.out.println("Falso");
}

4-9

public class B public class A {

private int z; private int x;


private B b;
public B(int z){
this.z=z; public A(int x, B b){
} this.x = x;
this.b = b;
public boolean equals(B b){ }
return (this.z == b.z);
} public boolean equals(A a){
return (this.x==a.x
} && this.b.equals(a.b);
}

4 - 10
public class Main {

public static void main(String[] args) {


B b1 = new B(2);
B b2 = new B(2);
A a1 = new A(3,b1);
A a2 = new A(3,b2);
if (a1.equals(a2)) System.out.println("Cierto");
else System.out.println("Falso");
}

4 - 11

equals() hashCode()

equals()
a.equals(b) b.equals(a)
a.equals(a)
a.equals(b) and b.equals(c) a.equals(c)

a == b a.equals(b)

hashCode() Object
o Hashtable HashMap

a.equals(b) a.hashCode() == b.hashCode()

equals()
o hashCode()
4 - 12
hash table

Jorge Stolfi - Own work, Public Domain,


https://commons.wikimedia.org/w/index.php?curid=6601264

4 - 13

clone()

clone()
o Object

Fecha f1, f2 = new Fecha(25, 12, 17);


f1 = f2.clone(); // Copia del objeto

if (f1 == f2) // Falso (no apuntan al mismo objeto)


System.out.println("El mismo");

if (f1.equals(f2)) // Cierto (si hemos sobrescrito equals)


System.out.println("Iguales");

4 - 14
shallow copy

obj2: Clase2 obj2: Clase2

int y = 6 int y = 6
int z = 4 int z = 4
b
a

obj1: Clase1 obj1: Clase1 obj3: Clase1

Clase2 c = obj2 Clase2 c = obj2 Clase2 c = obj2


int x = 3 int x = 3 int x = 3

Clase1 a = obj1 Clase1 a = obj1 Clase1 b = obj3

4 - 15

deep copy

obj2: Clase2 obj2: Clase2 obj4: Clase2


int y = 6 int y = 6 int y = 6
int z = 4 int z = 4 int z = 4
b
a

obj1: Clase1 obj1: Clase1 obj3: Clase1


Clase2 c = obj2 Clase2 c = obj2 Clase2 c = obj4
int x = 3 int x = 3 int x = 3

Clase1 a = obj1 Clase1 a = obj1 Clase1 b = obj3

4 - 16
clone()

Object.clone()

clone()
o
Cloneable

clone()

4 - 17
Universidad Complutense de Madrid
Facultad de Informática
Grado en Ingeniería Informática, Grupo B

Tecnología de la Programación

Tipos de datos de Java

Simon Pickin,
Alberto Díaz, Puri Arenas, Yolanda García

5-2
widening

5-3

5-4
5-5

5-6
5-7

5-8
5-9

5 - 10
5 - 11

5 - 12
5 - 13

5 - 14
5 - 15

5 - 16
breakpoint

5 - 17

5 - 18
5 - 19

5 - 20
En la declaración
En la asignación

En la declaración

En la asignación

5 - 21

" "

" " " "

5 - 22
modificación del valor del parámetro

modificación de los datos referenciados por el valor del parámetro

5 - 23

5 - 24
5 - 25

5 - 26
wrapper classes

5 - 27

wrapper classes

tipos genéricos

5 - 28
Boxing unboxing

Auto boxing

Unboxing

5 - 29

5 - 30
5 - 31

asociación

navegable

multiplicidad
rol

5 - 32
5 - 33

Universidad Complutense de Madrid


Facultad de Informática
Grado en Ingeniería Informática, Grupo B

Tecnología de la programación

Apéndice
5A - 35

5A - 36
5A - 37

MAX

MAX

5A - 38
5A - 39

5A - 40
5A - 41

polimorfismo de subtipo covariantes

get
§5A - 42
java archive

bytecode

classpath

§5A - 43

java archive

§5A - 44
java archive

§5A - 45

java archive

§5A - 46
java archive

§5A - 47
Universidad Complutense de Madrid
Facultad de Informática
Grado en Ingeniería Informática, Grupo B

Tecnología de la Programación

La Herencia en la Programación
Orientada a Objetos
Simon Pickin
Alberto Díaz, Puri Arenas, Marco Antonio Gómez

§6 - 2
es-un

es-un

§6 - 3

public class
private long
private

public
public long
this
this

.... //

//
public void
this
this

§6 - 4
§6 – 5

public class extends


private long
private int

public

public long return


public long return
public void int
public void int

§6 - 6
new

§6 - 7

clase padre superclase clase base

clase hija subclase clase derivada

§6 - 8
la fragilidad de la
clase base

§6 - 9

Object

§6 - 10
§6 - 11

error

§6 - 12
6 - 13

§6 - 14
§6 - 15

§6 - 16
obrescritura

§6 - 17

§6 - 18
§6 - 19

§6 - 20
§6 - 21

ocultados

oculta

§6 - 22
§6 - 23

§6 - 24
§6 - 25

sobrecarga de métodos o de sobrescritura de métodos


§6 - 26
§6 - 27

§6 - 28
contravariante

covariante

§6 - 29

§6 - 30
§6 - 31

§6 - 32
covarianza

§6 - 33

covariante en el tipo de retorno

contravariante en el tipo de
los parámetros

§6 - 34
§6 - 35

§6 - 36
1. Arrays covariantes

2. Arrays contravariantes

3. Arrays invariantes

§6 - 37

§6 - 38
cualquier

herencia de implementación

§6 - 39

Usos

§6 - 40
cualquier

strong behavioural subtyping

§6 - 41

public class

private int
private int

public int int

public int

public int

public int return

§6 - 42
public class extends
public int

§6 - 43

setters

§6 - 44
public
package private
package
private:
protected:

package

§6 - 45

§6 - 46
métodos abstractos métodos virtuales

§6 - 47

§6 - 48
§6 - 49

abstract public class

protected int
protected int

public

public int int

abstract public int


abstract public void

§6 - 50
public class extends

private int
private int

public int int int int


super

public int
return

public void

§6 - 51

public class extends


private int

public int int int


super

public int
return

public void

§6 - 52
Constant Interface Antipattern

getter setter
getter

protocolo de comportamiento

§6 - 53

Desafortunadamente, ya no es cierto en Java 8 (ver más adelante)

§6 - 54
Desde Java 8, se puede omitir el modificador de método public
y se pueden omitir los modificadores de atributo public static final

Desde Java 8, se permiten cuerpos de ciertos métodos (ver más adelante)

Desde Java 8, las interfaces pueden contener implementaciones. ¡Cuidado!

§6 - 55

§6 - 56
§6 - 57

§6 - 58
§6 - 59

§6 - 60
package-private

§6 - 61

declaración implicita desde Java 8

No es cierto para una interfaz de Java 8 (ver más adelante)

Java 8 permite métodos default in interfaces (ver más adelante)

§6 - 62
§6 - 63

mixin

§6 - 64
§6 - 65

§6 - 66
Java 8: solo se necesita si las implementaciones estándares incluyen estado

§6 - 67

default

default

§6 - 68
§6 - 69

Diseña y documenta para la herencia o bien prohíbela

§6 - 70
§6 - 71

§6 - 72
§6 - 73

§6 - 74
§6 - 75

//
#include
using namespace

class
public
void

class
public
void

class public public

§6 - 76
int

§6 - 77

§6 - 78
#include
using namespace

class
public
void

int

class public
public

void

§6 - 79

class public
public

void

class public public

int

§6 - 80
dos métodos mostrar1
no compila

virtual

dos atributos problematico


no compila

comportamiento no definido
§6 - 81

§6 - 82
§6 - 83

§6 - 84
Java Language Specification Interface Members

§6 - 85

§6 - 86
§6 - 87

tipo estático
tipo dinámico

§6 - 88
§6 - 89

§6 - 90
§6 - 91

§6 - 92
§6 - 93

Se resuelve en tiempo de compilación usando tipos estáticos

Se resuelve en tiempo de ejecución usando tipos dinámicos

§6 - 94
class
public void

public void

public static void


new new
new

§6 - 95

§6 - 96
// tipo estático B, tipo dinámico C
// ¿error? ¿qué es lo que se imprime?

§6 - 97

// tipo estático B, tipo dinámico C


// ¿error? ¿qué es lo que se imprime?

§6 - 98
// tipo estático B, tipo dinámico C
// ¿error? ¿qué es lo que se imprime?

§6 - 99

// tipo estático B, tipo dinámico C


// ¿error? ¿qué es lo que se imprime?

§6 - 100
// tipo estático B, tipo dinámico C
// ¿error? ¿qué es lo que se imprime?

§6 - 101

// tipo estático D, tipo dinámico D


// ¿error? ¿qué es lo que se imprime?

§6 - 102
downcasting

cast, downcast

§6 - 103

downcasting

§6 - 104
§6 - 105

§6 - 106
§6 - 107

§6 - 108
§6 - 109

§6 - 110
§6 - 111

§6 - 112
§6 - 113

§6 - 114
§6 - 115

§6 - 116
class
public
virtual int return
int return

class public
public
int return
int return

int

int
return

§6 - 117

class
public
virtual void

class public
public
void

§6 - 118
new

new

dynamic_cast
dynamic_cast

§6 - 119

class

class public
public
new
delete
private

int
new
delete
return

§6 - 120
Universidad Complutense de Madrid
Facultad de Informática
Grado en Ingeniería Informática, Grupo B

Tecnología de la programación

Apéndice

§6 - 122
Diseña y documenta para la herencia o bien prohíbela

§6 - 123

§6 - 124
§6 - 125
Universidad Complutense de Madrid
Facultad de Informática
Grado en Ingeniería Informática, Grupo en Inglés

Tecnología de la Programación

Tratamiento de excepciones
Simon Pickin,
Yolanda García, Alberto Díaz, Marco Antonio Gómez, Puri Arenas,

o
o

o
o

§7 - 2
public class Overflow {

public static void main(String[] args){


int values[] = {1, 2, 3};
for (int i = 0; i <= 3; i++)
System.out.println(values[i]);
}
}

1
2
3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Overflow.main(Overflow.java:6)

§7 - 3

Fatal
o
o
o

Recoverable
o

int:

§7 - 4
o

o throwing

o
main
o main

§7 - 5

§7 - 6
Exception

Throwable
o
Error
o

o
Exception
o
o IOException ArithmeticException
o Exception RunTimeException checked exceptions”
IOException
NullPointerException unchecked exception”

§7 - 7

Exception

o java.lang
Throwable Exception RuntimeException
o java.io
EOFException FileNotFoundException
o

Throwable
o String getMessage()
null
o void printStackTrace()
call stack

§7 - 8
Run-Time

o
o

o
ArithmeticException

run-time
o

§7 - 9

o
o
catch

throws

public void readFile(String file)


throws EOFException, FileNotFoundException { ... }
EOFException FileNotFoundException IOException
public void readFile(String file) throws IOException { ... }

§7 - 10
catch

m0
o m0
o m1 m0 catch
throws
o m1 m2
m1 catch throws

o catch

§7 - 11

try catch

try
try

catch
o catch
o catch try
try
o catch
try
catch
o catch (*)
undeclared checked exception: compiler error

§7 - 12 try
try catch

o
o

catch

try catch
try {
...
} catch (IndexOutOfBoundsException e) {
System.err.println("IndexOutOfBoundsException: " + e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}

§7 - 13

try catch

a = 0
java.lang.ArithmeticException: / by zero at
EjemploExcep.main(EjemploExcep.java:6)
Exception in thread "main" Process Exit...

§7 - 14
try catch

a = 0
No dividas por 0 (java.lang.ArithmeticException: / by zero)
La ejecución sigue ...
§7 - 15

try catch finally

o
o
o
o
finally
o try catch
o try catch
finally

o try continue break return

§7 - 16
try catch finally

metodo2 IOException metodo1

§7 - 17

new throw
o
if (size == 0) {
throw new EmptyStackException();
}

o
o
o

main
§7 - 18
o

o Exception Exception

RunTimeException
o throws
o
o

§7 - 19

Exception

public myException extends Exception {


public myException() { super(); }
public myException(String message){ super(message) }
public myException(String message, Throwable cause){
super(message, cause);
}
public myException(Throwable cause){ super(cause); }
Exception(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace){
super(message, cause, enableSuppression, writeableStackTrace)
}
}

§7 - 20
MiExcepcion

§7 - 21

main
Lanzo mi excepción desde aquí.
La tengo! MiExcepcion: error malísimo...
... y sigo.

§7 - 22
catch(Exception e1) {
// do something with exception e1
throw e2; // e2 may or may not be the same exception as e1
}

o
o

SQLException
RunTimeException

§7 - 23

try-with-resources

private static void printFile() throws IOException {


InputStream input = null;
try {
input = new FileInputStream("file.txt");
int data = input.read(); // may throw IOException
while(data != -1){
System.out.print((char) data);
data = input.read(); // may throw IOException
}
} finally {
if(input != null){ input.close(); } // may throw IOException
}
}

§7 - 24
try-with-resources

try finally
o
o Respuesta finally
try

try-with-resources
o try
o java.lang.AutoCloseable
try-with-resources
o try
o try finally
try finally
getSuppressed

§7 - 25

try-with-resources

try-with-resources
private static void printFile() throws IOException {
try(FileInputStream input = new FileInputStream("file.txt")) {
int data = input.read();
while(data != -1){
System.out.print((char) data);
data = input.read();
}
}
}

§7 - 26
try-with-resources

try-with-resources
private static void printFile() throws IOException {
try( FileInputStream input = new FileInputStream("file.txt");
BufferedInputStream bufferedInput = new BufferedInputStream(input)
) {
int data = bufferedInput.read();
while(data != -1){
System.out.print((char) data);
data = bufferedInput.read();
}
}
}

§7 - 27

interface
throw
o

o
o

§7 - 28
Universidad Complutense de Madrid
Facultad de Informática
Grado en Ingeniería Informática

Tecnología de la Programación

Entrada/Salida en Java
Simon Pickin

o
o System.in
o System.out System.err

o
o
o stream
stream
stream
§8 - 2
java.io

o
InputStream OutputStream
o
Reader Writer

stream streams
o
charset
InputStreamReader OutputStreamWriter

o stdin stdout stderr


o System.in InputStream
o System.out System.err PrintStream OutputStream
§8 - 3

InputStream OutputStream Reader Writer

o streams

o
o
o
o
o
o
o
o
o long int
o
§8 - 4
InputStream OutputStream

stream
o stream streams
streams

o finally
o try-with-resources
o

§8 - 5

https://docs.oracle.com/javase/tutorial/essential/io/bytestreams.html

§8 - 6
// FileInputStream read() devuelve -1 si se llega a fin de fichero
public class CopyBytes {
public static void main(String[] args) throws IOException {
FileInputStream inBytes = null;
FileOutputStream outBytes = null;
try {
inBytes = new FileInputStream("bytes_in.txt");
outBytes = new FileOutputStream("bytes_out.txt");
int c; // almacena el valor del byte en los últimos 8 bits
while ((c = inBytes.read()) != -1) { outBytes.write(c); }
} finally {
if (in != null) { inBytes.close(); }
if (out != null) { outBytes.close(); }
}
}
}

§8 - 7

http://www3.ntu.edu.sg/home/ehchua/programming/java/j5b_io.html
http://www.studytrails.com/java-io/classDiagram.jsp
https://docs.oracle.com/javase/8/docs/api/java/io/package-tree.html

§8 - 8
Reader Writer
Stream
o charset charset

charset

streams streams
o FileReader FileWriter FileInputStream FileOutputStream

o String
o
streams

§8 - 9

// FileReader read() devuelve -1 si se llega a fin de fichero


public class CopyCharacters {
public static void main(String[] args) throws IOException {
FileReader inChars = null;
FileWriter outChars = null;
try {
inChars = new FileReader("default_chars_in.txt");
outChars = new FileWriter("default_chars_out.txt");
int c; // almacena el character en la variable de tipo int
while ((c = inChars.read()) != -1) { outChars.write(c); }
} finally {
if (inChars != null) { inChars.close(); }
if (outChars != null) { outChars.close(); }
}
}
}

§8 - 10
PrintWriter

http://www3.ntu.edu.sg/home/ehchua/programming/java/j5b_io.html
http://www.studytrails.com/java-io/classDiagram.jsp
https://docs.oracle.com/javase/8/docs/api/java/io/package-tree.html
§8 - 11

o
o

o
§8 - 12
stream
o stream buffered stream

o stream buffered stream


stream

o Reader BufferedReader
o Writer BufferedWriter
o InputStream BufferedInputStream
o OutputStream BufferedOutputStream

o flush()
§8 - 13

BufferedInputStream in = new BufferedInputStream(


new FileInputStream("in.dat"));

http://www3.ntu.edu.sg/home/ehchua/programming/java/j5b_io.html

§8 - 14
public class CopyBytes { // se ejecuta más rápido que el ejemplo 1
public static void main(String[] args) throws IOException {
BufferedInputStream inBytes = null;
BufferedOutputStream outBytes = null;
try {
inBytes = new BufferedInputStream(
new FileInputStream("bytes_in.txt"));
outBytes = new BufferedOutputStream
new FileOutputStream("bytes_out.txt"));
int c; // almacena el valor del byte en los últimos 8 bits
while ((c = inBytes.read()) != -1) { outBytes.write(c); }
} finally {
if (in != null) { inBytes.close(); }
if (out != null) { outBytes.close(); }
}
}
}

§8 - 15

public class CopyLines { // se ejecuta más rápido que el ejemplo 2


public static void main(String[] args) throws IOException {
BufferedReader inChars = null;
BufferedWriter outChars = null;
try {
inChars = new BufferedReader(
new FileReader("default_chars_in.txt") );
outChars = new BufferedWriter(
new FileWriter("default_chars_out.txt") );
String l; // con BufferedReader se puede leer líneas enteras
while ((l = inChars.readLine()) != null){
outChars.write(l); outChars.newline();
}
} finally {
if (inChars != null) { inChars.close(); }
if (outChars != null) { outChars.close(); }
}
}
}
§8 - 16
charset
o
o

InputStreamReader OutputStreamWriter
o Streams

o stream charset
o charset
String charset
o
java.nio.charset.Charset
java.nio.charset.CharsetDecoder
§8 - 17

public class CopyUTF8Characters { // compara con el ejemplo 2


public static void main(String[] args) throws IOException {
InputStreamReader inChars = null;
OutputStreamWriter outChars = null;
try { // el flujo de char "envuelve" el flujo de byte
inChars = new InputStreamReader(
new FileInputStream("UTF8chars_in.txt"), "UTF-8");
outChars = new OutputStreamWriter(
new FileOutputStream("UTF8chars_out.txt"), "UTF-8");
int c; // almacena el caracter en los últimos 8-32 bits
while ((c = inChars.read()) != -1) { outChars.write(c); }
} finally {
if (inChars != null) { inChars.close(); }
if (outChars != null) { outChars.close(); }
}
}
}

§8 - 18
public class CopyUTF8Lines { // compara con el ejemplo 4
public static void main(String[] args) throws IOException {
BufferedReader inChars = null;
PrintWriter outChars = null;
try {
inChars = new BufferedReader(
new InputStreamReader(
new FileInputStream("UTF8chars_in.txt"), "UTF-8"));
outChars = new PrintWriter(
new OutputStreamWriter(
new FileOutputStream("UTF8chars_out.txt"), "UTF-8"));
String l; // PrintWriter tiene el método println (incluye salto)
while ((l = inChars.readLine()) != null){ outChars.println(l); }
} finally {
if (inChars != null) { inChars.close(); }
if (outChars != null) { outChars.close(); }
}
}
}

§8 - 19

stream
o FileInputStream FileOutputStream FileReader FileWriter

o String

o java.io.File
o java.io.FileDescriptor
streams
o boolean

o
o
§8 - 20
o RandomAccessFile
stream cursor
o
o seek()
o getFilePointer() long

o String
o java.io.File
String
o "r" "rw" "rws" "rwd"

§8 - 21

public class RandomAccessFileExample {// Utiliza try-with-resources de Java 7


public static void main(String[] args) throws IOException {
try (RandomAccessFile raf = new RandomAccessFile("books.dat", "rw")){
String books[] = new String[2];
books[1] = "Java Security";
books[2] = "Java Security Handbook";
for (int i = 0; i < books.length; i++) {
raf.writeUTF(books[i]);
}
raf.seek(raf.length());
raf.writeUTF("Servlet Programming");
raf.seek(0);
while (raf.getFilePointer() < raf.length()) {
System.out.println(raf.readUTF());
}
} // SUSTITUIR ESTE EJEMPLO POR UNO QUE SALTA HASTA MEDIO DEL FICHERO
} // SALTAR HASTA EL FINAL NO NECESITA RANDOMACCESSFILE
}

§8 - 22
data stream byte stream
o boolean char byte short int long float double
String
o DataInputStream DataOutputStream
data stream byte stream
data stream
o EOFException

o
o stream

§8 - 23

DataInputStream in = new DataInputStream(


new BufferedInputStream(
new FileInputStream("in.dat")));

http://www3.ntu.edu.sg/home/ehchua/programming/java/j5b_io.html

§8 - 24
// Utiliza try-with-resources de Java 7
public void dataStreamInOut() throws IOException {
try(DataOutputStream data_out = new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream("data.bin")))){
data_out.writeInt(123);
data_out.writeFloat(123.45F);
data_out.writeLong(789);
}
try(DataInputStream data_in = new DataInputStream(
new BufferedInputStream(
new FileInputStream("data.bin")))){
int anInt = data_in.readInt(); // anInt == 123
float aFloat = data_in.readFloat(); // aFloat == 123.45
long aLong = data_in.readLong(); // aLong == 789
int anotherInt = data_in.readInt(); // lanza EOFException
}
}

§8 - 25

o
Data streams
PrintStream

o
String
o Integer.toString(x) "" + x x
o String.format
String
o x = Integer.parseInt() x
o NumberFormatException

o System.getProperty("line.separator") System.lineSeparator()

§8 - 26
o

o BufferedWriter.newLine()
String

o
String
o
o
o Scanner InputMismatchException

§8 - 27

java.io.PrintWriter

o print() println()
toString
o format() Formatter
printf()

o Writer OutputStream File


Writer
Writer

PrintWriter IOException
o checkError() setError() clearError()
PrintStream, PrintWriter
§8 - 28
PrintWriter

public void writeArrayToFile(float[] anArray) {

PrintWriter out = null;

try (out = new PrintWriter("OutFile.txt")){


for (int i=0; i < anArray.length; i++)

// escribe "fin de línea" independiente de plataforma con println


out.println("Value at: " + i + " = " + anArray[i]);

// puede ser lanzada por el constructor


} catch (FileNotFoundException fnfe) {
// …
} finally
// …
}
}

§8 - 29

PrintWriter

public void writeArrayToFile(float[] anArray) {

PrintWriter out = null;

try (out = new PrintWriter("OutFile.txt")){


for (int i=0; i < anArray.length; i++)

// escribe "fin de línea" independiente de plataforma con %n


out.format("Value at: %d = %f.%n", i, anArray[i]);

// puede ser lanzada por el constructor


} catch (FileNotFoundException fnfe) {
// …
} finally
// …
}
}

§8 - 30
java.util.Scanner

o
o float int boolean String
o
InputMismatchException
o IOException ioException() IOException

o InputStream Reader channel


o File Path
InputStream
o stdin

§8 - 31

public class ScanSum {


public static void main(String[] args) throws IOException {
Scanner s = null; double sum = 0;
try(s = new Scanner(new BufferedReader(
new FileReader("usnumbers.txt")))) {
s.useLocale(Locale.US);
while (s.hasNext()) {
if (s.hasNextDouble()) { sum += s.nextDouble(); }
else { s.next(); }
}
} catch (InputMismatchException ime) { … }
System.out.println(sum);
} usnumbers.txt
}

§8 - 32
o

o
o

o Person
o

§8 - 33

object stream
o ObjectInputStream ObjectOutputStream
o Serializable
Serializable
NotSerializableException
o

o readObject() Object

o transient
§8 - 34
public class ObjectStreamExample { // Utiliza try-with-resources
public static class Person implements Serializable {
public String name = null; public int age = 0;
}
public static void main(String[] args)
throws IOException, ClassNotFoundException {
try(ObjectOutputStream objectsOut = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream("person.bin")))){
Person outPerson = new Person();
outPerson.name = "Noam Chomsky"; outPerson.age = 89;
out.writeObject(outPerson);
}
try(ObjectInputStream in = new ObjectInputStream(
new BufferedInputStream(new FileInputStream("person.bin")))){
Person inPerson = (Person) in.readObject();
}
}
}

§8 - 35

o Serializable

transient

§8 - 36
o
serialVersionUID
o

o serialVersionUID

serialVersionUID
o
o serialVersionUID

§8 - 37

java.io

ByteArrayInputStream CharArrayReader
o
ByteArrayOutputStream CharArrayWriter
o
o toByteArray() toCharArray()

StringReader StringWriter
o String
SequenceInputStream
o

§8 - 38
java.io

PipedInputStream PipedOutputStream
PipedReader PipedWriter
o threads
o
PusbackInputStream PushbackReader
LineNumberReader StreamTokenizer
o
o Scanner split() StreamTokenizer
FilterInputStream FilterOutputStream
FilterReader FilterWriter
o
o
§8 - 39

http://tutorials.jenkov.com/java-io/overview.html

§8 - 40
o

§8 - 41

o
o

o
java.io
o java.nio

§8 - 42
java.io
o

java.nio
o

§8 - 43

§8 - 44
o non-blocking I/O
o

o asynchronous I/O
o

o CompletionHandler Future
java.util.concurrent

§8 - 45

java.nio

o
o
java.nio java.io
o java.nio
o
o
non-blocking mode

o java.io java.nio
o FileChannel
AsynchronousFileChannel

§8 - 46
java.nio

o java.nio
o
java.nio
o

§8 - 47

java.nio

o
o

o FileChannel

§8 - 48
o

o java.io.File
o java.nio.file

o
Old habits die hard
o

§8 - 49

java.io.File

File
o
o getParent()
File
o exists()
o isFile() isDirectory()
o mkdir() mkdirs()
o length()
o renameTo()
o createNewFile() delete()
o list() listFiles()
o canRead()
canWrite() canExecute()
§8 - 50
java.io.File

public class FileManipulationExample {


public static void main(String[] args) {

File f = new File("pepe/doc/path.txt"); // path not absolute


f.getName(); // returns "path.txt"; file may, or may not, exist
f.getParent(); // returns "/pepe/doc"; dir may, or may not, exist
File d = f.getParentFile().getAbsoluteFile(); //"/home/pepe/doc/path"
d.mkdirs(); // created if don’t exist, if already exist no pasa na‘

if ( f.exists() { if ( f.isFile() ) { ... } else { ... }


} else { f.createNewFile() }
if (f.canRead()) { ... } // file corresponding to f must exist
if (f.canWrite()) { ... } // file corresponding to f must exist
if (f.canExecute()) { ... } // file corresponding to f must exist

f.delete(); // deletes file corresponding to f


d.delete(); // deletes directory corresponding to g, if empty

§8 - 51

java.io.File

f.getName(); // as before (File object has not been deleted)


f.getParent(); // as before (File object has not been deleted)

File oldFile = new File("/home/pepe/old");


File newFile = new File("/home/pepe/new");
if (oldFile.renameTo(newFile)){
oldFile=newFile;
System.out.println(oldFile.getName()); // prints "new"
System.out.println(oldFile.getAbsolutePath()) // "/home/pepe/new"
}
d.mkdir(); f.createNewFile();
d.listFiles(); // returns array of File objects (only one element)
d.list(); // returns array of String (only element: "path.txt")
// equivalent to: map( getName, d.listFiles() )
java.net.URL url = java.net.URI.toURL(f.toURI());
// File.toURL() is deprecated
}
}

§8 - 52
java.nio.file

o
java.io.File
o
o

§8 - 53

java.nio.file.Path

Path
o

o
"." ".."
o

Path
o

https://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
o

§8 - 54
java.nio.file.Paths

Paths.get()
o Path
File
o String URI
varargs
https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html#varargs
String
String

§8 - 55

java.nio.file.Files

o
o Files Path
o Files glob

§8 - 56
java.nio.file

public class CopyAndDelete {


public static void main(String[] args) {
if (args.length != 2) {
System.err.println("usage: java CopyAndDelete file1 file2");
return;
}
Path source = Paths.get(args[0]); Path target = Paths.get(args[1]);
try { // gives same result as Files.move(source, target)
Files.copy(source, target); Files.delete(source);
} catch (NoSuchFileException nsfe) { // on copying
System.err.printf("%s: no such file or directory%n", source);
} catch (DirectoryNotEmptyException dnee) { // on deleting directory
System.err.printf("%s: directory not empty%n", source);
} catch (FileAlreadyExistsException faee) { // on copying
System.err.printf("%s: file already exists%n", target);
} catch (IOException ioe) {
System.err.printf("I/O error: %s%n", ioe.getMessage()); }
}
}
§8 - 57

Universidad Complutense de Madrid


Facultad de Informática
Grado en Ingeniería Informática, Grupo en Inglés

Programming Technology

Appendix
java.io.File java.nio.file

java.nio.file.Path java.io.File
o
o java.nio.File.Path.toFile()
java.io.File java.nio.files
o https://docs.oracle.com/javase/tutorial/essential/io/legacy.html

§8 - 59

\n
o
o

o System.getProperty("line.separator") very ugly!


o System.lineSeparator() still pretty ugly!
StringBuilder

o newline() better!

o println("…"), much better!


o %n format() much better!
§8 - 60

También podría gustarte