import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; class ProgLetturaTXT { public static void main(String argv[]) { JFrame f = new JFrame("Lettura File"); //creo una griglia f.setLayout(new GridLayout(3,1,5,10)); JPanel p1 = new JPanel();//prima riga: label+text JPanel p2 = new JPanel();//seconda riga: label+text JPanel p3 = new JPanel();//seconda riga: label+text JTextField nomefile = new JTextField(40); JButton btnCarica = new JButton("Carica"); JTextArea testo = new JTextArea(30,80); //inserisce le componenti nei pannelli p1.add(new JLabel("File: ", JLabel.RIGHT)); p1.add(nomefile); p2.add(btnCarica); p3.add(testo); f.add(p1); f.add(p2); f.add(p3); //imposto azione per il pulsante btnCarica.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { //variabili String riga; //gestore file FileReader fr = null; BufferedReader fIN = null; //APERTURA file try { fr = new FileReader(nomefile.getText()); fIN = new BufferedReader(fr); } catch(IOException e) { JOptionPane.showMessageDialog(null,"Errore APERTURA "+nomefile.getText(),"ERRORE",JOptionPane.ERROR_MESSAGE); return; } //lettura file riga = ""; try { //leggo una riga intera per volta while((riga = fIN.readLine()) != null) { testo.append(riga+"\n"); }//while lettura } catch(IOException e) { JOptionPane.showMessageDialog(null,"Errore LETTURA "+nomefile.getText(),"ERRORE",JOptionPane.ERROR_MESSAGE); return; } //CHIUSURA file try { fr.close(); } catch(IOException e) { JOptionPane.showMessageDialog(null,"Errore CHIUSURA "+nomefile.getText(),"ERRORE",JOptionPane.ERROR_MESSAGE); return; } } }); //mostro la finestra f.setSize(1600, 900); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); }//main }//NominativoLOR