I am looking to write and read text files to and from (respectively) a directory different from that of my program. When I specify a directory to write to or read from, should I be using forward slashes or backslashes to identify a file path?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Using forward slashes will make it system independent. I'd stick to that for simplicity.
Consider using
java.io.File.separator
if you ever display the path to the user. You'd rather not surprise those Windows users. They're a jumpy lot.You should use /
For example C:/User/...
I've never found it documented anywhere, but the JDK classes let you use slashes regardless of whether you're on Windows or not. (You can see this in the JDK source, where it explicitly converts path separators for you.)
Officially — and certainly in any UI you're doing — you should use the
file.separator
system property, which is available viaSystem.getProperty
(the list of standard system properties is documented in the docs forSystem.getProperties
):...and also via the
static
fields They're also available asFile.separator
(andFile.separatorChar
).You can also use the various features of the
java.io.File
class for combining and splitting paths, and/or the various features of the interfaces and classes injava.nio.file
.You could use either.
If you use
/
then you only need a single slash.If you use
\
, you need to use\\
. That is, you need to escape it.You can also use the
resolve()
method of thejava.nio.Path
class to add directories / files to the existing path. That avoids the hassle of using forward or backward slashes. You can then get the absolute path by calling thetoAbsolutePath()
method followed bytoString()
SSCCE: