|
|
Line 5: |
Line 5: |
| == Mecanismos de Entrada e Saída de Dados == | | == 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. | | 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>
| |
|
| |
|
| == Exemplos == | | == Exemplos == |