`

Java File.listFiles order

 
阅读更多

Java File.listFiles order

 

The documentation for the Java JDK specifically mentions that the files returns can be in any order.

There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order.

The actual ordering of the files varies from platform to platform, and often is a result of the physical order of the files in the directory structure. On Solaris, this order will often reverse if you copy a folder. Generally this is not noticeable, as most tools sort the files in some order before returning them to the user.

Unfortunately, file ordering is important when the files are added to a classloader. As files at the front of the classpath are searched before files at the end, if you have two different classes in your classpath, the order may not be stable. This isn't a problem if you specify the full classpath when you launch Java, but if you load files dynamically, like JBoss does, then your behavior is subject to change. The following is a test case which may pass depending on your platform and file system. For me, it fails on Windows XP, but passes on Solaris 10.

	public static void main(String[] args) throws IOException {
		final List<String> files =  java.util.Arrays.asList("c", "b", "a");
		for (String f : files) {
			File file = new File(f);
			file.createNewFile();
			file.deleteOnExit();	
		}
		FilenameFilter filenameFilter = new FilenameFilter() {
			public boolean accept(File dir, String name) {
				return files.contains(name);
			}
		};
		File[] ondisk = new File(".").listFiles(filenameFilter);
		for(int i = 0; i < files.size(); i++) {
			assert ondisk[i].getName().equals(files.get(i)) : "Expected file " + files.get(i) + " but found " + ondisk[i].getName();
		}
	}

Depending on your application, you may want to sort the files alphabetically, or by last modified. The following example emulates the ls -ta command:

	private static final Comparator<File> lastModified = new Comparator<File>() {
		@Override
		public int compare(File o1, File o2) {
			return o1.lastModified() == o2.lastModified() ? 0 : (o1.lastModified() < o2.lastModified() ? 1 : -1 ) ;
		}
	};
	public void testFileSort() throws Exception {
		File[] files = new File(".").listFiles();
		Arrays.sort(files, lastModified);
		System.out.println(Arrays.toString(files));
	}
分享到:
评论

相关推荐

    java 删除指定目录下的文件

    File[] files = dir.listFiles(); if (files != null) { for (File file : files) { deleteDirectoryRecursively(file); } } dir.delete(); } else { dir.delete(); } } } ``` 在上述代码中,`...

    批量移除文件的BOM格式

    File[] files = directory.listFiles(); if (files != null) { for (File file : files) { removeBOM(file); } } else { System.out.println("目录为空"); } } else { System.out.println("目录不存在"); ...

    Debugging with GDB --2007年

    2.1.3 Redirecting WDB input and output to a file . . . . . 2.2 Quitting GDB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.3 Shell commands . . . . . . . . . . . ....

    JavaSoundDemo.zip

    permission java.io.FilePermission "&lt;&lt;ALL FILES&gt;&gt;", "read, write"; permission javax.sound.sampled.AudioPermission "record"; permission java.util.PropertyPermission "user.dir", "read"; }; The ...

    The Definitive Guide to NetBeans Platform

    ■CHAPTER 7 File Access and Display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 ■CHAPTER 8 Graphical Components . . . . . . . . . . . . . . . . . . . . . . . . . . ....

    Java编程题汇总

    File[] files = directory.listFiles(); if (files != null) { for (File file : files) { if (file.isFile()) { System.out.println(file.getName()); } } } } } ``` **知识点解释:** - **文件对象**:...

    Java邮件开发Fundamentals of the JavaMail API

    With the JavaMail API, in order to communicate with a server, you need a provider for a protocol. The creation of protocol-specific providers is not covered in this course because Sun provides a ...

    iBatis-设置缓存模式-Java源码(下载)

    &lt;sqlMap resource="com/mydomain/data/Order.xml"/&gt; &lt;sqlMap resource="com/mydomain/data/Documents.xml"/&gt; --&gt; &lt;/sqlMapConfig&gt; File: Util.java import java.io.Reader; import java.sql....

    apktool documentation

    apks are nothing more than a zip file containing resources and compiled java. If you were to simply unzip an apk like so, you would be left with files such as classes.dex and resources.arsc. $ unzip...

    ZendFramework中文文档

    10.4.7. ORDER BY 分句 10.4.8. 通过总数和偏移量进行LIMIT限制 10.4.9. 通过页数和总数进行LIMIT限制 10.5. Zend_Db_Table 10.5.1. 简介 10.5.2. 开始 10.5.3. 表名和主键 10.5.4. 插入数据 10.5.5. 更新...

    python3.6.5参考手册 chm

    The plistlib module: A Property-List Parser ctypes Enhancements Improved SSL Support Deprecations and Removals Build and C API Changes Port-Specific Changes: Windows Port-Specific Changes: Mac OS...

    Python程序设计(第二版).chm

    "Give Me an Order of Persistence, but Hold the Pickles" Section 16.2. Persistence Options in Python Section 16.3. DBM Files Section 16.4. Pickled Objects Section 16.5. Shelve Files Section ...

    JDK7-8新特性介绍

    java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)) { // Enumerate each entry for (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements...

    Google C++ Style Guide(Google C++编程规范)高清PDF

    Header Files The #define Guard Header File Dependencies Inline Functions The -inl.h Files Function Parameter Ordering Names and Order of Includes Scoping Namespaces Nested Classes Nonmember, Static ...

    VB编程资源大全(英文源码 网络)

    It is a complete FTP client that allows you to browse FTP directories, 下载 and upload files, resume broken file transfer, create and remove directories, delete and rename files. All the operations ...

    android lint performance probe帮助.zip

    Once YourKit is installed, edit the properties in gradle.properties to point to the corresponding files in your YourKit installation. You will need to set both the yourkitJar property and the ...

    Editplus 3[1].0

    Syntax file=C:\Program Files\EditPlus 2\cpp.stx 那么,就把”C:\Program Files\EditPlus 2\“替换成你当前软件的路径。 其它提示找不到文件的解决方法同上 【10】软件技巧——设置editplus支持其它文字,如韩文 ...

Global site tag (gtag.js) - Google Analytics