简体   繁体   English

在Java中,将字符串用作文件路径名时,“ \\\\”和“ \\”有什么区别

[英]In java, when using Strings as file Pathnames, what is the difference between '\\' and '\'

Eg When I use C:\\\\a.txt 例如,当我使用C:\\\\a.txt

It works fine, but when I use C:\\a.txt 它工作正常,但是当我使用C:\\a.txt

It does not. 它不是。

Anyone explain the difference between the two except from saying one works and the other doesn't. 任何人都可以解释两者之间的区别,只是说一种有效而另一种无效。

Thanks 谢谢

\\ is a special character used for escaping other special characters. \\是用于转义其他特殊字符的特殊字符。 As such, if a single \\ is present it is interpreted as a special character in the string, but since there is nothing to escape, it's considered a "wrong usage". 这样,如果存在单个\\ ,它将被解释为字符串中的特殊字符,但是由于没有任何可转义的内容,因此被视为“错误用法”。

Therefore, the \\ has to be escaped with a second \\ to give it its literal meaning. 因此, \\必须以第二个\\进行转义才能赋予其字面含义。

A single \\ means an escape sequence which has a specific meaning for the compiler. 单个\\表示转义序列,对编译器具有特定含义。 \\\\ basicly escapes the escape sequence. \\\\基本上转义转义序列。 So, if you type C:\\a the compiler treats \\a as a escape sequence, something that you did not intend. 因此,如果键入C:\\a则编译器会将\\a视为转义序列,这是您不希望的。

http://docs.oracle.com/javase/tutorial/java/data/characters.html http://docs.oracle.com/javase/tutorial/java/data/characters.html

In java the \\ symbol is reserved to use with other char to make special symbols, for example, 在Java中, \\符号保留与其他char一起使用以制作特殊符号,例如,

\n is new line
\t is a tab

So if you use one \\ like in C:\\a.txt it will think that \\a is an special char, while using \\\\ will be transformed in one \\ 因此,如果您在C:\\a.txt使用\\ ,它将认为\\a是一个特殊字符,而使用\\\\则会将其转换为\\

只是要记住的一句话: Backslash is NOT a path separator!

它也很好用File.separator来获得运行JVM的操作系统所必需的分隔符“ /”或“ \\”(如果还有其他分隔符,我不知道它们)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Java中使用绝对路径名 - Using absolute pathnames in java 使用 HTL 调用 java 时使用“is”或“get”有什么区别 - What is the difference between using "is" or "get" in java when calling it with HTL Java 字符串上的 + 和 += 之间的区别 - Difference between + and += on Java Strings 使用 MongoDB 和 Java 时,文档和 dbObject 之间有什么区别? - what are the difference between document and dbObject when using MongoDB and Java? 在Java中使用Scanner类进行输入与将Strings Args []与parseint一起使用之间有什么区别? - What is Difference between using the Scanner class in Java for input and using Strings Args[] with parseint? 在Java J2ME中使用new运算符和没有new运算符分配的字符串有什么区别? - What is the difference between strings allocated using new operator & without new operator in java J2ME? java类文件版本之间有什么区别 - What is the difference between the java class file versions Java中的File和FileLoader有什么区别? - What's the difference between File and FileLoader in Java? 使用 javac 的区别<file>和 java<file></file></file> - Difference between using javac<file> and java<file> 使用 Java 11 时 JDK_JAVA_OPTIONS 和 JAVA_TOOL_OPTIONS 有什么区别? - What is the difference between JDK_JAVA_OPTIONS and JAVA_TOOL_OPTIONS when using Java 11?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM