2011-02-16 46 views
1

这里的代码在这个论坛发现,我需要存储10个最近的文件到另一个折叠,我试图修改,但它不工作,以及我想要的。如何使用java将文件列表从控制台存储到目录?

任何帮助,谢谢

代码

import java.io.File; 
import java.util.Arrays; 
import java.util.Comparator; 
import java.io.*; 
import java.text.*; 
import java.util.*; 




    public class Newest 
    { 
     public static void main(String[] args) 
     { 
      File dir = new File("c:\\File"); 
      File[] files = dir.listFiles(); 
      Arrays.sort(files, new Comparator<File>() 
      { 
       public int compare(File f1, File f2) 
       { 
        return Long.valueOf(f2.lastModified()).compareTo 
          (
          f1.lastModified()); 
       } 
      }); 
      //System.out.println(Arrays.asList(files)); 
      for(int i=0, length=Math.min(files.length, 12); i<length; i++) { 
     System.out.println(files[i]); 


    for (File f : files) { 
      System.out.println(f.getName() + " " + sdf.format(new Date(f.lastModified()))); 
      File dir = new File("c://Target"); 
      boolean success = f.renameTo(new File(dir,f.getName())); 
      if (!success) 


      } 
     } 
    } 

回答

1

我觉得你有2个问题:

  • 要将文件存储到另一个目录,代码正在移动的文件 (renameTo(..)
  • 您正在循环中运行“移动循环”,该循环在所有文件上运行(你想对他们多次移动)

我已经清理你的代码了一下,去除多余的循环。还要注意的是,直到 移动文件复制文件(我在下面添加复制方法):

public static void main(String[] args) 
{ 
    String source = "c:/File"; 
    String target = "c:/Target"; 

    // get the files in the source directory and sort it 
    File sourceDir = new File(source); 
    File[] files = sourceDir.listFiles(); 
    Arrays.sort(files, new Comparator<File>() { 
     public int compare(File f1, File f2) { 
      return (int) (f1.lastModified() - f2.lastModified()); 
     } 
    }); 

    // create the target directory 
    File targetDir = new File(target); 
    targetDir.mkdirs(); 

    // copy the files 
    for(int i=0, length=Math.min(files.length, 10); i<length; i++) 
     files[i].renameTo(new File(targetDir, files[i].getName())); 
} 

这种方法是将文件复制:

private void copyFile(File from, File to) throws IOException, 
     FileNotFoundException { 

    FileChannel sc = null; 
    FileChannel dc = null; 

    try { 
     to.createNewFile(); 

     sc = new FileInputStream(from).getChannel(); 
     dc = new FileOutputStream(to).getChannel(); 

     long pos = 0; 
     long total = sc.size(); 
     while (pos < total) 
      pos += dc.transferFrom(sc, pos, total - pos); 

    } finally { 
     if (sc != null) 
      sc.close(); 
     if (dc != null) 
      dc.close(); 
    } 
} 
+0

非常感谢您的帮助 – user618111 2011-02-16 14:52:29

相关问题