Botão gravar dados em arquivo

5 respostas
F

E ai pessoal blz?

Tava fazendo um programa, com interface no NetBeans, para gravar qualquer coisa que o usuário digitasse na jTextArea.
Para isso criei uma classe Arquivo que contem o metodo escreve, que escreve em um txt. Tambem criei um JFrame que contem um jTextArea e um botão para enviar os dados escritos na jTextArea para o arquivo txt atravez do método escreve.
O problema é que quando chamo o método para escrever no arquivo (método: escreve) dentro do JFrame Tela o NetBeans pede para colocar throws IOException.

A linha errada é a 74 da Classe Tela. Essa linha fica toda sulinhada e quando vc poem o mouse em cima aparece a seguinte frase:
"unreported exception java.io.IOException; must be caught or declared to be thrown"

Já importei o java.io.*; e ja tentei colocar em todos os locais possiveis o throws IOException, mas não da certo.

Gostaria de saber como resolver esse problema.

Desde já agradeço. Abaixo estão as classes do programa

Classe "Arquivo"
import java.io.*;


public class Arquivo {

    Arquivo(){

    }

	public void escreve (String texto) throws IOException{

		PrintWriter arquivo = new PrintWriter(new FileWriter("arquivo.txt"));

		arquivo.println(texto);
		
		arquivo.close();
	}//FIM  escreve
}//FIM class

E a Interface

import java.io.*;

public class Tela extends javax.swing.JFrame {

    /** Creates new form Tela */
    public Tela() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton1 = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jButton1.setText("Gravar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(64, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(81, 81, 81))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(85, 85, 85)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton1)
                .addContainerGap(83, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>



    //  O PROBLEMA ESTA AQUI !!!
    //          |
    //          |
   //           V
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        Arquivo arquivo1 = new Arquivo();

        String texto= this.jTextArea1.getText();

        arquivo1.escreve(texto); //  O PROBLEMA 

    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Tela().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration

}

5 Respostas

R
public void escreve (String texto){  
        try{
        PrintWriter arquivo = new PrintWriter(new FileWriter("arquivo.txt"));  
  
        arquivo.println(texto);  
          
        arquivo.close();  
        }catch(java.io.IOException){}
    }

Que tal usar um try-catch ao invés de um throw?

F

Vo tentar aki Rafael
se der certo te aviso
obrigado

F

Ta dando um erro vc sabe o que é?

ta aparecendo na linha do catch quando coloca o mouse em cima

java.io.IOException = >“java” não é uma variável conhecida no contexto atual.<

R

fra:
Ta dando um erro vc sabe o que é?

ta aparecendo na linha do catch quando coloca o mouse em cima

java.io.IOException = >“java” não é uma variável conhecida no contexto atual.<

Como você já fez o import de tudo, com java.io.*;, só é necessário mencionar IOException.

Erro meu, sorry.

F

Muito obrigado resolvi meu problema

Criado 11 de julho de 2010
Ultima resposta 11 de jul. de 2010
Respostas 5
Participantes 2