如何替换反斜杠后面的“t”或者java中正斜杠文件路径中转义字符中的任何其他字母或字符?

发布于 2024-12-06 15:51:01 字数 660 浏览 3 评论 0原文

我正在将 CSV 文件导入 MySQL 数据库。这可以使用 java.mysql 对文件路径中的正斜杠的支持来完成。如果用户给出路径,

String filepath=" c:\upload\date\csv\sample.csv";

我们可以使用以下代码行将 '\' 替换为 '/' 来完成。

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

但是当用户输入如下路径时,

String filepath=" c:\test.csv";

替换函数无法

像文件路径中的 '\' 那样 将 "\\" 替换为 "/"不会保留 '\',因为 '\' 后面跟着 't',它会变成 '\t' 转义字符。 每一个转义序列都会出现这种类型的问题。

我想在路径中搜索反斜杠并将其替换为正斜杠,以给出以下内容:

c:/test.csv

这是如何完成的? 如何解决这个问题呢?

I'm importing a CSV file to MySQL database. This can be done using java.mysql support for forward slash in file path. If user gives the path

String filepath=" c:\upload\date\csv\sample.csv";

we can do it by replacing '\' with '/' using following line of code.

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

but when user enters path as follows

String filepath=" c:\test.csv";

the replace function unable to replace "\\" with "/"

as '\' in the filepath does not remain '\' as '\' is followed by 't' and it becomes as '\t' escape character.
this type of problem will come with each and every escape sequence.

I want to search for backslashes in the path and replace them with a forward slash, to give this:

c:/test.csv

How is that done?
How to solve this problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

西瓜 2024-12-13 15:51:01

如果您通过 JFileChooser 获取值,那么它会更像这样:

String value = "c:\\test.csv"; // This really only has a single backslash

但是您不需要用正斜杠替换反斜杠。我猜测是您直接在生成的 SQL 中包含该值:不要这样做。使用带参数的准备好的语句,您可能会发现问题就消失了...突然间您也不再那么容易受到 SQL 注入攻击...

如果您真的,真的需要将反斜杠转换为正斜杠,您可以使用:

String newValue = oldValue.replace("\\", "/");

...但您不应该必须这样做。

If you're getting the value via JFileChooser, then it will be more like this:

String value = "c:\\test.csv"; // This really only has a single backslash

But you shouldn't need to replace the backslashes with forward slashes. My guess is that you're including the value directly in the SQL you're generating: don't do that. Use a prepared statement with parameters instead, and you may well find the problem just goes away... and suddenly you won't be as vulnerable to SQL injection attacks either...

If you really, really need to convert backslashes to forward slashes, you can use:

String newValue = oldValue.replace("\\", "/");

... but you shouldn't have to do this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文