Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package br.com.geracao.main;
- import java.io.BufferedReader;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import javax.swing.JFileChooser;
- import javax.swing.JOptionPane;
- import javax.swing.filechooser.FileNameExtensionFilter;
- public class Leitor {
- public static void main(String[] args) {
- String caminho = "";
- // Abre o componente JFileChooser.
- JFileChooser chooser = new JFileChooser();
- // Define um filtro de extensão, exemplo: txt.
- FileNameExtensionFilter filter = new FileNameExtensionFilter("Arquivos TXT", "txt");
- // Aplica o filtro.
- chooser.setFileFilter(filter);
- // Abre a janela e pega o valor de resposta.
- int returnVal = chooser.showOpenDialog(null);
- if(returnVal == JFileChooser.APPROVE_OPTION) {
- // Pega o caminho do arquivo.
- caminho = chooser.getSelectedFile().getAbsolutePath();
- } else {
- return;
- }
- // Cria um FileReader (Abre um arquivo e deixa pronto para leitura).
- FileReader fileReader = null;
- try {
- fileReader = new FileReader(caminho);
- } catch (FileNotFoundException e) {
- JOptionPane.showMessageDialog(null, "O arquivo não foi encontrado.");
- return;
- }
- // Lê o arquivo no fileReader usando o BufferedReader.
- String texto = "";
- BufferedReader br = new BufferedReader(fileReader);
- try {
- String linha = br.readLine();
- while (linha != null) {
- texto += linha + "\n";
- linha = br.readLine();
- }
- br.close();
- } catch (Exception e) {
- JOptionPane.showMessageDialog(null, "Erro ao ler o arquivo (" + e.getLocalizedMessage() + ").");
- }
- JOptionPane.showMessageDialog(null, texto);
- JOptionPane.showMessageDialog(null, "Programa finalizado.");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement