`

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));
	}
分享到:
评论

相关推荐

    Thinking in Java 4th Edition

    The argument list ......................... 49 Building a Java program ...... 50 Name visibility ............................. 50 Using other components ............. 50 The static keyword ..............

    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 . . . . . . . . . . . . . . . . . . . . . . . . . . ....

    pro_apache_third_edition..pdf

    Contents About the Author...............................................................................................xix About the Technical Reviewer and Contributing Author.................xxi ...

    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....

    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 ...

    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 ...

    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支持其它文字,如韩文 ...

    tomcat-7_API_帮助文档

    or by placing them in JAR files in the "lib" directory. To override the XML parser implementation or interfaces, use the endorsed mechanism of the JVM. The default configuration defines JARs located ...

    tomcat-8_API

    or by placing them in JAR files in the "lib" directory. To override the XML parser implementation or interfaces, use the endorsed mechanism of the JVM. The default configuration defines JARs located ...

    EditPlus 2整理信箱的工具

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

    Beginning Python (2005).pdf

    Try It Out: Searching for Files of a Particular Type 181 Try It Out: Refining a Search 183 Working with Regular Expressions and the re Module 184 Try It Out: Fun with Regular Expressions 186 Try ...

    PHP基础教程 是一个比较有价值的PHP新手教程!

    你可以用list()或者array()来定义它们,也可以直接为数组赋值。数组的索引从0开始。虽然我在这里没有说明,但是你一样可以轻易的使用多维数组。 // 一个包含两个元素的数组 $a&#91;0&#93; = "first"; $a&#91;1&#93;...

Global site tag (gtag.js) - Google Analytics