It was an incident when I was writing a program that uses the File class in Java. ..
It was a program that patrolled the folder tree of a specified folder, read the text after that, and output it to CSV.
targetFolder ├folder1 │ ├folder1_folder1 │ │ ├text1.txt │ │ ├text2.txt │ │ └text3.txt │ └folder1_folder2 │ ├text.txt │ ├text2.txt │ └text3.txt ├folder2 │ ├folder2_folder1 │ │ ├text1.txt │ │ ├text2.txt │ │ └text3.txt
The following is omitted
The method to go around is as follows
private static List<File> getFileInstanceList(String filePathStr) throws IOException {
try (Stream<Path> path = Files.list(Paths.get(filePathStr))) {
return path.map(f -> f.getFileName().toFile()).collect(Collectors.toList());
}
}
If you pass the path of the folder as an argument, the File instance of the folder in that folder will be returned as a list.
List<File> list = getFileInstanceList("C:\Users\hoge\Desktop\targetFile\");
At the read source, the returned list was looped with For-each, and the file path of the child folder was passed to the above method again, but ...
There was a problem with the File instance returned by this method When I got the path of the child folder, I could only get the file name
When I checked the JavaDoc of the File class, I found the following description.
Returns a File object that represents this path. If this Path is associated with the default provider, this method is equivalent to returning a File object constructed with a String representation of this Path. If this path is created by calling the File to Path method, there is no guarantee that the File object returned by this method will be equal to the original File.
Equivalent to returning a File object constructed with a String representation? ??
I don't know what it is, but I think it's like this if it's easy to understand. File class has a constructor that takes a String as an argument When the instance generated at that time specifies the full path of File In some cases, only the file name is specified, but the latter cannot retain the actual state of the file correctly.
Well, "C: \ Users \ hoge \ Desktop \ targetFile \ folder1" If there is a File instance created by "folder1", the former would be more realistic.
private static List<File> getFileInstanceList(String filePathStr) throws IOException {
try (Stream<Path> path = Files.list(Paths.get(filePathStr))) {
return path.map(f -> new File(f.toUri())).collect(Collectors.toList());
}
}
Since it is enough to pass the full path to generate a File, I changed it to instantiate a File with Uri of Path as an argument.
I'm just not sure even if I read JavaDoc, so I wonder if API is used to it.
Recommended Posts