Move file list between folders

3

I have a method that copies files from one folder to another, deleting the file then. It even caters me perfectly, but I would like to know if there is any way to do this without having to use InputStream and OutputStream , since I already had some problems with writing using these classes.

I saw that in Java 8 there are functions that facilitate file operations using the Files class. Is it possible to do this "move files" operation more simply and directly, using other methods, such as the Files class?

Follow the current code:

private static void copiarArquivos() throws IOException {

    File src = new File(".");
    String dstPath = "C:\java\";
    File dst;

    File[] files = src.listFiles();

    for (File f : files) {
        String fileName = f.getName();

        if (fileName.contains("File")) {

            dst = new File(dstPath + fileName);
            InputStream in = new FileInputStream(f);
            OutputStream out = new FileOutputStream(dst);
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
            f.delete();
        }
    }
}
    
asked by anonymous 30.11.2016 / 13:33

2 answers

4

The first major change to make is just move the file and not copy it, this is a huge waste of resource. You can just ask the operating system to rearrange your file system organization without even copying or even moving a byte of it, just change its metadata to indicate that it is in another folder. You do not need to know anything how this works, just know which method to call.

private static void copiarArquivos() throws IOException {
    File src = new File(".");
    String dstPath = "C:\java\";
    for (File f : src.listFiles()) {
        String fileName = f.getName();
        if (fileName.contains("File")) {
            Files.move(f.toPath(), Paths.get(dstPath, fileName), REPLACE_EXISTING);
        }
    }
}

Java 8 still allows streams ( examples ) and the code can become more declarative. I do not always like it, I think it's simple and understandable.

You can kill two variables, but I did.

    
30.11.2016 / 13:52
4

Just for curiosity in versions prior to 7.

Renaming:

import java.io.File;

public class Movendo {

  public static void main(String[] args) {
    try {
      File arquivo = new File("C:/pasta1/arquivo.txt");

      if (arquivo.renameTo(new File("C:/pastab/" + arquivo.getName()))) {
        System.out.println("Arquivo movido com sucesso!");
      } else {
        System.out.println("Falha ao mover arquivo!");
      }
    } catch (Exception e) {
      System.out.println("Falha ao mover arquivo!");
    }
  }
}
    
30.11.2016 / 14:30