[英]How to store file list from console to directory using java?
here the code found in this forum and i need to stored the 10 recent files into another foldre, i tried to modify but it's not working as well as i wanted. 在此论坛中找到的代码,我需要将10个最近的文件存储到另一个foldre中,我尝试进行修改,但效果不如我所愿。
any help , Thank you 任何帮助,谢谢
code 码
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)
}
}
}
I think you have 2 problems: 我认为您有2个问题:
renameTo(..)
) renameTo(..)
) I have cleaned up your code a bit and removed the extra loop. 我已经整理了一下代码,并删除了多余的循环。 Also note that it is till moving the files not copying the files (I add a copy method below):
还要注意的是,直到不能 移动 的文件复制 (我在下面添加复制方法) 的文件 :
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()));
}
This method is copying files: 此方法正在复制文件:
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.