java.io.File的两种构造方法是否执行相同功能?针对mkdirs()调用场景的疑问
File(String parent, String child) and File(String pathname) functionally identical in your example? Great question! Let's break this down clearly, starting with what each constructor does and then focusing on your specific scenario.
First, let's outline the core behavior of each constructor:
File(String parent, String child): This takes a parent directory path and a child path (file/directory name), then combines them using your system's default path separator (like/on Android/Unix systems,\on Windows) to form the full path for the newFileobject.File(String pathname): This directly uses the complete path string you provide to create theFileobject, no拼接 needed.
For your exact example
When you run:
new File("/storage/emulated/0", "directory").mkdirs()
The constructor will combine the parent path /storage/emulated/0 and child name directory into the full path /storage/emulated/0/directory (since Android uses / as the path separator). This is exactly the same as passing the full path directly to the other constructor:
new File("/storage/emulated/0/directory").mkdirs()
In this scenario, the two calls are 100% functionally identical: both will attempt to create the directory folder under /storage/emulated/0, and mkdirs() will handle creating any missing parent directories (though that's not necessary here since /storage/emulated/0 is typically Android's external storage root).
When might they behave differently?
The only edge case where these constructors diverge is if the child parameter is an absolute path itself. For example:
new File("/storage/emulated/0", "/system/app").mkdirs()
Here, the constructor ignores the parent path entirely and uses the absolute child path /system/app instead. So this is equivalent to new File("/system/app").mkdirs(), not new File("/storage/emulated/0/system/app").mkdirs(). That's an important detail to keep in mind.
内容的提问来源于stack exchange,提问作者Viktor

