[RESOLVIDO] Cópia e Renomeação de Arquivos

Olá, pessoal!

Não sou um expert em Java mas estou engatinhando e fazendo por onde para aprender esta linguagem.

Bem, estou desenvolvendo uma aplicação desktop relativamente simples, mas como ainda estou no começo, torna-se difícil.

A aplicação se comportará da seguinte forma:

Através de um jComboBox, o usuário selecionará uma filial e ao clicar em OK, e de acordo com a filial selecionada, um arquivo .ini correspondente a esta filial será copiado de um diretório para outro e renomeado para um determinado nome (ex.: arquivo.ini). O nome a ser renomeado após cópia para o destino será sempre o mesmo. O que muda é o nome do arquivo de origem.

Esta é minha classe principal:

[code]package pacs.selector;

public class PacsSelector {

public static void main(String[] args) {                             
    
      new JFramePacsSelector().setVisible(true);                             

}
}

[/code]

Esta é a minha classe com o jFrame e seu jComboBox, botão, etc:

[code]package pacs.selector;

import javax.swing.JComboBox;
import javax.swing.JOptionPane;

public class JFramePacsSelector extends javax.swing.JFrame {
public static final String pathIn = “C:\Teste”;
public static final String pathOut = “C:\Teste\Teste2”;
/**
* Creates new form JFramePacsSelector
*/
public JFramePacsSelector() {
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() {

    Painel = new javax.swing.JPanel();
    LabelSelecaoUnidade = new javax.swing.JLabel();
    ComboListaUnidades = new javax.swing.JComboBox();
    BotaoSair = new javax.swing.JButton();
    BotaoOK = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("Pacs Selector V. 1.0");
    setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
    setResizable(false);

    LabelSelecaoUnidade.setText("Selecione a unidade:");

    ComboListaUnidades.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "(1) Botafogo", "(107) Ilha", "(108) Caxias", "(109) Madureira", "(111) Soriano", "(112) Saens Pena", "(113) São Gonçalo", "(121) Niterói", "(123) Volta Redonda", "(130) Debret", "(134) Redentor", "(135) Meier - Dias da Cruz", "(137) Figueiredo Magalhães", "(139) Jardim Botânico", "(141) Vila da Penha", "(144) Recreio", "(155) Campo Grande", "(157) Icaraí", "(194) Barra Life" }));
    ComboListaUnidades.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            ComboListaUnidadesActionPerformed(evt);
        }
    });

    BotaoSair.setText("Sair");
    BotaoSair.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            BotaoSairActionPerformed(evt);
        }
    });

    BotaoOK.setText("OK");
    BotaoOK.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            BotaoOKActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout PainelLayout = new javax.swing.GroupLayout(Painel);
    Painel.setLayout(PainelLayout);
    PainelLayout.setHorizontalGroup(
        PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(PainelLayout.createSequentialGroup()
            .addGroup(PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(PainelLayout.createSequentialGroup()
                    .addGap(150, 150, 150)
                    .addComponent(BotaoSair))
                .addGroup(PainelLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(LabelSelecaoUnidade)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(ComboListaUnidades, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(55, 55, 55)
                    .addComponent(BotaoOK)))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    PainelLayout.setVerticalGroup(
        PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(PainelLayout.createSequentialGroup()
            .addContainerGap()
            .addGroup(PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(LabelSelecaoUnidade)
                .addComponent(ComboListaUnidades, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(BotaoOK))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
            .addComponent(BotaoSair)
            .addGap(19, 19, 19))
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(Painel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(Painel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );

    pack();
}// </editor-fold>                        

private void BotaoSairActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // Fecha a tela quando clica no botão sair
    System.exit(0);        
}                                         

private void ComboListaUnidadesActionPerformed(java.awt.event.ActionEvent evt) {                                                   
    //Obtém o item selecionado
    ComboListaUnidades.getSelectedItem();                
}                                                  

private void BotaoOKActionPerformed(java.awt.event.ActionEvent evt) {                                        
    //Converte o item selecionado para String
    String unidade = ComboListaUnidades.getSelectedItem().toString();
    if (ComboListaUnidades.getSelectedIndex()==0 ){
    JOptionPane.showMessageDialog(null, "A unidade escolhida foi: " + unidade);
    }
    else{
     JOptionPane.showMessageDialog(null, "A unidade não existe!");       
    }                 
}                                       

/**
 * @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(JFramePacsSelector.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(JFramePacsSelector.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(JFramePacsSelector.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(JFramePacsSelector.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 JFramePacsSelector().setVisible(true);
        }
    });
}
// Variables declaration - do not modify                     
private javax.swing.JButton BotaoOK;
private javax.swing.JButton BotaoSair;
private javax.swing.JComboBox ComboListaUnidades;
private javax.swing.JLabel LabelSelecaoUnidade;
private javax.swing.JPanel Painel;
// End of variables declaration                   

}
[/code]

O que fiz até o momento, foi o seguinte:

  1. De acordo com o item selecionado, é realizada uma conversão para String.

  2. Utilizei um if de acordo com a posição do item na jComboBox

Como ainda estou testando conforme o desenvolvimento, deixei apenas em teste o if exibindo a filial selecionada caso a mesma esteja na posição 0 e caso não esteja, dizendo que a filial não existe.

As dúvidas são as seguintes:

  1. A utilização do if é recomendada para este caso?
    A ideia de utilizar o if é: caso a posição seja 0 (ou 1, 2, 3, etc) ele busque o arquivo .ini (ex.: c:\filiais\filial1.ini) e copie para o diretório de origem renomeando para o nome que será sempre padrão (ex.: c:\programa\arquivo.ini).

  2. Como implementar a função de copiar o arquivo e renomeá-lo de acordo com a opção de filial escolhida?

Não sei se ficou confuso. Tentei explicar bem o que estou tentando. Caso haja alguma dúvida, eu explico melhor.

Desde já grato,

Consegui evoluir um pouco.

Achei no tópico http://www.guj.com.br/java/128689-copia-de-arquivo-via-java um método para copiar arquivos, disponibilizado pelo ViniGodoy.

Criei uma classe chamada Arquivos, ficando assim:

[code]package pacs.selector;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class Arquivos{

File source = new File ("C:\\Teste\\Imagem.jpg");
File destination = new File ("C:\\Teste\\Teste2\\Imagem.jpg");

    public static void copyFile(File source, File destination) throws IOException {
    if (destination.exists())
        destination.delete();

    FileChannel sourceChannel = null;
    FileChannel destinationChannel = null;

    try {
        sourceChannel = new FileInputStream(source).getChannel();
        destinationChannel = new FileOutputStream(destination).getChannel();
        sourceChannel.transferTo(0, sourceChannel.size(),
                destinationChannel);
    } finally {
        if (sourceChannel != null && sourceChannel.isOpen())
            sourceChannel.close();
        if (destinationChannel != null && destinationChannel.isOpen())
            destinationChannel.close();
   }

}
}
[/code]

Quando eu chamado este método após o IF na classe JFramePacsSelector, recebo o seguinte erro após execução do programa, seleção da filial e pressionando o botão OK:

run:
Exception in thread “AWT-EventQueue-0” java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: pacs.selector.Arquivos.copyFile
at pacs.selector.JFramePacsSelector.BotaoOKActionPerformed(JFramePacsSelector.java:121)
at pacs.selector.JFramePacsSelector.access$200(JFramePacsSelector.java:9)
at pacs.selector.JFramePacsSelector$3.actionPerformed(JFramePacsSelector.java:56)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:729)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:688)
at java.awt.EventQueue$3.run(EventQueue.java:686)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:702)
at java.awt.EventQueue$4.run(EventQueue.java:700)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:699)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
CONSTRUÍDO COM SUCESSO (tempo total: 9 segundos)

Está dando este erro, pois o método que você implementou faz exatamente isso.
Para chamar o método que você copiou do ViniGodoy, vc tem que chamar este método copyFile(File source, File destination), é o mesmo nome, porém com mais parâmetros. Isso é chamado de overload

EDIT: bom, vc editou o seu post, então agora não faz muito sentido no que te respondi. Acredito que vc tenha editado, porque vc entendeu o que estava acontecendo

[quote=igor_ks]Está dando este erro, pois o método que você implementou faz exatamente isso.
Para chamar o método que você copiou do ViniGodoy, vc tem que chamar este método copyFile(File source, File destination), é o mesmo nome, porém com mais parâmetros. Isso é chamado de overload

EDIT: bom, vc editou o seu post, então agora não faz muito sentido no que te respondi. Acredito que vc tenha editado, porque vc entendeu o que estava acontecendo[/quote]

Olá, Igor,

Eu havia editado antes da sua resposta pois ia colocar um outro trecho que estava funcionando. Como vi que você respondeu, retornei com o post anterior.

Chamei o método da seguinte forma: Arquivos.copyFile(File source, File destination); mas o NetBeans informa a seguinte mensagem:

cannot find symbol

symbol: variable File
location: class JFramePacsSelector

‘)’ expected

not a statement

‘;’ expecte…

Bom, vc não voltou seu post anterior, pois seu post anterior vc estava com 2 métodos, sendo um deles criado automaticamente pelo NetBeans, e vc estava chamando este ao invés do que você criou.

Este erro que vc postou por ultimo, não faz muito sentido para mim. Desconfio que vc tenha pego log errado, ou acabei me perdendo neste código que o netbeans gera mesmo. Isso é erro simples de compilação, veja a linha que sua IDE está apontando o erro e tente entender, é algo simples como uma falta de um fecha parenteses “)”

[quote]cannot find symbol

symbol: variable File
location: class JFramePacsSelector

‘)’ expected

not a statement

‘;’ expecte… [/quote]

Bem, como ainda estou no início da linguagem Java, achei o método retirado do outro tópico muito confuso para o meu entendimento.

Achei este outro método e já alterei os parâmetros:

public static void copy(File origem, File destino) throws IOException { String source = "C:/Teste/Imagem.jpg"; String destiny = "C:/Teste/Teste2/Imagem.jpg"; String destinoRenomear = "C:/Teste/Teste2/ImagemRenomeada.jpg"; File arquivoOrigem = new File(source); File arquivoCopiar = new File(destiny); File arquivoRenomeado = new File(destinoRenomear); Date date = new Date(); InputStream in = new FileInputStream(origem); OutputStream out = new FileOutputStream(destino); // Transferindo bytes de entrada para saída byte[] buffer = new byte[1024]; int lenght; while ((lenght= in.read(buffer)) > 0) { out.write(buffer, 0, lenght); } in.close(); out.close(); }

Ele está funcionando e o NetBeans não está reclamando.

A questão é:

Como posso implementar este método, de forma que, de acordo com a unidade selecionada, ele busque o arquivo em um determinado diretório (este arquivo terá o nome da filial, por exemplo), e o renomeie após a cópia já no diretório de destino?

Deixei este método dentro da minha classe contendo o JFrame. Está assim:

[code]package pacs.selector;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import javax.swing.JOptionPane;

public class JFramePacsSelector extends javax.swing.JFrame {
/**
* Creates new form JFramePacsSelector
*/
public JFramePacsSelector() {
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() {

    Painel = new javax.swing.JPanel();
    LabelSelecaoUnidade = new javax.swing.JLabel();
    ComboListaUnidades = new javax.swing.JComboBox();
    BotaoSair = new javax.swing.JButton();
    BotaoOK = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("Pacs Selector V. 1.0");
    setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
    setResizable(false);

    LabelSelecaoUnidade.setText("Selecione a unidade:");

    ComboListaUnidades.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "(1) Botafogo", "(107) Ilha", "(108) Caxias", "(109) Madureira", "(111) Soriano", "(112) Saens Pena", "(113) São Gonçalo", "(121) Niterói", "(123) Volta Redonda", "(130) Debret", "(134) Redentor", "(135) Meier - Dias da Cruz", "(137) Figueiredo Magalhães", "(139) Jardim Botânico", "(141) Vila da Penha", "(144) Recreio", "(155) Campo Grande", "(157) Icaraí", "(194) Barra Life" }));
    ComboListaUnidades.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            ComboListaUnidadesActionPerformed(evt);
        }
    });

    BotaoSair.setText("Sair");
    BotaoSair.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            BotaoSairActionPerformed(evt);
        }
    });

    BotaoOK.setText("OK");
    BotaoOK.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            BotaoOKActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout PainelLayout = new javax.swing.GroupLayout(Painel);
    Painel.setLayout(PainelLayout);
    PainelLayout.setHorizontalGroup(
        PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(PainelLayout.createSequentialGroup()
            .addGroup(PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(PainelLayout.createSequentialGroup()
                    .addGap(150, 150, 150)
                    .addComponent(BotaoSair))
                .addGroup(PainelLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(LabelSelecaoUnidade)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(ComboListaUnidades, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(55, 55, 55)
                    .addComponent(BotaoOK)))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    PainelLayout.setVerticalGroup(
        PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(PainelLayout.createSequentialGroup()
            .addContainerGap()
            .addGroup(PainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(LabelSelecaoUnidade)
                .addComponent(ComboListaUnidades, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(BotaoOK))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
            .addComponent(BotaoSair)
            .addGap(19, 19, 19))
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(Painel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(Painel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );

    pack();
}// </editor-fold>                        

private void BotaoSairActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // Fecha a tela quando clica no botão sair
    System.exit(0);        
}                                         

private void ComboListaUnidadesActionPerformed(java.awt.event.ActionEvent evt) {                                                   
    //Obtém o item selecionado
    ComboListaUnidades.getSelectedItem();                
    //ComboListaUnidades.getSelectedIndex();
}                                                  

private void BotaoOKActionPerformed(java.awt.event.ActionEvent evt) {                                        
    //Converte o item selecionado para String
    String unidade = ComboListaUnidades.getSelectedItem().toString();
    if (ComboListaUnidades.getSelectedIndex()==0 ){
    JOptionPane.showMessageDialog(null, "A unidade escolhida foi: " + unidade);                                                                   
    }
    if (ComboListaUnidades.getSelectedIndex()==1 ){
    JOptionPane.showMessageDialog(null, "A unidade escolhida foi: " + unidade);
    }
    if (ComboListaUnidades.getSelectedIndex()==2 ){
    JOptionPane.showMessageDialog(null, "A unidade escolhida foi: " + unidade);
    }
    if (ComboListaUnidades.getSelectedIndex()==3 ){
    JOptionPane.showMessageDialog(null, "A unidade escolhida foi: " + unidade);
    }
    if (ComboListaUnidades.getSelectedIndex()==4 ){
    JOptionPane.showMessageDialog(null, "A unidade escolhida foi: " + unidade);
    }
    if (ComboListaUnidades.getSelectedIndex()==5 ){
    JOptionPane.showMessageDialog(null, "A unidade escolhida foi: " + unidade);
    }
    if (ComboListaUnidades.getSelectedIndex()==6 ){
    JOptionPane.showMessageDialog(null, "A unidade escolhida foi: " + unidade);
    }
    if (ComboListaUnidades.getSelectedIndex()==7 ){
    JOptionPane.showMessageDialog(null, "A unidade escolhida foi: " + unidade);
    }
    if (ComboListaUnidades.getSelectedIndex()==8 ){
    JOptionPane.showMessageDialog(null, "A unidade escolhida foi: " + unidade);
    }
    if (ComboListaUnidades.getSelectedIndex()==9 ){
    JOptionPane.showMessageDialog(null, "A unidade escolhida foi: " + unidade);
    }
    if (ComboListaUnidades.getSelectedIndex()==10 ){
    JOptionPane.showMessageDialog(null, "A unidade escolhida foi: " + unidade);
    }
    if (ComboListaUnidades.getSelectedIndex()==11 ){
    JOptionPane.showMessageDialog(null, "A unidade escolhida foi: " + unidade);
    }
    if (ComboListaUnidades.getSelectedIndex()==12 ){
    JOptionPane.showMessageDialog(null, "A unidade escolhida foi: " + unidade);
    }
    if (ComboListaUnidades.getSelectedIndex()==13 ){
    JOptionPane.showMessageDialog(null, "A unidade escolhida foi: " + unidade);
    }
    if (ComboListaUnidades.getSelectedIndex()==14 ){
    JOptionPane.showMessageDialog(null, "A unidade escolhida foi: " + unidade);
    }
    if (ComboListaUnidades.getSelectedIndex()==15 ){
    JOptionPane.showMessageDialog(null, "A unidade escolhida foi: " + unidade);
    }
    if (ComboListaUnidades.getSelectedIndex()==16 ){
    JOptionPane.showMessageDialog(null, "A unidade escolhida foi: " + unidade);
    }
    if (ComboListaUnidades.getSelectedIndex()==17 ){
    JOptionPane.showMessageDialog(null, "A unidade escolhida foi: " + unidade);
    }
    if (ComboListaUnidades.getSelectedIndex()==18 ){
    JOptionPane.showMessageDialog(null, "A unidade escolhida foi: " + unidade);
    }    
}                                       

/**
 * @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(JFramePacsSelector.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(JFramePacsSelector.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(JFramePacsSelector.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(JFramePacsSelector.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 JFramePacsSelector().setVisible(true);
        }
    });                            
}
public static void copy(File origem, File destino) throws IOException {
    String source = "C:/Teste/Imagem.jpg";
    String destiny = "C:/Teste/Teste2/Imagem.jpg";        
    String destinoRenomear = "C:/Teste/Teste2/ImagemRenomeada.jpg";      
    File arquivoOrigem    = new File(source);
    File arquivoCopiar    = new File(destiny);         
    File arquivoRenomeado = new File(destinoRenomear);                    
    Date date = new Date();
    InputStream in = new FileInputStream(origem);
    OutputStream out = new FileOutputStream(destino);           
    // Transferindo bytes de entrada para saída
    byte[] buffer = new byte[1024];
    int lenght;
    while ((lenght= in.read(buffer)) > 0) {
        out.write(buffer, 0, lenght);
    }
    in.close();
    out.close();
    Long time = new Date().getTime() - date.getTime();
    System.out.println("Saiu copy"+time);       
}
// Variables declaration - do not modify                     
private javax.swing.JButton BotaoOK;
private javax.swing.JButton BotaoSair;
private javax.swing.JComboBox ComboListaUnidades;
private javax.swing.JLabel LabelSelecaoUnidade;
private javax.swing.JPanel Painel;
// End of variables declaration                   

}[/code]

Ainda estou tentando implementar o método e está complicado! :frowning:

Voltei a usar o método do Vini. Coloquei em uma classe chamada ArquivosTest, ficando assim:

[code]package pacs.selector;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class ArquivosTest {

//File source = new File ("C:\\Teste\\Imagem.jpg");
//File destination = new File ("C:\\Teste\\Teste2\\Imagem.jpg");

File s = new File ("C:\\Teste\\Imagem.jpg");
File d = new File ("C:\\Teste\\Teste2\\Imagem.jpg");

    public static void copyFile(File source, File destination) throws IOException {
    if (destination.exists())
        destination.delete();

    FileChannel sourceChannel = null;
    FileChannel destinationChannel = null;

    try {
        sourceChannel = new FileInputStream(source).getChannel();
        destinationChannel = new FileOutputStream(destination).getChannel();
        sourceChannel.transferTo(0, sourceChannel.size(),
                destinationChannel);
    } finally {
        if (sourceChannel != null && sourceChannel.isOpen())
            sourceChannel.close();
        if (destinationChannel != null && destinationChannel.isOpen())
            destinationChannel.close();
   }

}
}
[/code]

A questão é:

Como devo chamar este método na minha classe com o JFrame?

Montei a chamada da seguinte forma:

ArquivosTest botafogo = new ArquivosTest(); botafogo.s = new File ("C:\\Teste\\Imagem.jpg"); botafogo.d = new File ("C:\\Teste\\Teste2\\Imagem.jpg"); try { ArquivosTest.copyFile(null, null); } catch (IOException ex) { Logger.getLogger(JFramePacsSelector.class.getName()).log(Level.SEVERE, null, ex); }

Quando eu executo a aplicação, seleciono a filial e clico em OK, exibe os erros abaixo:

run:
Exception in thread “AWT-EventQueue-0” java.lang.NullPointerException
at pacs.selector.ArquivosTest.copyFile(ArquivosTest.java:18)
at pacs.selector.JFramePacsSelector.BotaoOKActionPerformed(JFramePacsSelector.java:131)
at pacs.selector.JFramePacsSelector.access$200(JFramePacsSelector.java:14)
at pacs.selector.JFramePacsSelector$3.actionPerformed(JFramePacsSelector.java:61)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:729)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:688)
at java.awt.EventQueue$3.run(EventQueue.java:686)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:702)
at java.awt.EventQueue$4.run(EventQueue.java:700)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:699)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
CONSTRUÍDO COM SUCESSO (tempo total: 10 segundos)

Obs.: O NetBeans não está exibindo erros e alerta algum.

Alguém poderia editar esse código do meu JFrame para que eu possa entender aonde estou errando?

Grato!

seu método copyFile, está esperando dois File como parâmetro, ou seja, um do arquivo original, e outro de onde vc quer copiar o arquivo.

este código aqui:

File s = new File ("C:\\Teste\\Imagem.jpg"); File d = new File ("C:\\Teste\\Teste2\\Imagem.jpg");

não está fazendo nada, além de ocupar memória. Eles não estão sendo usados em nenhum lugar.

Na sua chamada do métódo, vc deve passar esses dois arquivos

(Não vou dar o código pronto pra você, mas está quase certo. Entenda a lógica, siga os passos, que entenderá o que está acontecendo. Depure o código se já sabe fazer isso)

Igor,

Consegui resolver o problema.

O primeiro erro que estava gerando era o “resto” de algumas tentativas com outros códigos na classe do JFrame que sobraram no final dos demais códigos e eu me esqueci de comentar para anular o código.

Estava desde ontem quebrando a cabeça e agora entendi a lógica da coisa. O método do Vini já estava pronto e eu não estava entendendo que deveria declarar as variáveis source e destination na classe do JFrame e que já existiam na classe que eu criei com o método do Vini.

Agora está funcionando certinho.

Preciso apenas adaptar a renomeação dos arquivos ao chegar no diretório de destino, mas creio que a parte mais complicada já foi.

Desde já, muito grato!

Vlw!

Nota: na verdade nem preciso criar uma função que renomeie o arquivo. Dentro da variável destination já posso colocar o nome que eu quero para o arquivo. :wink:

Hoje em dia, para copiar arquivos usando o Java 7, é mais fácil usar o Files.copy.

[quote=ViniGodoy]Hoje em dia, para copiar arquivos usando o Java 7, é mais fácil usar o Files.copy.

http://blog.caelum.com.br/evolucao-do-java-io-ao-ni/[/quote]

Obrigado, Vini!