Friday, December 21, 2012

How to escape String literal in Java using Eclipse IDE

Whenever you paste String in Eclipse which contains escape characters,  to store in a String variable or just as String literal it will ask to manually escape special characters like single quotes, double quotes, forward slash etc. This problem is more prominent when you are pasting large chunk of data which contains escape characters like a whole HTML or XML file,  which contains lots of single quotes e.g. ‘’ and double quotes “” along with forward slash on closing tags. It’s very hard to manually escape all those characters and its pretty annoying as well. While writing JUnit test for XML documents, parsing and processing I prefer to have whole XML file as String in Unit test, which pointed me to look for that feature in Eclipse. As I said earlier in my post Top 30 Eclipse keyboard shortcuts, I always look to find new shortcut and settings in Eclipse which help to automate repetitive task. Thankfully Eclipse has one setting which automatically escapes text as soon as you paste it. This is even more useful if you prefer to copy file path and just paste it, Since windows uses forward slash it automatically escape that instead of you going manually and escaping them. By default this setting is disabled in Eclipse IDE and you need to enable it.

How to enable automatic escaping while pasting text as String literal in Eclipse :

Here is the steps you need to perform to enable this setting in Eclipse which will automatically provide escaping required in Java for special characters like quotes, slashes etc.

1. Open Eclipse IDE
2. Go to Windows --> Preferences --> Java --> Editor --> Typing 
3) check the check box "Escape text when pasting into a String literal" on section "In String literals.

This will escape text when pasted as String literal. Do it now, its an option worth enabling and I just wonder why not Eclipse IDE make this option enable by default. Believe me its extremely useful but same time hard to discover. Here is a screen shot of this option.  As you can see, by default this option is not enabled.

How to escape text when paste as String literal Eclipse Tips

Next time no need to extra edit any XML or HTML text before pasting as String literal in Eclipse IDE. Eclipse will do it for you automatically. Once again, if you are doing anything manually and think that it would be good Eclipse can assist on that task, look for it using google or Eclipse help. There is good chance you can discover a useful Eclipse shortcut or settings.

Other Eclipse tutorials and tips for Java programmer

3 comments :

Anonymous said...

Very Informative..

Ajay Sharma said...

Awesome

nabil said...

thanks man you saved my day

Post a Comment