简体   繁体   English

java中如何转义文件路径中的反斜杠和自动生成的转义字符

[英]How to escape the backslashes and the automatically generated escape character in file path in java

I have very small and simple problem but I am not getting solutions on it.我有非常小而简单的问题,但我没有得到解决方案。 Actually I am getting a CSV file path using file chooser.实际上,我正在使用文件选择器获取 CSV 文件路径。 I am entering the data in this csv file in to database using load data local infile query.我正在使用加载数据本地 infile 查询将此 csv 文件中的数据输入到数据库中。

Suppose my entered file path is "C:\\title.csv" When I put this string in to query the you will see the \\t combination in the path.假设我输入的文件路径是“C:\\title.csv” 当我把这个字符串放入查询中时,你会在路径中看到 \\t 组合。 This \\t which is actually part of the file path and not the escape character '\\t'.这个 \\t 实际上是文件路径的一部分,而不是转义字符 '\\t'。 But the java and mysql consider it as escape character.但是 java 和 mysql 将其视为转义字符。

then I tried to replace '\\' in the file path string with "\\\\" using following code line.然后我尝试使用以下代码行将文件路径字符串中的 '\\' 替换为“\\\\”。

String filepath="C:\title.csv";
String filepath2=filepath.replace("\\","\\\\");

Still there is not effect on the file path and it still consider the '\\t' as escape character.仍然对文件路径没有影响,它仍然将 '\\t' 视为转义字符。

So my question is how to solve this problem without changing the name of the file?所以我的问题是如何在不更改文件名的情况下解决这个问题?

If we have path like如果我们有类似的路径

String filepath="C:\new folder\title.csv";

It will consider the \\n and \\t as escape character.它会将 \\n 和 \\t 视为转义字符。 how to solve this problem if the name of the file or folder in path cause for escape character?如果路径中的文件或文件夹的名称导致转义字符,如何解决此问题?

Use a double slash in Java string literal to escape a slash :在 Java字符串文字中使用双斜杠来转义斜杠:

String s = "c:\\new folder\\title.csv";

If an end user enters a string in a JFileChooser, the string variable will contain all the characters entered by the user.如果最终用户在 JFileChooser 中输入字符串,则字符串变量将包含用户输入的所有字符。 Escaping is only needed when using String literals in Java source code.只有在 Java 源代码中使用字符串文字时才需要转义。

And use a prepared statement to insert strings into a database table.并使用准备好的语句将字符串插入到数据库表中。 This will properly escape special characters and avoid SQL injection attacks.这将正确转义特殊字符并避免SQL 注入攻击。 Read more about prepared statements in the Java tutorial about JDBC .关于 JDBCJava 教程中阅读有关准备好的语句的更多信息。

你需要使用:

 String filepath2=filepath.replace("\\","\\\\");

String filepath2=filepath.replace("\\","\\\\")不是有效代码 - \\是字符串文字中的特殊字符,需要进行转义:

String escapedFilepath = filepath.replace("\\","\\\\"); //double all backslashes

您必须在初始文字 ( filepath ) 中使用转义,例如:

String filepath="C:\\title.csv"

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM