Je ne réussi pas à utiliser Ecrire une sortie dans un fichier texte en utilisant NetBeans. J'essaie d'utiliser "BufferedWriter". Dans le code suivant, je tente lire le fichier dont le nom doit être inserté en remplaçant le texte "Digite aqui o arquivo com os dados". Alors, le programme crée un fichier sortie appelé "Saida.txt" quand on clique sur "Vai"; le programme devrait écrire quelques informations dans ce fichier, mais il bloque.

Voici ci-dessous le code:
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
 
/*
 * MagnAjusteIGU.java
 *
 * Created on 19/10/2012, 12:14:00
 */
 
package magnajuste;
 
 
import java.io.*;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
 
/**
 *
 * @author llcastro
 */
public class MagnAjusteIGU extends javax.swing.JFrame {
 
    /** Creates new form MagnAjusteIGU */
    public MagnAjusteIGU() {
        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() {
 
        txArqEnt = new javax.swing.JTextField();
        lbTitulo = new javax.swing.JLabel();
        btVai = new javax.swing.JButton();
        lbChutes = new javax.swing.JLabel();
        txDisp = new javax.swing.JTextField();
        txDmod = new javax.swing.JTextField();
        txMagnz = new javax.swing.JTextField();
        lbDisp = new javax.swing.JLabel();
        lbDmod = new javax.swing.JLabel();
        lbMagnz = new javax.swing.JLabel();
        txSaida = new javax.swing.JTextField();
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("Ajuste de magnetização por curva de Langevin"); // NOI18N
 
        txArqEnt.setText("Digite aqui o arquivo com os dados.");
        txArqEnt.setToolTipText("");
        txArqEnt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txArqEntActionPerformed(evt);
            }
        });
 
        lbTitulo.setText("Ajuste da magnetização por curva de Langevin");
 
        btVai.setText("Vai!");
        btVai.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btVaiActionPerformed(evt);
            }
        });
 
        lbChutes.setText("Chutes iniciais:");
 
        txDisp.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txDisp.setText("0.5");
        txDisp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txDispActionPerformed(evt);
            }
        });
 
        txDmod.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txDmod.setText("10.0");
 
        txMagnz.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txMagnz.setText("500");
 
        lbDisp.setText("dispersão dos diâmetros");
 
        lbDmod.setText("diâmetro modal (nm)");
 
        lbMagnz.setText("magnetização do sólido (A/m)");
 
        txSaida.setText("saída");
        txSaida.setToolTipText("");
        txSaida.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txSaidaActionPerformed(evt);
            }
        });
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btVai)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txSaida, javax.swing.GroupLayout.DEFAULT_SIZE, 352, Short.MAX_VALUE))
                    .addComponent(lbTitulo)
                    .addComponent(txArqEnt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbChutes)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txDisp, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lbDisp))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txDmod, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lbDmod))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txMagnz, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lbMagnz)))
                .addContainerGap())
        );
 
        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {txDisp, txDmod, txMagnz});
 
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lbTitulo)
                .addGap(18, 18, 18)
                .addComponent(txArqEnt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(lbChutes)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txDisp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbDisp))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txDmod, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbDmod))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txMagnz, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbMagnz))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btVai)
                    .addComponent(txSaida, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
 
        pack();
    }// </editor-fold>                        
 
private void txArqEntActionPerformed(java.awt.event.ActionEvent evt) {                                         
// TODO add your handling code here:
}                                        
 
private void txDispActionPerformed(java.awt.event.ActionEvent evt) {                                       
// TODO add your handling code here:
}                                      
 
private void btVaiActionPerformed(java.awt.event.ActionEvent evt) {                                      
 
      // Entrada de dados pela interface gráfico:
 
      double inDisp = Double.parseDouble(txDisp.getText());
      double inDmod = Double.parseDouble(txDmod.getText());
      double inMsol = Double.parseDouble(txMagnz.getText());
 
      String arqEnt = txArqEnt.getText();
 
      // Dados de entrada por arquivo:
 
      Vector<Float> inB = new Vector<Float>();
      Vector<Float> inM = new Vector<Float>();
 
      BufferedReader br = null;
      BufferedWriter bw = null;
 
      String nomeArqSaida = "Saida.txt";
 
      File arqSaida = new File(nomeArqSaida);
        try
        {
          arqSaida.createNewFile();
          bw = new BufferedWriter(new OutputStreamWriter
        (new FileOutputStream(arqSaida)));
 
        }
        catch (IOException ex)
        {
          Logger.getLogger(MagnAjusteIGU.class.getName()).log(Level.SEVERE, null, ex);
        }
 
      // Outras variaveis:
 
      String linha;
 
      try
      {
        br = new BufferedReader(new FileReader(new File(arqEnt)));
      }
      // Definicao de excecao:      
      catch (FileNotFoundException ex)
      {
        Logger.getLogger(MagnAjusteIGU.class.getName())
                .log(Level.SEVERE,null, ex);
      }
 
      // Tentativa de ler a proxima linha:
      try
      {
        while ( ( linha = br.readLine() ) != null)
        {
          // Definicao de separadores de dados:
          String delims = "[ ]+";
 
          // Leitura dos dados no vetor coluna:
          String[] coluna = linha.split(delims);
 
          // Atribuicao dos dados aos vetores inB e inM:
          inB.add(Float.parseFloat(coluna[0]));  
          inM.add(Float.parseFloat(coluna[1]));
 
          // Relato de dados no campo de saida:
          txSaida.setText("Leu inB: "+inB);
        }
      }
      // Definicao de excecao:
      catch (IOException ex)
      {
        Logger.getLogger(MagnAjusteIGU.class.getName())
                .log(Level.SEVERE,null, ex);
      }
 
      // Tentativa de escrever no arquivo de saida:
      try
      {
        // Impressao do numero de dados de campo e magnetizacao:
        bw.write("Numero de campos :"+inB.size());
        bw.newLine();
        bw.write("Numero de magnetizações:"+inM.size());
 
        txSaida.setText("Leu inB.size(): "+inB.size());
 
 
        // Impressao dos dados: 
        for(int i=0; i<inB.size(); i++)
        {
          bw.write(" "+ inB.get(i) +" "+inM.get(i));
        }
 
        // Fechar arquivo de saida:
        bw.close();
      }
      // Tratamento de excecao:
      catch (IOException ex)
      {
        Logger.getLogger(MagnAjusteIGU.class.getName())
          .log(Level.SEVERE, null, ex);
      }
 
      JOptionPane.showMessageDialog
      (
       null, // este argumento tem relacao com local da janela
        "Disp: " + inDisp
       + " / Dmod: " + inDmod
       + " / Msol: " + inMsol
       + " / Entr.: " + arqEnt
      );
 
}                                     
 
private void txSaidaActionPerformed(java.awt.event.ActionEvent evt) {                                        
// TODO add your handling code here:
}                                       
 
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see <a href="http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html" target="_blank">http://download.oracle.com/javase/tu...feel/plaf.html</a> 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MagnAjusteIGU.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MagnAjusteIGU.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MagnAjusteIGU.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MagnAjusteIGU.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
 
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
 
            public void run() {
                new MagnAjusteIGU().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton btVai;
    private javax.swing.JLabel lbChutes;
    private javax.swing.JLabel lbDisp;
    private javax.swing.JLabel lbDmod;
    private javax.swing.JLabel lbMagnz;
    private javax.swing.JLabel lbTitulo;
    private javax.swing.JTextField txArqEnt;
    private javax.swing.JTextField txDisp;
    private javax.swing.JTextField txDmod;
    private javax.swing.JTextField txMagnz;
    private javax.swing.JTextField txSaida;
    // End of variables declaration                   
}