簡體   English   中英

如何使用Java將文件列表從控制台存儲到目錄?

[英]How to store file list from console to directory using java?

在此論壇中找到的代碼,我需要將10個最近的文件存儲到另一個foldre中,我嘗試進行修改,但效果不如我所願。

任何幫助,謝謝

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)


            }
        }
    } 

我認為您有2個問題:

  • 您想將文件存儲到另一個目錄,代碼正在移動文件( renameTo(..)
  • 您正在運行“ move-loop”的循環中,該循環在所有文件上運行(試圖將它們移動多次)

我已經整理了一下代碼,並刪除了多余的循環。 還要注意的是,直到不能 移動 的文件復制 (我在下面添加復制方法) 的文件

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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM