creacion de un archivo de texto,bloc de notas ó .txt desde java

Technology

creacion de un archivo de texto,bloc de notas ó .txt desde java

primero creamos el proyecto yo lo voy a llamar texto luego creamos una nueva clase la voy a llamar textoclass y en esta clase ponemos el siguiente codigo:
package texto;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import javax.swing.JFileChooser;
import javax.swing.JTextArea;

/**
 * @web http://javayotros.blogspot.com/
 * @author java
 */
public class textoclass {    
//para leer
File archivo = null;
FileReader fr = null;
BufferedReader br = null;
//para escribir
FileWriter fichero = null;
PrintWriter pw = null;
//ruta absoluta del archivo a manipular
String ruta = "";

    public textoclass(){
    }
    
    private String OpenFile(String ruta){
        String t="";
        try {         
            archivo = new File (ruta);            
            fr = new FileReader (archivo);
            br = new BufferedReader(fr);
            // Lectura del fichero linea por linea
            String linea;
            while((linea=br.readLine())!=null)            
                t = t + linea + "\n";
        }
      catch(Exception e){
         e.printStackTrace();
      }finally{         
         try{                    
            if( null != fr ){   
               fr.close();     
            }                  
         }catch (Exception e2){ 
            e2.printStackTrace();
         }
      }
        return t;
    }
    
    private void SaveFile(String t, String ruta){   
    //se separa el texto cada salto de linea
    StringTokenizer st = new StringTokenizer(t,"\n");
    try
        {
            fichero = new FileWriter(ruta);
            pw = new PrintWriter(fichero);                               
            //se guarda linea por linea en el archivo
            while(st.hasMoreTokens()){
                String line = st.nextToken();
                pw.println(line);           
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
           try {           
           if (null != fichero)
              fichero.close();
           } catch (Exception e2) {
              e2.printStackTrace();
           }
        }                
    }
    
    //segun la opcion muestra en pantalla una ventana de dialogo
    //para "abrir" o "guardar" un archivo
    public boolean  Dialog(String Opcion, JTextArea tArea){                
        //esta variable se utiliza como una bandera de retorno
        //no es necesaria, solo sirve para tener un control         
        boolean b=true;
        //ventana para "abrir un archivo", retorna FALSE si se abre
        if (Opcion.equals("Open")){
                JFileChooser fileChooser = new JFileChooser();              
                int result = fileChooser.showOpenDialog(null);  
                if ( result == JFileChooser.APPROVE_OPTION ){            
                    ruta = fileChooser.getSelectedFile().getAbsolutePath(); 
                    tArea.setText(OpenFile(ruta));                                       
                    b=false;
                }
        }
        //ventana para guardar un archivo
        else if (Opcion.equals("Save As")){
                JFileChooser fileChooser = new JFileChooser();              
                int result = fileChooser.showSaveDialog(null);
                if ( result == JFileChooser.APPROVE_OPTION ){                       
                    ruta = fileChooser.getSelectedFile().getAbsolutePath();                          
                    ruta = ruta + ".txt";
                    SaveFile(tArea.getText() ,ruta);                           
                    b=false;
                }
        }
        //aqui no muestra ninguna ventana, guarda automaticamente el archivo
        //respecto a un archivi previamente abierto
        else if(Opcion.equals("Save")){
            SaveFile(tArea.getText() ,ruta); 
            b=false;
        }       
        return b;
    }
}
lugo creamos el jframe yo lo llame textoform con el siguiente codigo pueden armar el jframe :
package texto;
/**
 * @web 
 * @author  andres2288
 */
public class textoform extends javax.swing.JFrame {
    
    /** Creates new form textoform */
    public textoform() {
        initComponents();
        this.setTitle(title + "new document]");
    }
    
    /** 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.
     */
    //                           
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        TEXTO = new javax.swing.JTextArea();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        smNew = new javax.swing.JMenuItem();
        smOpen = new javax.swing.JMenuItem();
        smSave1 = new javax.swing.JMenuItem();
        smSave2 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        smAcerca = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        TEXTO.setColumns(20);
        TEXTO.setRows(5);
        TEXTO.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                TEXTOKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(TEXTO);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 570, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 461, Short.MAX_VALUE)
        );

        jMenu1.setText("Archivo");

        smNew.setText("Nuevo");
        smNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                smNewActionPerformed(evt);
            }
        });
        jMenu1.add(smNew);

        smOpen.setText("Abrir archivo...");
        smOpen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                smOpenActionPerformed(evt);
            }
        });
        jMenu1.add(smOpen);

        smSave1.setText("Guardar");
        smSave1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                smSave1ActionPerformed(evt);
            }
        });
        jMenu1.add(smSave1);

        smSave2.setText("Guardar como");
        smSave2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                smSave2ActionPerformed(evt);
            }
        });
        jMenu1.add(smSave2);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Ayuda");

        smAcerca.setText("Acerca de...");
        smAcerca.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                smAcercaActionPerformed(evt);
            }
        });
        jMenu2.add(smAcerca);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }//                         

    private void smOpenActionPerformed(java.awt.event.ActionEvent evt) {                                       
        // Abre archivo de texto            
       isnew=tc.Dialog("Open",TEXTO);   
       this.setTitle(title + tc.ruta+"]");
    }                                      

    private void smSave2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // Guarda en un nuevo archivo
       isnew=tc.Dialog("Save As",  TEXTO); 
        this.setTitle(title + tc.ruta+"]");
}                                       

    private void smSave1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // Guarda modificaciones de un archivo abierto
        if (isnew) {
           isnew = tc.Dialog("Save As", TEXTO);
           this.setTitle(title + tc.ruta + "]");
        }
        else
        {                 
            isnew=tc.Dialog("Save", TEXTO);   
            this.setTitle(title + tc.ruta+"]");
        }
    }                                       

    private void TEXTOKeyReleased(java.awt.event.KeyEvent evt) {                                  
        // TODO add your handling code here:
        
    }                                 

    private void smNewActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // TODO add your handling code here:
        TEXTO.setText("");
        isnew=true;
        this.setTitle(title + "new document]");
    }                                     

    private void smAcercaActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        TEXTO.setText("visitame: javayotros.blogspot.com");
    }                                        
    
    /**
     * @param args the command line arguments
     */
    textoclass tc = new textoclass();
    Boolean isnew = true;
    String title = "R/W editado by andres2288- file:[";
    
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new textoform().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify                     
    private javax.swing.JTextArea TEXTO;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JMenuItem smAcerca;
    private javax.swing.JMenuItem smNew;
    private javax.swing.JMenuItem smOpen;
    private javax.swing.JMenuItem smSave1;
    private javax.swing.JMenuItem smSave2;
    // End of variables declaration                   
    
}
y eso es todo finalmente la salida del programa es el siguiente
aqui un video tutorial

Post a Comment

2 Comments