如何在java中的文件路径中转义反斜杠和自动生成的转义字符 [英] How to escape the backslashes and the automatically generated escape character in file path in java

查看:1774
本文介绍了如何在java中的文件路径中转义反斜杠和自动生成的转义字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常小而简单的问题,但我没有得到解决方案。
实际上,我使用文件选择器获取CSV文件路径。
我使用加载数据本地infile查询将此csv文件中的数据输入到数据库。



假设我输入的文件路径是C:\title .csv
当我把这个字符串放在查询中,你会看到路径中的\t组合。这个\它实际上是文件路径的一部分,而不是转义字符'\t'。但是java和mysql认为它是转义字符。



然后我试图用\\替换'\'在文件路径字符串中使用以下代码

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

仍然对文件路径没有影响,仍然将'\t'视为转义字符。



所以我的问题是如何解决这个问题而不改变文件的名称?



如果我们有路径,如

  String filepath =C:\\\
ew folder\title.csv;

它会将\\\
和\t视为转义字符。
如果路径中的文件或文件夹的名称导致转义字符,如何解决此问题?

解决方案

使用Java 字符串文字中的双斜线可以转义斜杠:

  String s =c:\\ \\\\\title.csv; 

如果最终用户在JFileChooser中输入字符串,则字符串变量将包含所有由用户。只有在Java源代码中使用String文字时,才需要转义。



并使用预备语句将字符串插入到数据库表中。这将适当地避免特殊字符,并避免 SQL注入攻击。在有关JDBC的Java教程中阅读有关准备语句的更多信息。 / p>

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. I am entering the data in this csv file in to database using load data local infile query.

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. This \t which is actually part of the file path and not the escape character '\t'. But the java and mysql consider it as escape character.

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.

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. 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 :

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. Escaping is only needed when using String literals in Java source code.

And use a prepared statement to insert strings into a database table. This will properly escape special characters and avoid SQL injection attacks. Read more about prepared statements in the Java tutorial about JDBC.

这篇关于如何在java中的文件路径中转义反斜杠和自动生成的转义字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆