问题描述
该目录有n个文件.我正在创建类,它将使用java arraylist从目录中按大小对文件进行排序.
The directory has n number of files.I am creating class, it will sort files by size from directory using java arraylist.
我可以读取文件名和大小.但是如何按大小对文件排序?
I can read the file name and size. but how to sort the files by size?
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
public class SortingFiles
{
public static void main(String[] args)
{
File dir=null;
File[] paths;
final ArrayList<String> al= new ArrayList<String>();
try{
// create new file object
dir = new File("D:\\New folder\\New");
// array of files and directory
paths = dir.listFiles();
ArrayList<File> fileList = new ArrayList<File>();
for(File file:paths)
{
// prints filename and directory name
System.out.println(file.getName()+" - " +file.length() );
al.add(file.getName());
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
我试图按大小对文件进行排序
i have tried to sort the file by size
for(int i=1; i<al.size(); i++)
{
System.out.println("\n Aftr : " +al.get(i) );
}
但是它不起作用..任何人都可以帮助我..我正在尝试不使用"import org.apache.commons.io.FileUtils;".那该怎么办?
But it is not working.. Any one can help me..I am trying without "import org.apache.commons.io.FileUtils;". So what to do ?
推荐答案
您必须创建一个 Map< String,Long>
并使用 filename
注册每个文件作为键,文件大小
作为值.最后,使用自然顺序,按值对 Map
进行排序,例如:
You have to create a Map<String, Long>
and register each file by using the filename
as key and the filesize
as value.Finally, sort the Map
by value using natural order, e.g:
List<Path> paths = Files.walk(Paths.get(folder))
.filter(Files::isRegularFile)
.sorted((Path a, Path b) -> a.toFile().length() > b.toFile().length() ? 1 : -1)
.collect(Collectors.toList());
这篇关于使用Java数组列表按大小对目录中的文件进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!