Entradas e Saídas em Java
From Wiki**3
Mecanismos de entradas e saídas em Java. A classe File. Streams, Readers, Writers. Composição de canais. Acesso aleatório a ficheiros. Serialização de tipos primitivos e de objectos: a interface Serializable. Elementos não serializáveis: a palavra chave transient. Excepções associadas a entradas e saídas.
Mecanismos de Entrada e Saída de Dados
Mecanismos de entradas e saídas em Java. A classe File. Streams, Readers, Writers. Composição de canais. Acesso aleatório a ficheiros.
Exemplo: Leitor1
<java5> public class Leitor1 {
public static void main(String[] args) throws IOException {
//------------------------------------------------ // Leitura de linhas
BufferedReader in = new BufferedReader(new FileReader("Leitor1.java"));
String s, s2 = new String();
while((s = in.readLine()) != null) s2 += s + "\n";
in.close();
System.out.print(s2);
//------------------------------------------------ // Leitura do System.in (a.k.a. stdin)
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a line: ");
System.out.println(stdin.readLine());
}
} </java5>
Exemplo: Leitor2
<java5> public class Leitor2 {
public static void main(String[] args) throws IOException {
String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//------------------------------------------------ // Leitura de memória (caracteres Unicode: 16 bits) StringReader strin = new StringReader(s); int c; while((c = strin.read()) != -1) System.out.println((char)c);
//------------------------------------------------
// Leitura formatada de memória (bytes: 8 bits)
try {
byte ba[] = s.getBytes();
DataInputStream memin = new DataInputStream(new ByteArrayInputStream(ba));
while(true) System.out.print((char)memin.readByte());
}
catch(EOFException e) { System.err.println("... já está!"); }
}
} </java5>
Exemplo: Escrita em Ficheiro (Escritor1)
<java5> public class Escritor1 {
public static void main(String[] args) throws IOException {
try {
//String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//BufferedReader in = new BufferedReader(new StringReader(s));
BufferedReader in = new BufferedReader(new FileReader("Escritor1.java"));
PrintWriter out =
new PrintWriter(new BufferedWriter(new FileWriter("Escritor1.out")));
int lineCount = 1;
while((s = in.readLine()) != null ) out.printf("%3d: %s\n", lineCount++, s);
out.close();
}
catch(EOFException e) { System.err.println("... já está!"); }
}
} </java5>
Exemplo: Escrita de Leitura Binárias (dados) (Escritor2)
<java5> public class Escritor2 {
public static void main(String[] args) throws IOException {
try {
DataOutputStream out =
new DataOutputStream(new BufferedOutputStream(new FileOutputStream("raw.dat")));
out.writeUTF("Valor de PI");
out.writeDouble(Math.PI);
out.writeUTF("Raiz quadrada de 2");
out.writeDouble(Math.sqrt(2));
out.close();
DataInputStream in =
new DataInputStream(new BufferedInputStream(new FileInputStream("raw.dat")));
System.out.println(in.readUTF());
System.out.println(in.readDouble());
System.out.println(in.readUTF());
System.out.println(in.readDouble());
}
catch(EOFException e) { throw new RuntimeException(e); }
}
} </java5>
Exemplo: Leitura e Escrita de Acesso Aleatório
<java5> public class LeituraEscritaAleatória {
public static void main(String[] args) throws IOException {
RandomAccessFile rf = new RandomAccessFile("raw.dat", "rw");
for(int i = 0; i < 10; i++) rf.writeDouble(i * 1.414);
rf.close();
rf = new RandomAccessFile("raw.dat", "rw");
rf.seek(5*8);
rf.writeDouble(47.0001);
rf.close();
rf = new RandomAccessFile("raw.dat", "r");
for(int i = 0; i < 10; i++)
System.out.println("Valor " + i + ": " + rf.readDouble());
rf.close();
}
} </java5>
Serialização de Objectos
Serialização de tipos primitivos e de objectos: a interface Serializable. Elementos não serializáveis: a palavra chave transient.
Exemplo: Zorg e Zog
<java5> class Alienígena implements Serializable {
String _nome;
transient String _segredo = "7";
public Alienígena(String n) { _nome = n; _segredo = _nome + _nome.length(); }
public void voing() { System.out.println(_nome + (_segredo != null ? _segredo : "")); }
} </java5>
<java5> public class Serialização {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Alienígena a1 = new Alienígena("Zorg"), a2 = new Alienígena("Zog");
a1.voing(); //output: ZorgZorg4
a2.voing(); //output: ZogZog3
ObjectOutputStream out =
new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("raw.dat")));
out.writeObject(a1); out.writeObject(a2);
out.close();
ObjectInputStream in =
new ObjectInputStream(new BufferedInputStream(new FileInputStream("raw.dat")));
Alienígena r1 = (Alienígena)in.readObject(); // pode lançar “StreamCorruptedException”
Alienígena r2 = (Alienígena)in.readObject();
r1.voing(); //output: Zorg
r2.voing(); //output: Zog
}
} </java5>
Exemplos
- Exemplo 04: Serialização de Objectos - Zorg e Zog