2

I am making a standalone application using java,and in that i need to insert the path of the image that user chooses from file chooser. I am getting the path of the file but when i store it in the database(mysql) it doesn't stores the \,so when i retrieve that path,the file doesn't show up.

How to store the path of file with \\ so that one gets escaped using java code?

i tried using replaceall method but its giving an error of illegal character set.

filename.replaceall("\","\\");

But this didn't work out.

1
  • Are you going to use the stored path in another Java application, or is it used for something else? Commented Jan 21, 2011 at 20:08

5 Answers 5

5

Use Prepared statement to store path containing \.PreparedStatement doesn't escape anything

Sign up to request clarification or add additional context in comments.

Comments

4

Since String is immutable and all methods you call on it doesn't change Strings internal value, but rather return the modified result, you need to assign the result of the replace to a variable. Also, since you want replace chars, not regex patterns, the replace() method is more than sufficient. The replaceAll() takes regex and the \ is a special character in regex as well.

filename = filename.replace("\\", "\\\\");

However, forward slashes are supposed to work as good in Windows.

filename = filename.replace("\\", "/");

However #2, you might want to store it in DB using PreparedStatement which sanitizes bad and SQL-injection-sensitive characters for you away. Prepare here.


Unrelated to the concrete problem, why would you like to store the file path in a DB? This is prone to portability errors. I'd suggest to store only the (unique) filename and have the actual files in a single common path which is configureable as application setting.

Comments

0

The slash should not be an issue. Make sure your path has the slash before you insert into the database. Also make sure you are using a PreparedStatement to insert the data.

Comments

-1

With respect to Your posts BalusC but I think I cannot agree with you in one thing. Indeed Strings are immutable but filename.replace("a","b") return new instance of string.

So I think assigning to new variable is not necessary?

Comments

-1

We can also use addslashes function for saving the file path,

addslashes($filepath)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.