Mover Arquivos

2 respostas
V

Boa Tarde Galera !!!!

Estou tentando mover arquivos txt de um diretório para o outro, eu só consigo mover 1 único arquivo, eu queria ser capaz de abrir uma pasta e ter um filter ou copiar todo o seu conteúdo para a outra pasta.

O código que tenho é este:

package javaapplication8;

import java.io.File;
import java.util.TimerTask;

public class MyTimerTask extends TimerTask {
public void run() {
//System.out.println("Realizando algo");


 // arquivo a ser movido
    
    
        File arquivo = new File("c:\*.txt");
    
        // diretorio de destino
        File dir = new File("c:\mover");
    
        // move o arquivo para o novo diretorio
        boolean ok = arquivo.renameTo(new File(dir, arquivo.getName()));
        if(ok){
            System.out.println("Arquivo foi movido com sucesso");
        }
        else{
            System.out.println("Nao foi possivel mover o arquivo");
        }


}
}

Se alguem souber como me ajudar eu agradeço.

Desde já Muito Obrigado !!!!!!!!

2 Respostas

rodrigo.bossini

Esse tutorial ensina como fazer isso copiando os arquivos um a um. Talvez você consiga algo mais interessante com as classes FileChannel. Ou quem sabe com o apache commons IO. Vale a pena pesquisar.

V

Obrigado pela ajuda.

Eu usei o exemplo que vc me enviou eu fiz algumas alterações.

Na classe a seguir, quando ela tinha o main, funcionava perfeitamente, ai eu inclui o Timer parou de excluir os arquivos que ja foram copiados.

package javaapplication8;

import java.io.*;
import java.util.List;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;

  public class CopyDirectory extends TimerTask{
 public void run() {
  
 
 
   CopyDirectory cd = new CopyDirectory();
    BufferedReader in = new BufferedReader
                        (new InputStreamReader(System.in));
//    System.out.println("Enter the source directory or file name : ");
//
//      String source = in.readLine();
    
    String source = "c:\arq";

    File src = new File(source);
 
//    System.out.println("Enter the destination directory or file name : ");
//    String destination = in.readLine();

    String destination = "c:\mover";
            
      File dst = new File(destination); 
        try {

            cd.copyDirectory(src, dst);
        } catch (IOException ex) {
            Logger.getLogger(CopyDirectory.class.getName()).log(Level.SEVERE, null, ex);
        }

  }
  

  public void copyDirectory(File srcPath, File dstPath)
                               throws IOException{
  
  if (srcPath.isDirectory()){

      
//    Criar Diretório
      
      if (!dstPath.exists()){

        dstPath.mkdir();
 
     }

 
     String files[] = srcPath.list();
  
    for(int i = 0; i < files.length; i++){
        
//        srcPath.renameTo(dstPath);
//         boolean ok = srcPath.renameTo(new File(dstPath, srcPath.getName()));
//         if (ok){
//         System.out.println("ccc");
//         
//         }
        copyDirectory(new File(srcPath, files[i]), 
                     new File(dstPath, files[i]));
                         
               srcPath.deleteOnExit();

      }

    }
 
   else{
 
      if(!srcPath.exists()){

        System.out.println("File or directory does not exist.");
 
       System.exit(0);

      }
      
else
 
      {
          
          
 
       InputStream in = new FileInputStream(srcPath);
       OutputStream out = new FileOutputStream(dstPath); 
                     // Transfer bytes from in to out
            byte[] buf = new byte[1024];
 
              int len;
 
           while ((len = in.read(buf)) > 0) {
 
          out.write(buf, 0, len);

        }
 
       in.close();
 
           out.close();
              srcPath.deleteOnExit();

      }
 

   }
   
 System.out.println("Directory copied.");
 

  }
 

}

Segue a classe do Timer

package javaapplication8;

import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Timer;

public class MyTimer {

public MyTimer() {
Timer timer = new Timer(true);
Date hoje = new GregorianCalendar().getTime();
timer.schedule(new CopyDirectory(), hoje, 5000);  //3 segundos
}

public static void main(String[] args) {
new MyTimer();
while(true){
        }
       }
}

Se souber como me ajudar eu agradeço.

Desde ja fico grato pela ajuda

Criado 6 de junho de 2010
Ultima resposta 7 de jun. de 2010
Respostas 2
Participantes 2