I'm reading multiple text files using Java and printing their directories and I wonder why the output is not alphabetically arranged?
Code Snippet (got it from the internet also)
File dir = new File("/home/dilapitan/Desktop/xml-parsing/files/");
File[] listOfFiles = dir.listFiles();
for (File path : listOfFiles) {
System.out.println(path);
}
Output:
dilapitan@NT071855:~/Desktop/xml-parsing$ java Multiple
/home/dilapitan/Desktop/xml-parsing/files/c.txt
/home/dilapitan/Desktop/xml-parsing/files/b.txt
/home/dilapitan/Desktop/xml-parsing/files/a.txt
dilapitan@NT071855:~/Desktop/xml-parsing$
Can I do it with the output being:
a.txt
b.txt
c.txt
Thank you in advance!
To quote File#listDir
's documentation :
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.
If you want to print them in a specific order, you'll have to do so yourself. Java 8 streams git you an elegant way of combining the extraction of the file's name from the patch and sorting them in a single statement:
Arrays.stream(listOfFiles)
.map(File::getName)
.sorted()
.forEach(System.out::println);
Just another way to do it, but using the power of java8
List<Path> x = Files.list(Paths.get("C:\\myPath\\Tools"))
.filter(p -> Files.exists(p))
.map(s -> s.getFileName())
.sorted()
.collect(Collectors.toList());
x.forEach(System.out::println);
or even better
List<Path> x = Files.list(Paths.get("C:\\Users\\myPath\\Tools"))
.filter(Files::exists)
.map(Path::getFileName)
.sorted()
.collect(Collectors.toList());
x.forEach(System.out::println);
Thank you to those who answered. I thought of a very simple solution:
File dir = new File("/home/dilapitan/Desktop/xml-parsing/files/");
File[] listOfFiles = dir.listFiles();
Arrays.sort(listOfFiles);
for (File path : listOfFiles) {
System.out.println(path);
}
hahahaha my apologies everyone.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.