Reputation: 1
I developed a software in netbeans + Ubuntu and then converted the runnable .jar file of netbeans to .exe file using a converter software. I used:
File f = new File("./dir/fileName");
which works fine in Ubuntu but it gives an error in Windows, because the directory pattern of both OSs are different.
Upvotes: 0
Views: 414
Reputation: 719446
I used:
File f = new File("./dir/fileName")
which works fine in Ubuntu but it gives error in Windows, bcz the directory pattern of both os are different.
It is presumably failing because that file doesn't exist at that path. Note that it is a relative path, so the problem could have been that the the path could not be resolved from the current directory ... because the current directory was not what the application was expecting.
In fact, it is perfectly fine to use forward slashes in pathnames in Java on Window. That's because at the OS level, Windows accepts both /
and \
as path separators. (It doesn't work in the other direction though. UNIX, Linux and MacOS do not accept backslash as a pathname separator.)
However Puce's advice is mostly sound:
It is inadvisable to hard-code paths into your application. Put them into a config file.
Use the NIO2 Path
and Paths
APIs in preference to File
. If you need to assemble paths from their component parts, these APIs offer clean ways to do it while hiding the details of path separators. The APIs are also more consistent than File
, and give better diagnostics.
But: if you do need to get the pathname separator, File.separator
is an acceptable way to get it. Calling FileSystem.getSeparator()
may be better, but you will only see a difference if your application is using different FileSystem
objects for different file systems with different separators.
Upvotes: 2
Reputation: 38152
Absolute paths should not be hardcoded. They should be read e.g. from a config file or user input.
Then you can use the NIO.2 File API to create your file paths: Paths.get(...)
(java.io.File is a legacy API).
In your case it could be:
Path filePath = Paths.get("dir", "fileName");
Upvotes: 4
Reputation: 697
You can use File.separator as you can see in api docs: https://docs.oracle.com/javase/8/docs/api/java/io/File.html
Upvotes: 1