Mostrando entradas con la etiqueta File & IO. Mostrar todas las entradas
Mostrando entradas con la etiqueta File & IO. Mostrar todas las entradas

jueves, 15 de octubre de 2015

Simple Editor Java - File Analizer





package Proyecto;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.io.File;
import java.io.FileWriter;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import org.jdesktop.swingx.JXCollapsiblePane;

public class Principal extends javax.swing.JFrame
{
    public Principal()
    {
        initComponents();
        this.setLocationRelativeTo(null);
        setTitle("Code Editor");
        jXCollapsiblePane1.setLayout(new BorderLayout());
        jXCollapsiblePane1.add(jPanel2, BorderLayout.CENTER);
        btnControl.addActionListener(jXCollapsiblePane1.getActionMap().get(JXCollapsiblePane.TOGGLE_ACTION));
        //txtEditor.setText("public class Hola {}");
        dirArchivo.setEnabled(false);
    }
    
    String titulo = " - Editor 0.1";
    final StyleContext cont = StyleContext.getDefaultStyleContext();
    final AttributeSet attr = cont.addAttribute(cont.getEmptySet(), StyleConstants.Foreground, Color.BLUE);
    final AttributeSet attrBlack = cont.addAttribute(cont.getEmptySet(), StyleConstants.Foreground, Color.BLACK);
    final AttributeSet attrComent = cont.addAttribute(cont.getEmptySet(), StyleConstants.Foreground, Color.RED);
    
    DefaultStyledDocument doc = new DefaultStyledDocument()
    {
        @Override
        public void insertString(int offset, String str, AttributeSet a) throws BadLocationException
        {
            super.insertString(offset, str, a);
            String text = getText(0, getLength());
            int before = findLastNonWordChar(text, offset);
            if (before < 0) 
            {
                before = 0;
            }
            int after = findFirstNonWordChar(text, offset + str.length());
            int wordL = before;
            int wordR = before;

            while (wordR <= after) {
                if (wordR == after || String.valueOf(text.charAt(wordR)).matches("\\W")) {
                    if (text.substring(wordL, wordR).matches("(\\W)*(abstract|continue|for|new|switch|default|if|package|synchronized|boolean|do|goto|private|this|break|double|implements|protected|throw|byte|else|import|public|throws|case|enum|return|catch|extends|int|short|try|char|final|interface|static|void|class|finally|long|volatile|const|float|native|super|while)")) {
                        setCharacterAttributes(wordL, wordR - wordL, attr, false);
                    } else {
                        setCharacterAttributes(wordL, wordR - wordL, attrBlack, false);
                    }
                    wordL = wordR;
                }
                wordR++;
            }
        }

        public void remove(int offs, int len) throws BadLocationException {
            super.remove(offs, len);
            String text = getText(0, getLength());
            int before = findLastNonWordChar(text, offs);
            if (before < 0) {
                before = 0;
            }
            int after = findFirstNonWordChar(text, offs);

            if (text.substring(before, after).matches("(\\W)*(abstract|continue|for|new|switch|default|if|package|synchronized|boolean|do|goto|private|this|break|double|implements|protected|throw|byte|else|import|public|throws|case|enum|return|catch|extends|int|short|try|char|final|interface|static|void|class|finally|long|volatile|const|float|native|super|while)")) 
.
.
.
Descargar:
https://www.dropbox.com/s/8f9bxbls19xdxa0/Compilers.rar?dl=0
https://www.youtube.com/user/delfirosales

miércoles, 28 de mayo de 2014

Reproductor de Audio en Java

Reproductor de Audio basico en Java con opciones de Play, Pausa y Stop.
Primero descargar e instalar Java Media Framework API (JMF) del siguiente enlace. http://www.oracle.com/technetwork/java/javase/download-142937.html


import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.media.CannotRealizeException;
import javax.media.Manager;
import javax.media.NoPlayerException;
import javax.media.Player;
import javax.media.Time;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Delfi
 */
public class Reproductor extends javax.swing.JFrame {
   
    Player audioPlayer = null;
    String audioPath = " ";  
    /**
     * Creates new form Reproductor
     */
    public Reproductor() {
        initComponents();
        this.setLocationRelativeTo(null);
        jlabelEstado.setText(" ");
        dirArchivo.setText(" ");
    }  

    /**
     * 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")
    //                         
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        btnPlay = new javax.swing.JButton();
        btnPause = new javax.swing.JButton();
        btnStop = new javax.swing.JButton();
        jlabelEstado = new javax.swing.JLabel();
        dirArchivo = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuAbrir = new javax.swing.JMenuItem();
        jMenuSalir = new javax.swing.JMenuItem();
        jMenuAbout = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Reproductor de Audio - Java Tips - http://javacodebasics.blogspot.mx");
        setIconImage(new ImageIcon(getClass().getResource("/Imagenes/music.png")).getImage());
        setResizable(false);

        btnPlay.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/play.png"))); // NOI18N
        btnPlay.setText("Play");
        btnPlay.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPlayActionPerformed(evt);
            }
        });

        btnPause.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/pause.png"))); // NOI18N
        btnPause.setText("Pause");
        btnPause.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPauseActionPerformed(evt);
            }
        });

        btnStop.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/stop.png"))); // NOI18N
        btnStop.setText("Stop");
        btnStop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnStopActionPerformed(evt);
            }
        });

        jlabelEstado.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jlabelEstado.setText("Reproductor");

        dirArchivo.setText(" ");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(btnPlay, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btnPause, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btnStop, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jlabelEstado, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(dirArchivo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(14, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnPlay)
                    .addComponent(btnPause)
                    .addComponent(btnStop))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jlabelEstado)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(dirArchivo)
                .addGap(3, 3, 3))
        );

        jMenu1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/archivo.png"))); // NOI18N
        jMenu1.setText("Archivo");

        jMenuAbrir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/abrir.png"))); // NOI18N
        jMenuAbrir.setText("Abrir archivo de audio");
        jMenuAbrir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuAbrirActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuAbrir);

        jMenuSalir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/salir.png"))); // NOI18N
        jMenuSalir.setText("Salir");
        jMenuSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuSalirActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuSalir);

        jMenuBar1.add(jMenu1);

        jMenuAbout.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/about.png"))); // NOI18N
        jMenuAbout.setText("About");
        jMenuAbout.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenuAboutMouseClicked(evt);
            }
        });
        jMenuBar1.add(jMenuAbout);

        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()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }//                       

    private void btnPauseActionPerformed(java.awt.event.ActionEvent evt) {                                        
        audioPlayer.stop();
        jlabelEstado.setText("Pausa");
    }                                      

    private void btnPlayActionPerformed(java.awt.event.ActionEvent evt) {                                      
        if(file.equals(""))
        {
            JOptionPane.showMessageDialog(null, "Cargue una Pista de Audio", "Error al Reproducir", JOptionPane.INFORMATION_MESSAGE, new ImageIcon(getClass().getResource("/imagenes/verificar.png")));
        }
        else
        {
            audioPlayer.start();
            jlabelEstado.setText("Reproduciendo");
        }
    }                                      

    private void btnStopActionPerformed(java.awt.event.ActionEvent evt) {                                      
        audioPlayer.stop();
        audioPlayer.setMediaTime(new Time(0.0));
        jlabelEstado.setText("");
    }                                      

    String file="";
    public String abrirAudio()
    {    
        JFileChooser se = new JFileChooser();
       
        se.setCurrentDirectory(new File(System.getProperty("user.home") + "\\Music"));
        FileNameExtensionFilter filtro = new FileNameExtensionFilter("Archivos de Imagen", "mp3", "wav");
        se.setFileFilter(filtro);
        se.setFileSelectionMode(JFileChooser.FILES_ONLY);
       
        int estado = se.showOpenDialog(null);
        if(estado == JFileChooser.APPROVE_OPTION)
        {
            try
            {
                String pathArchivo = se.getSelectedFile().getPath();
                URL url = se.getSelectedFile().toURL();  
                this.file= se.getSelectedFile().getName();
                audioPlayer = Manager.createRealizedPlayer( url );
                dirArchivo.setText(pathArchivo);
            } catch (MalformedURLException ex) {
                Logger.getLogger(Reproductor.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Reproductor.class.getName()).log(Level.SEVERE, null, ex);
            } catch (NoPlayerException ex) {
                Logger.getLogger(Reproductor.class.getName()).log(Level.SEVERE, null, ex);
            } catch (CannotRealizeException ex) {
                Logger.getLogger(Reproductor.class.getName()).log(Level.SEVERE, null, ex);
            }
        }        
        return "Java Tips - " + this.file;
    }
   
    private void jMenuAbrirActionPerformed(java.awt.event.ActionEvent evt) {                                          
      this.setTitle(abrirAudio());
    }                                        

    private void jMenuSalirActionPerformed(java.awt.event.ActionEvent evt) {                                          
        this.dispose();
    }                                        

    private void jMenuAboutMouseClicked(java.awt.event.MouseEvent evt) {                                      
        About a = new About();
        a.setVisible(true);
    }                                      

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        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(Reproductor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Reproductor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Reproductor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Reproductor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Reproductor().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                    
    private javax.swing.JButton btnPause;
    private javax.swing.JButton btnPlay;
    private javax.swing.JButton btnStop;
    private javax.swing.JLabel dirArchivo;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenuAbout;
    private javax.swing.JMenuItem jMenuAbrir;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuSalir;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JLabel jlabelEstado;
    // End of variables declaration                  
}



Descargar Archivo Netbeans:

sábado, 21 de diciembre de 2013

Get File size in bytes

Obtener el tamaño de un archivo en bytes, KB y MB utilizando el método length de la clase File de Java.
import java.io.*;
 
public class GetFileSizeInByetes {
 
  public static void main(String[] args) {
   
    //create file object
    File file = new File("C:\Users\Delfi\Desktop\Aplicacion.java");
   
    /*
     * To get the size of a file, use
     * long length() method of Java File class.
     *
     * This method returns size of a particular file in bytes. It returns 0L
     * if file does not exists, and unspecified if file is a directory.
     *
     */
   
     long fileSize = file.length();
   
     System.out.println("File size in bytes is: " + fileSize);
     System.out.println("File size in KB is : " + (double)fileSize/1024);
     System.out.println("File size in MB is :" + (double)fileSize/(1024*1024));
  }
}
Output:
File size in bytes is: 492480
File size in KB is : 480.9375
File size in MB is :0.46966552734375

Entradas populares