Entradas e Saídas em Java/Exemplo 01: Leitura e Escrita de Texto

From Wiki**3

< Entradas e Saídas em Java

Nos exemplos abaixo, as funções main declaram o lançamento de excepções. Estas declarações não são, em geral, boa prática (são aplicadas apenas para simplificar o código). As excepções deveriam ser tratadas pela função main.

Exemplo: Leitor1

  public class Leitor1 {

    public static void main(String[] args) {

      // ------------------------------------------------
      // Leitura de linhas
      try (BufferedReader in = new BufferedReader(new FileReader("Leitor1.java"))) {
        String s, s2 = new String();
        while ((s = in.readLine()) != null)
          s2 += s + "\n";
        System.out.print(s2);
      } catch (IOException e) {
        e.printStackTrace();
      }

    }
  }

Exemplo: Leitor2

  public class Leitor2 {

    public static void main(String[] args) {

      // ------------------------------------------------
      // Leitura do System.in (a.k.a. stdin)

      try (BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in))) {
        System.out.print("Enter a line: ");
        System.out.println(stdin.readLine());
      } catch (IOException e) {
        e.printStackTrace();
      }

    }
  }

Exemplo: Leitor3

  public class Leitor3 {

    public static void main(String[] args) {

      String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

      // ------------------------------------------------
      // Leitura de memória (caracteres Unicode: 16 bits)
      try (StringReader strin = new StringReader(s)) {
        int c;
        while ((c = strin.read()) != -1)
          System.out.println((char) c);
      } catch (IOException e) {
        e.printStackTrace();
      }

      // ------------------------------------------------
      // Leitura formatada de memória (bytes: 8 bits)
      byte ba[] = s.getBytes();

      try (DataInputStream memin = new DataInputStream(new ByteArrayInputStream(ba))) {
        while (true)
          System.out.print((char) memin.readByte());
      } catch (EOFException e) {
        System.err.println("... já está!");
      } catch (IOException e) {
        e.printStackTrace();
      }

    }
  }

Exemplo: Escrita em Ficheiro (Escritor1)

  public class Escritor1 {

    public static void main(String[] args) {

      try (BufferedReader in = new BufferedReader(new FileReader("Escritor1.java"))) {
        // String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        // BufferedReader in = new BufferedReader(new StringReader(s));

        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("Escritor1.out")));

        int lineCount = 1;
        String line;
        while ((line = in.readLine()) != null)
          out.printf("%3d: %s\n", lineCount++, line);
        out.close();

      } catch (EOFException e) {
        System.err.println("... já está!");
      } catch (IOException e) {
        e.printStackTrace();
      }

    }

  }