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

家住魔仙堡 提交于 2019-11-26 22:54:56

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.

you need to use:

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

String filepath2=filepath.replace("\","\\") is not valid code - \ is a special character in string literals and needs to be escaped:

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

You have to use escaping in the initial literal (filepath), for example:

String filepath="C:\\title.csv"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!