Copiar imagem em java

Boa Tarde a Todos

Estou fazendo um programa em java o qual tem cadastro de funcionario.
E neste cadastro eu uso um botão para carregar a imagem. segue o comando abaixo.

 private void btnAdicionarFotoActionPerformed(java.awt.event.ActionEvent evt) {                                                 
        JFileChooser arquivo = new JFileChooser();
        arquivo.setDialogTitle("Selecione a Imagem");
        arquivo.setFileSelectionMode(JFileChooser.FILES_ONLY);
        FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & PNG Images", new String[]{"jpg", "png"});
        arquivo.setFileFilter(filter);
        arquivo.setAcceptAllFileFilterUsed(false);
        arquivo.setMultiSelectionEnabled(false);
        File file = new File("user.dir");
        int option = arquivo.showOpenDialog(this);
//          PessoasDAO pDao = new PessoasDAO();  
        if (option == JFileChooser.APPROVE_OPTION) {
            String caminhoArquivo = "";
            caminhoArquivo = arquivo.getSelectedFile().getAbsolutePath();// carrega o caminho da imagem 
            file = arquivo.getSelectedFile();
            String nomeArquivo = file.getName();
            int e = nomeArquivo.lastIndexOf(".");
            String extensao = nomeArquivo.substring(e);
            Image image = null;
            try {
                image = ImageIO.read(file);
            } catch (IOException ex) {
                Logger.getLogger(CadastroFuncionario.class.getName()).log(Level.SEVERE, null, ex);
            }
            if (extensao.equals(".jpg") || extensao.equals(".JPG")) {
                lblFotoFuncionario1.setIcon(new ImageIcon(arquivo.getSelectedFile().getAbsolutePath()));
                txtCaminhoImagem.setText(caminhoArquivo);// seta o caminho em uma jTextFild
                lblFotoFuncionario1.setIcon(new ImageIcon(image.getScaledInstance(lblFotoFuncionario1.getWidth(), lblFotoFuncionario1.getHeight(), Image.SCALE_DEFAULT)));

            } else {
                JOptionPane.showMessageDialog(null, "Arquivo não suportado", "Erro", JOptionPane.ERROR_MESSAGE);
            }
        }

    } 

este comando carrega a imagem bunitinho em uma jLabel Redimensionada para o tamanho da jLabel certinho.
porem te o perigo do usuaria excluir a foto original sendo assim dar erro quando for abrir o programa de novo.
eu fiz em VB.NET algo que antes de eu salvar no banco o caminho da imagem eu copio a imagem para uma pasta o projeto e assim depois eu salvo no banco, mas em java eu nem imagino como faz isso.
Sera que alguem poderia me ajudar ficarei grato.
fico on line no skype quase 24 horas

guimarques1987etc

O seu código já está quase bom - você tem o nome do arquivo de origem:

            file = arquivo.getSelectedFile();  

Agora você precisa de criar o nome do arquivo de destino, onde você vai fazer o backup, e de uma rotina que copie os arquivos.

Se estiver usando o Java 7, tem prontinho uma coisa que copia arquivos do jeito mais rápido possível:

http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#copy(java.nio.file.Path,%20java.nio.file.Path,%20java.nio.file.CopyOption...)

Se estiver usando uma versão anterior do Java, basta procurar aqui no GUJ. Muita gente já postou aqui rotinas que copiam arquivos

public static Path copy(Path source,
Path target,
CopyOption… options)
throws IOException
Copy a file to a target file.
This method copies a file to the target file with the options parameter specifying how the copy is performed. By default, the copy fails if the target file already exists or is a symbolic link, except if the source and target are the same file, in which case the method completes without copying the file. File attributes are not required to be copied to the target file. If symbolic links are supported, and the file is a symbolic link, then the final target of the link is copied. If the file is a directory then it creates an empty directory in the target location (entries in the directory are not copied). This method can be used with the walkFileTree method to copy a directory and all entries in the directory, or an entire file-tree where required.

The options parameter may include any of the following:

Option Description
REPLACE_EXISTING If the target file exists, then the target file is replaced if it is not a non-empty directory. If the target file exists and is a symbolic link, then the symbolic link itself, not the target of the link, is replaced.
COPY_ATTRIBUTES Attempts to copy the file attributes associated with this file to the target file. The exact file attributes that are copied is platform and file system dependent and therefore unspecified. Minimally, the last-modified-time is copied to the target file if supported by both the source and target file store. Copying of file timestamps may result in precision loss.
NOFOLLOW_LINKS Symbolic links are not followed. If the file is a symbolic link, then the symbolic link itself, not the target of the link, is copied. It is implementation specific if file attributes can be copied to the new link. In other words, the COPY_ATTRIBUTES option may be ignored when copying a symbolic link.
An implementation of this interface may support additional implementation specific options.

Copying a file is not an atomic operation. If an IOException is thrown then it possible that the target file is incomplete or some of its file attributes have not been copied from the source file. When the REPLACE_EXISTING option is specified and the target file exists, then the target file is replaced. The check for the existence of the file and the creation of the new file may not be atomic with respect to other file system activities.

Usage Example: Suppose we want to copy a file into a directory, giving it the same file name as the source file:

 Path source = ...
 Path newdir = ...
 Files.copy(source, newdir.resolve(source.getFileName());

Parameters:
source - the path to the file to copy
target - the path to the target file (may be associated with a different provider to the source path)
options - options specifying how the copy should be done
Returns:
the path to the target file
Throws:
UnsupportedOperationException - if the array contains a copy option that is not supported
FileAlreadyExistsException - if the target file exists but cannot be replaced because the REPLACE_EXISTING option is not specified (optional specific exception)
DirectoryNotEmptyException - the REPLACE_EXISTING option is specified but the file cannot be replaced because it is a non-empty directory (optional specific exception)
IOException - if an I/O error occurs
SecurityException - In the case of the default provider, and a security manager is installed, the checkRead method is invoked to check read access to the source file, the checkWrite is invoked to check write access to the target file. If a symbolic link is copied the security manager is invoked to check LinkPermission(“symbolic”).

descupe mas não consegui intender este metodo.

Se estiver com problemas e o Google Translator não conseguir lhe ajudar, então procure aqui no GUJ porque acho que há pelo menos uns 10 tópicos que têm programas prontos para copiar arquivos.

Procure no Google como:

cópia arquivos site:www.guj.com.br