如何在文件路径中的转义符中的反斜杠后跟't'或任何其他字母或字符来替换Java中的正斜杠? [英] How to replace backslash followed by 't' or any other alphabet or character in escape chacter in file path to forward slash in java?

查看:392
本文介绍了如何在文件路径中的转义符中的反斜杠后跟't'或任何其他字母或字符来替换Java中的正斜杠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将CSV文件导入MySQL数据库.可以使用java.mysql对文件路径中的正斜杠的支持来完成此操作.如果用户提供了路径

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 '\'不会保留'\',因为'\'后跟't'并成为'\t'转义字符. 这种问题会伴随着每一个转义序列.

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?

推荐答案

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

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

但是您不需要用正斜杠替换反斜杠.我的猜测是您将值直接包含在要生成的SQL中:不要这样做.改用带参数的预备语句,您可能会发现问题已经消失了……突然之间,您也不会像以前那样容易受到SQL注入攻击的侵害...

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.

这篇关于如何在文件路径中的转义符中的反斜杠后跟't'或任何其他字母或字符来替换Java中的正斜杠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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