Jump to content
Fórum Script Brasil
  • 0

Gravar arquivo na pasta do projeto


SirSmart
 Share

Question

2 answers to this question

Recommended Posts

  • 0

Dá uma olhadinha neste código e tente entender. Fiz com imagem, mas acredito que dê para fazer com arquivo

Lembrando que você pode usar o JFileChooser para pegar o caminho 

//Metodo para fazer upload de image
    public void uploadImage(File src,String nomeImg) throws FileNotFoundException{
        
        FileInputStream entrada = new FileInputStream(src);
        FileOutputStream saida = new FileOutputStream("img_patrimonio/"+nomeImg);
        int buffer;
          try {
                while((buffer = entrada.read()) != -1){
                 
                     saida.write(buffer);
                
                }
             } catch (IOException ex) {
                 
                    JOptionPane.showConfirmDialog(null,"Erro de buffer!\n"+ex,"Alerta!",JOptionPane.ERROR_MESSAGE);
          }
          try {
              
               entrada.close();
               
          } catch (IOException ex){
                    JOptionPane.showConfirmDialog(null,"Erro de entrada!\n"+ex,"Alerta!",JOptionPane.ERROR_MESSAGE);
          }
          try {
              
              saida.close();
              
          } catch (IOException ex) {
              
              JOptionPane.showConfirmDialog(null,"Erro de saída!\n"+ex,"Alerta!",JOptionPane.ERROR_MESSAGE);
              
          }
        
    }

Pegando o caminho

 

public void actionPerformed(ActionEvent e) {
                JFileChooser teste = new JFileChooser();
                FileNameExtensionFilter f = new FileNameExtensionFilter("*jpg","jpg");
                teste.setFileFilter(f);
                teste.showOpenDialog(jpForm);
                try{
            
                    jlbUrlImg.setText(teste.getSelectedFile().toString());
          
                }catch(Exception ex){
            
                    System.out.println("Nenhum arquivo selecionado!");
            
                }
            }

Criei um objeto chamado teste e um chamado  "f".

Teste é o JFileChooser, e "F" é o tipo de arquivo que será lido.

teste.getSelectedFile().toString()

pega o caminho do arquivo selecionado.

Link to comment
Share on other sites

  • 0
Criei um mini projeto para ficar melhor o entendimento.
Obrigado!
package mover;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;

public class MoverArquivo extends javax.swing.JFrame {

    public MoverArquivo() {
        initComponents();
    }
    
    //Metodo que será responsável por enviar o arquivo
    public void enviarArquivo(File arquivo){
        
        
        try {
            //Recebendo o arquivo de entrada
            FileInputStream entrada = new FileInputStream(arquivo);
            //Preparando arquivo de saida
            FileOutputStream saida = new FileOutputStream("teste.zip");
            //Variavel para passar os Bytes e montar o arquivo em novo diretorio
            int b = 0;
            //Loop responsável pelo envio Byte a Byte
            while((b = entrada.read()) != -1){
                
                saida.write(b);
                
            }
            //Não esqueça de fechar o envio assim que terminar
            saida.close();
            
        } catch (FileNotFoundException ex) {
            
            Logger.getLogger(MoverArquivo.class.getName()).log(Level.SEVERE, null, ex);
            
        } catch (IOException ex) {
            
            Logger.getLogger(MoverArquivo.class.getName()).log(Level.SEVERE, null, ex);
            
        }
        
        
        
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jbAbrir = new javax.swing.JButton();
        jlUrl = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jbAbrir.setText("Abrir");
        jbAbrir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbAbrirActionPerformed(evt);
            }
        });

        jlUrl.setText("URL");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addComponent(jbAbrir)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jlUrl)
                .addContainerGap(296, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(45, 45, 45)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbAbrir)
                    .addComponent(jlUrl))
                .addContainerGap(48, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        
    //Acao do botao para abrir o aquivo
    private void jbAbrirActionPerformed(java.awt.event.ActionEvent evt) {                                        
       
        //Criando um objeto do tipo JFileChooser
        JFileChooser janelaArquivo = new  JFileChooser();
        
        //Deixando a janela visivel
        janelaArquivo.showOpenDialog(this);
        //Passando para o método criado acima por parametro, já que ele precisa de um arquivo
        enviarArquivo(janelaArquivo.getSelectedFile());
        
    }                                       

    /**
     * @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 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(MoverArquivo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MoverArquivo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MoverArquivo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MoverArquivo.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 MoverArquivo().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jbAbrir;
    private javax.swing.JLabel jlUrl;
    // End of variables declaration                   
}

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

  • Forum Statistics

    • Total Topics
      149.6k
    • Total Posts
      646.2k
×
×
  • Create New...