Advertisement
vinedfs

Exemplo de leitura de arquivo de texto

Jul 22nd, 2014
252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.71 KB | None | 0 0
  1. package br.com.geracao.main;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.FileNotFoundException;
  5. import java.io.FileReader;
  6.  
  7. import javax.swing.JFileChooser;
  8. import javax.swing.JOptionPane;
  9. import javax.swing.filechooser.FileNameExtensionFilter;
  10.  
  11. public class Leitor {
  12.  
  13.     public static void main(String[] args) {
  14.        
  15.         String caminho = "";
  16.        
  17.         // Abre o componente JFileChooser.
  18.         JFileChooser chooser = new JFileChooser();
  19.         // Define um filtro de extensão, exemplo: txt.
  20.         FileNameExtensionFilter filter = new FileNameExtensionFilter("Arquivos TXT", "txt");
  21.         // Aplica o filtro.
  22.         chooser.setFileFilter(filter);
  23.         // Abre a janela e pega o valor de resposta.
  24.         int returnVal = chooser.showOpenDialog(null);
  25.         if(returnVal == JFileChooser.APPROVE_OPTION) {
  26.             // Pega o caminho do arquivo.
  27.             caminho = chooser.getSelectedFile().getAbsolutePath();
  28.         } else {
  29.             return;
  30.         }
  31.        
  32.         // Cria um FileReader (Abre um arquivo e deixa pronto para leitura).
  33.         FileReader fileReader = null;
  34.         try {
  35.             fileReader = new FileReader(caminho);
  36.         } catch (FileNotFoundException e) {
  37.             JOptionPane.showMessageDialog(null, "O arquivo não foi encontrado.");
  38.             return;
  39.         }
  40.        
  41.         // Lê o arquivo no fileReader usando o BufferedReader.
  42.         String texto = "";
  43.         BufferedReader br = new BufferedReader(fileReader);
  44.         try {
  45.             String linha = br.readLine();
  46.             while (linha != null) {
  47.                 texto += linha + "\n";
  48.                 linha = br.readLine();
  49.             }
  50.             br.close();
  51.         } catch (Exception e) {
  52.             JOptionPane.showMessageDialog(null, "Erro ao ler o arquivo (" + e.getLocalizedMessage() + ").");
  53.         }
  54.        
  55.         JOptionPane.showMessageDialog(null, texto);
  56.         JOptionPane.showMessageDialog(null, "Programa finalizado.");
  57.        
  58.     }
  59.  
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement