Copiar archivo en Java y reemplazar destino existente


Estoy tratando de copiar un archivo con java.nio.file.Archivos como este:

Files.copy(cfgFilePath, strTarget, StandardCopyOption.REPLACE_EXISTING);

El problema es que Eclipse dice "El método copy(Path, Path, CopyOption...) en el tipo Files no es aplicable para los argumentos (File, String, StandardCopyOption) "

Estoy usando Eclipse y Java 7 en Win7 x64. Mi proyecto está configurado para usar compatibilidad con Java 1.6.

¿Hay una solución a esto o tengo que crear algo como esto como una solución alternativa:

File temp = new File(target);

if(temp.exists())
  temp.delete();

Gracias.

Author: commander_keen, 2013-06-18

3 answers

Como complemento a la respuesta de @asilias:

Si usa Java 7, suelte File por completo. Lo que quieres es Path en su lugar.

Y para obtener un objeto Path que coincida con una ruta en su sistema de archivos, haga lo siguiente:

Paths.get("path/to/file"); // argument may also be absolute

Acostúmbrate muy rápido. Tenga en cuenta que si todavía utiliza API que requieren File, Path tiene un método .toFile().

Tenga en cuenta que si se encuentra en el desafortunado caso de usar una API que devuelve File objetos, siempre puede hacer:

theFileObject.toPath()

Pero en código de los suyos, use Path. Sistemática. Sin pensarlo dos veces.

EDITAR Copiar un archivo a otro usando 1.6 usando NIO se puede hacer como tal; tenga en cuenta que la clase Closer está inspirada por Guava :

public final class Closer
    implements Closeable
{
    private final List<Closeable> closeables = new ArrayList<Closeable>();

    // @Nullable is a JSR 305 annotation
    public <T extends Closeable> T add(@Nullable final T closeable)
    {
        closeables.add(closeable);
        return closeable;
    }

    public void closeQuietly()
    {
        try {
            close();
        } catch (IOException ignored) {
        }
    }

    @Override
    public void close()
        throws IOException
    {
        IOException toThrow = null;
        final List<Closeable> l = new ArrayList<Closeable>(closeables);
        Collections.reverse(l);

        for (final Closeable closeable: l) {
            if (closeable == null)
                continue;
            try {
                closeable.close();
            } catch (IOException e) {
                if (toThrow == null)
                    toThrow = e;
            }
        }

        if (toThrow != null)
            throw toThrow;
    }
}

// Copy one file to another using NIO
public static void doCopy(final File source, final File destination)
    throws IOException
{
    final Closer closer = new Closer();
    final RandomAccessFile src, dst;
    final FileChannel in, out;

    try {
        src = closer.add(new RandomAccessFile(source.getCanonicalFile(), "r");
        dst = closer.add(new RandomAccessFile(destination.getCanonicalFile(), "rw");
        in = closer.add(src.getChannel());
        out = closer.add(dst.getChannel());
        in.transferTo(0L, in.size(), out);
        out.force(false);
    } finally {
        closer.close();
    }
}
 8
Author: fge,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-20 12:52:27

Debe pasar Path argumentos como se explica en el mensaje de error:

Path from = cfgFilePath.toPath(); //convert from File to Path
Path to = Paths.get(strTarget); //convert from String to Path
Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING);

Que asume que su strTarget es una ruta válida.

 73
Author: assylias,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-18 13:02:50

StrTarget es un objeto" String "y no un objeto" Path "

 1
Author: vincentcjl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-18 13:03:52