copy files from one folder to another

1

I have the following program:

public static void main(String args[]) { 

                File origen = new File("C:\Users\Montse\Documents\NetBeansProjects\Copiar2\hola.txt");
                File destino = new File("C:\Users\Montse\Documents\NetBeansProjects\Copiar2\backupVisibles\hola.txt");

                try {
                        InputStream in = new FileInputStream(origen);
                        OutputStream out = new FileOutputStream(destino);

                        byte[] buf = new byte[1024];
                        int len;

                        while ((len = in.read(buf)) > 0) {
                                out.write(buf, 0, len);
                        }

                        in.close();
                        out.close();
                } catch (IOException ioe){
                        ioe.printStackTrace();
                }


        }

I can not see how to get the following:

I need to Argument [0] the argument of the current directory.

that is: String sDirectory="C: \ Users \ Montse \ Documents \ NetBeansProjects \ Copy2"; File f = new File (sDirectory);

and copy the file that I put in the parameter args [1] for example the file hello.txt

The most I have achieved is this program that basically what it does is copy a file from one folder to another, but I do not get what I really need ..: (

thanks!

PS: I add text because I think I have not explained myself completely well.

That is, with the first ARGS [0] I need you to put the current directory. In the second ARGS [1] I need that X file for example the file hello.txt (that is to say I will put it in the parameters that I choose ..)

And that file will be saved in the folder that I want.

    
asked by Montse Mkd 27.02.2017 в 19:01
source

6 answers

1

I enclose a possible solution to your doubt

public static void main(String[] args) {
try {           
    if (args.length != 2) {
        System.out.println("Error el número de parametros debe de ser tres <Directorio Origen> <Fichero>");
        System.exit(-1);
    }

    //
    String pathOrigen = args[0];
    String fichero = args[1];
    String pathDestino = pathOrigen + "backup\"; // Define aqui tu directorio destino
    File ficheroCopiar = new File(pathOrigen, fichero);
    File ficheroDestino = new File(pathDestino, fichero);
    if (ficheroCopiar.exists()) {
        Files.copy(Paths.get(ficheroCopiar.getAbsolutePath()), Paths.get(ficheroDestino.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING);
    } else {
        System.out.println("El fichero "+fichero+" no existe en el directorio "+pathOrigen);
    }

} catch (Exception e) {
    e.printStackTrace();
}

}

    
answered by 08.11.2017 / 10:30
source
2

Here you will find how to move and copy a file

The class java.nio.file.Files , implements a series of static methods for file handling operations (files), among which is the move() method.

Using this method, we can write a function that moves a file from one directory to another. The move() method receives a CopyOptions argument, with which we can specify that it overwrites the destination file if it already existed.

package mx.com.softmolina;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

/**
 *
 * @author SoftMolina
 */
public class MoverArchivoMove {

    public static void main(String[] args) {

        Path origenPath = FileSystems.getDefault().getPath("C:\carpeta1\ejemplo1.txt");
        Path destinoPath = FileSystems.getDefault().getPath("C:\carpeta2\ejemplo1.txt");

        try {
            Files.move(origenPath, destinoPath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            System.err.println(e);
        }

    }

}

Copy a file to Java

The class java.nio.file.Files , implements a series of static methods for file handling operations (files), among which is the copy() method.

Using this method, we can write a function that copies a file elsewhere. The copy() method receives a CopyOptions argument, with which we can specify that it overwrites the destination file if it already existed.

    package mx.com.softmolina;

    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.nio.file.StandardCopyOption;
    import java.util.logging.Level;
    import java.util.logging.Logger;

    /**
     *
     * @author SoftMolina
     */
    public class CopiarArchivo {

        static final Logger LOGGER = Logger.getAnonymousLogger();

        public CopiarArchivo(String origenArchivo, String destinoArchivo) {
            try {
                Path origenPath = Paths.get(origenArchivo);
                Path destinoPath = Paths.get(destinoArchivo);
                //sobreescribir el fichero de destino si existe y lo copia
                Files.copy(origenPath, destinoPath, StandardCopyOption.REPLACE_EXISTING);
            } catch (FileNotFoundException ex) {
                LOGGER.log(Level.SEVERE, ex.getMessage());
            } catch (IOException ex) {
                LOGGER.log(Level.SEVERE, ex.getMessage());
            }
        }

       public static void main(String args[]) {
        if(args.length == 2)
            new copiarArchivo(args[0], args[1]);
        else
            System.out.println("Debe ingresar dos parametros");
       }

    }

Or I found this example: Here

import java.io.*;

    public class FileCopy {
        public FileCopy(String sourceFile, String destinationFile) {
            System.out.println("Desde: " + sourceFile);
            System.out.println("Hacia: " + destinationFile);

            try {
                File inFile = new File(sourceFile);
                File outFile = new File(destinationFile);

                FileInputStream in = new FileInputStream(inFile);
                FileOutputStream out = new FileOutputStream(outFile);

                int c;
                while( (c = in.read() ) != -1)
                    out.write(c);

                in.close();
                out.close();
            } catch(IOException e) {
                System.err.println("Hubo un error de entrada/salida!!!");
            }
        }

        public static void main(String args[]) {
            if(args.length == 2)
                new FileCopy(args[0], args[1]);
            else
                System.out.println("Debe ingresar dos parametros");
        }
    }
    
answered by 27.02.2017 в 21:15
1

If you create a jar executable of your program you can call it from the console simply as:

java -jar MiApp.jar ruta/a/fuente ruta/a/destino

That will call your method main with the arguments:

arg[0]="ruta/a/fuente";
arg[1]="ruta/a/destino";

and you can change your code to work with that instead of the constants.

    
answered by 27.02.2017 в 19:34
1

File has a constructor just for you. One parameter for the directory and another for the file.

Substitute:

File origen = new File("C:\Users\Montse\Documents\NetBeansProjects\Copiar2\hola.txt");

by:

File origen = new File(args[0], args[1]);

And leave the rest the same. Now origen refers to the file indicated in args[1] that is in the directory indicated in args[0] .

So that the destination file would be fixed. The one you have put in the program. If you want to be one chosen by parameters when calling the program you can use the same technique.

    
answered by 27.02.2017 в 23:10
0

args would be defined as a String array:

String args[] = {"C:\Users\Montse\Documents\NetBeansProjects\Copiar2\hola.txt","Bohra","C:\Users\Montse\Documents\NetBeansProjects\Copiar2\backupVisibles\hola.txt"};

You would call main() in this way:

  MyClass.main(args[]);

and within main() you would get the values in this way:

  File origen = new File(args[0]);
  File destino = new File(args[1]);
    
answered by 27.02.2017 в 19:27
0

Having my friend there is my proposal.

public static void main(String args[]) {

    if(args.length == 2){

      File origen = new File(args[0] + "\" + args[1]);

      //Ruta que tu elijas [no dinámico]
      File destino = new File("C:\Users\Montse\Documents\NetBeansProjects\Copiar2\backupVisibles\hola.txt");

      try {
              InputStream in = new FileInputStream(origen);
              OutputStream out = new FileOutputStream(destino);

              byte[] buf = new byte[1024];
              int len;

              while ((len = in.read(buf)) > 0) {
                      out.write(buf, 0, len);
              }

              in.close();
              out.close();
      } catch (IOException ioe){
              ioe.printStackTrace();
      }
    }

}
  

Use

//Ruta raiz 
String pathDirectorio = "C:\Users\Montse\Documents\NetBeansProjects\Copiar2";
//Nombre del archivo
String file = "texto.txt"


String[] args = {pathDirectorio, file};
//Llama a su clase método main
MiClase.main(args);

I hope my dear goodbye will help you.

    
answered by 19.09.2017 в 07:58