CODE
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextArea;

import java.awt.Container;
import java.awt.Dimension;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileWriter;

public class Ler extends JFrame implements ActionListener {

    private JTextArea       TxtArquivo;
    private JFileChooser    Arquivo;
    private JButton         CmdEscolher, CmdSalvar;
    private JScrollPane     js;

    private void setCenter(JFrame frame) {

        Dimension paneSize      = frame.getSize();
     Dimension screenSize    = frame.getToolkit().getScreenSize();
     frame.setLocation( (screenSize.width - paneSize.width) / 2, (screenSize.height - paneSize.height) / 2);

    }

    public Ler(){

        setSize(400, 300);
        setResizable(false);
        setTitle("Abrindo um arquivo TXT");
        setCenter(this);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Container cp = getContentPane();
        cp.setLayout(null);

        Arquivo     = new JFileChooser(".");

        CmdSalvar = new JButton("Salvar arquivo");
        CmdSalvar.setBounds(50,10,140,25);
        CmdSalvar.addActionListener(this);
        cp.add(CmdSalvar);

        CmdEscolher = new JButton("Escolher arquivo");
        CmdEscolher.setBounds(200,10,140,25);
        CmdEscolher.addActionListener(this);
        cp.add(CmdEscolher);

        TxtArquivo = new JTextArea();
        TxtArquivo.setLineWrap(true);
        js = new JScrollPane(TxtArquivo);
        js.setBounds(5,40,385,210);
        js.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        cp.add(js);

    }

    public void actionPerformed(ActionEvent e){
        
        if(e.getSource() == CmdEscolher){

            int res = Arquivo.showOpenDialog(this);

            if(res == JFileChooser.APPROVE_OPTION){
                File arq = Arquivo.getSelectedFile();
                try{
                    TxtArquivo.setText(retornaString(arq.getPath()));
                } catch(Exception ex){
                    JOptionPane.showMessageDialog(null, "Não foi possível abrir o arquivo" +  arq.getPath() + "!", "Leitura de arquivo", JOptionPane.ERROR_MESSAGE);
                }
            }

        }

        if(e.getSource() == CmdSalvar){

            int res = Arquivo.showSaveDialog(this);
            if(res == JFileChooser.APPROVE_OPTION){
                File arq = Arquivo.getSelectedFile();
                try{
                    escreveArquivo(TxtArquivo.getText(), arq.getPath());
                } catch(IOException ioe){
                    JOptionPane.showMessageDialog(null, "Não foi possível salvar arquivo!");
                }
            }

        }

    }

    public String retornaString(String fileName) throws IOException {

        BufferedReader in = new BufferedReader(new FileReader(fileName));
        String line;
        StringBuffer buffer = new StringBuffer();

        while( (line = in.readLine()) != null ){
            buffer.append(line + "\n");
        }

        in.close();
        return buffer.toString();

    }

    public void escreveArquivo(String conteudo, String fileName) throws IOException {

        PrintWriter out = new PrintWriter(new FileWriter(fileName));
        out.print(conteudo);
        out.close();
        JOptionPane.showMessageDialog(null, "Arquivo salvo com sucesso!");

    }

    public static void main(String args[]) {

        Ler app = new Ler();
        app.show();

    }

}

Como prometido !! tah ae pessoal !
cool.gif

Você gostou? Comente no fórum!

Comentários:

felippe disse:

ola thiago,
sera que voce poderia me ajudar em fazer uma leitura de um simples txt e me dar a opcao de inserir novos dados atraves do showInput e somar oq ja tenho no txt mais oq estou digitando e sempre me mostrar resultados somatorios, ou enfim, qualquer tipo de calculo que eu desejar executar.
grato

Thiago Ananias disse:

Como assim? vc quer abrir um TXT ler oq tem dentro dele e CONCATENAR com uma variavel que vc vai armazenar o valor vindo de um JOptionPane.showInputDialog("")??

AndersonDutra disse:

Aproveitando o tópico. Se eu quiser fazer o seguinte. Tenho um texto assim:

Inicio

Hello Word

Fim

Quero identifica a palavra Fim e inserir antes dela. Como eu faço isso??

Thiago Ananias disse:

Anderson isso eh manipular String, veja os metodos indexOf e substring, são iguais ao javascript!

Ver o restante dos comentários no fórum (e aproveitar pra comentar também !).

Mais recentes em JSP e Java

Api's java
Por Daniel Vidal - Lista de api's...
Validador stella
Por Lucasbr - O caelum stella visa suprir as necessidades comumente...
Jsp - expression language
Por Daniel Vidal - Pra quem quiser conhecer um pouco mais sobre as els,...
[java] listeners
Por Daniel Vidal - Listeners - o java possui diversos tipos de listeners...
[swing] adicionando menu ao frame
Por Daniel Vidal - Passo 2...

Ver mais Artigos de JSP e Java.

Ver e retirar outras dúvidas no fórum Webly.

Alguns Direitos Reservados | RSS | O Fórum

Webly Portal e Fóruns - Internet + Humana | Design by ArthurHenrique.com