Java and Windows - error: illegal escape character - java

I have done my .java file that changes registry data. But I am getting "illegal escape character" error on the line where Runtime.getRuntime().exec exists. Where is my mistake ?
import java.util.*;
import java.applet.Applet;
import java.awt.*;
class test {
public static void main(String args[]) {
try {
Runtime.getRuntime().exec("REG ADD 'HKCU\Software\Microsoft\Internet Explorer\Main' /V 'Start Page' /D 'http://www.stackoverflow.com/' /F");
} catch (Exception e) {
System.out.println("Error ocured!");
}
}
}

You need to escape the backslashes used in your path.
String windowsPath = "\\Users\\FunkyGuy\\My Documents\\Hello.txt";

You need to escape \ with another \, so replace \ with \\ in your input string.

You need to escape the backslash characters in your registry path string:
"REG ADD `HKCU\\Software\\ ...
The backslash character has a special meaning in strings: it's used to introduce escape characters. if you want to use it literally in a string, then you'll need to escape it, by using a double-backslash.

Back slashes in Java are special "escape" characters, they provide the ability to include things like tabs \t and/or new lines \n and lots of other fun stuff.
Needless to say, you to to "escape" them as well by adding an addition \ character...
'HKCU\\Software\\Microsoft\\Internet Explorer\\Main'
On a side note. I would use ProcessBuilder or at the very least, the version of Runtime#exec that uses array arguments.
It will save a lot of hassle when it comes to dealing with spaces within command parameters, IMHO

Probably because you didn't escape the backslash in your string. Have a look at http://docs.oracle.com/javase/tutorial/java/data/characters.html for more information about proper escaping.

you need replace escape \ with \\
below code will work
Runtime.getRuntime().exec("REG ADD 'HKCU\\Software\\Microsoft\\Internet Explorer\\Main' /V 'Start Page' /D 'http://www.stackoverflow.com/' /F");

Related

How to use back slash in android json

I had a scenario where I need to give back slash for a key in JSON put method like below
json.put("path" , " \\abx\2010\341\test.PDF");
The value I gave for path key shows error.
How to handle this case?
You need to write double slash instead of one: \\
So your code become:
json.put("path" , " \\\\abx\\2010\\341\\test.PDF");
You can learn more about escaping special characters in this answer.
Try like this
json.put("path" , "\\abx\\2010\\341\\test.PDF");
You need to escape \.
Try json.put("path" , " \\abx\\2010\\341\\test.PDF");
You can learn more about it under Escape Sequences.
double \\ = single \ in string ""
json.put("path","\\abx\\2010\\341\\test.PDF");
If you want to show like this, JSON file should be as below.
"path" : " \\abx\2010\341\test.PDF"
JSON also \ represent as \ in java special characters. Then java code should be as below.
json.put("path" , " \\\\abx\\2010\\341\\test.PDF");

Making sure a path string is a valid java path string

This is how i try to make sure a path given in a property file is a valid java path (with \\ instead of \) :
String path = props.getProperty("path");
if (path.length()>1) path=path.replaceAll("\\\\", "\\");
if (path.length()>1) path=path.replaceAll("\\", "\\\\");
in the first replace im making sure that if the path already valid (has \\ instead of \) then it wont get doubled to \\\\ instead of \\ in the second replace...
anyway i get this weird exception :
java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(Unknown Source)
at java.util.regex.Matcher.appendReplacement(Unknown Source)
at java.util.regex.Matcher.replaceAll(Unknown Source)
at java.lang.String.replaceAll(Unknown Source)
at com.hw.Launcher.main(Launcher.java:56)
can anyone tell why?!
replaceAll expects RegExes, use replace instead.
You can find the JavaDocs here
If you want to be sure the path is valid, how about trying
File f = new File("c:\\this\\that");
f.getCanonicalPath();
The File class is made for taking apart paths. It's probably the best way to verify that a path is valid.
(Let me spell it out for newbies too.)
If you have a text file or a String, normally only a single backslash should occur.
In java source code, a string or character denotation, backslash is the escape character, transforming the next one into a special meaning. Backslash itself should be given doubled, as \\. The string value itself will have only one backslash character.
If you read special text, using backslash escaping (like \n for a line break), then use the non-regex replace of strings:
// First escapes of other:
path = path.replace("\\n", "\n"); // Text `\n` -> linefeed
path = path.replace("\\t", "\t"); // Text `\t` -> tab
// Then escape of backslash:
path = path.replace("\\\\", "\\"); // Text `\\` -> backslash
For file paths only the last might make sense, but it should not have been needed.

replacing '\\' string with '\' in java

Hi we have a string like "ami\\303\\261o". we want to replace \\ with \.
We have tried the following:
replace("\\", "\")
replaceAll("\\", "\")
But we didn't get proper output.
For use in a Java regex, you need to escape the backslashes twice:
resultString = subjectString.replaceAll("\\\\\\\\", "\\\\");
In a regex, \\ means "a literal backslash".
In a Java string, "\\" encodes a single backslash.
So, a Java string that describes a regex that matches a single backslash is "\\\\"
And if you want to match two backslashes, it's "\\\\\\\\", accordingly.
You must keep backslash escaping in mind. Use
public class so {
public static void main(String[] args) {
String s = "ami\\\\303\\\\261o";
System.out.println(s);
s = s.replace("\\\\", "\\");
System.out.println(s);
}
};
Each backslash escapes the following backslash and resolves to the two literal strings \\ and \
Also keep in mind, String.replace returns the modified string and keeps the original string intact.
No need of regex here. Escape the slashes and use replace()
someString.replace('\\\\', '\\');
Thats because the \\ inside your input String get internally replaced by \ because of the Java Escape Character.
That means that if you output your String without performing any regex on it, it would look like this: "ami\303\261o".
Generally you should remember to escape every escape-character with itself:
\ -> escaped = \\
\\ -> escaped = \\\\
\\\ -> escaped = \\\\\\
...and so on
Try below code
String val = "ami\\303\\261o";
val =val.replaceAll("\\\\", "\\\\");
System.out.println(val);
Outpout would be
ami\303\261o
A Fiddle is created here check it out
Java Running Example

Not able to escape \ in Java using \\

I have a string.
String invalid = "backslash escaping as <>:;%+\/"."
I received an error message telling me to add \ to escape the sequence.
When I try to write this in Java I know that backslash needs to be escaped as \\. So I wrote it as:
String invalid = "backslash escaping as <>:;%+\\/\"."
Now this displays as backslash escaping as <>:;%+\\/".
The backslash is not escaping. How do I get only one backslash?
I don't find a problem with your modification. This runs as expected:
String invalid = "backslash escaping as <>:;%+\\/\".";
System.out.println(invalid);
output:
backslash escaping as <>:;%+\/".
In your first example, you have a little problem:
\/".
Which I believe should be like this:
/\".
Because in the first way, you are closing the string before you want to. The part ." is out of the String.
Edit:
try writing the output to a file or to a JTextField or something and see what happens, your string is correct and if you compare your output with my output it is the same. It might be an issue with your debugger (weird, but possible).
The second string in your post is correctly displayed. There must be something wrong with the way in which you observe the output.
Just try the simplest thing possible:
Create a file named Escape.java and write this code into its contents:
public class Escape {
public static void main(String... args) {
String s = "backslash escaping as <>:;%+\\/\".";
System.out.println(s);
}
}
Open a whatever command line that your OS provides and go to the folder with the said source file.
Compile the source file:
javac Escape.java
And run the class file:
java -cp . Escape
It should give this output:
backslash escaping as <>:;%+\/".
...which is exactly what you want, I believe.

Java Regex - Changing path with an alias

I have a path called $SERVER/public_html/ab1/ab2/.
I want to change it so that instead of $SERVER it just replaces it with my user directory. So I do
path = path.replaceFirst("\\$SERVER", System.getProperty("user.dir"));
but when I run it, it removes my \ in the new string.
F:Programming ProjectsJava Project/public_html/ab1/ab2/
Pattern has a String quote(String) function that will help you for the first string and Matcher has String quoteReplacement(String) for the second:
path = path.replaceFirst(java.util.regex.Pattern.quote("$SERVER"), java.util.regex.Matcher.quoteReplacement(System.getProperty("user.dir")));
edit: the reason you have to escape anything is because the second string has the semantics of Matcher.appendReplacement which treats backslashes and dollars as escape next char and insert captured group resp.
from the doc:
Note that backslashes () and dollar
signs ($) in the replacement string
may cause the results to be different
than if it were being treated as a
literal replacement string. Dollar
signs may be treated as references to
captured subsequences as described
above, and backslashes are used to
escape literal characters in the
replacement string.
a more obvious solution is (be careful of the needed escaped with that backslash)
path = path.replaceFirst("\\$SERVER", System.getProperty("user.dir").replaceAll("\\\\","\\\\\\\\"));
Yea you are completly right. I am trying to figure out why it is happening so.
But at the moment the only think I can suggest is to go with such a solution.
public class RegExTest
{
public static void main(String[] args)
{
String path = "$SERVER/public_html/ab1/ab2";
System.out.println("path before="+path);
String user = System.getProperty("user.dir");
System.out.println("user="+user);
System.out.println("replaceFirst using user="+path.replaceFirst("\\$SERVER", user));
path = path.replaceFirst("\\$SERVER", "");
path = user +path;
System.out.println("path after="+path);
}
}
EDIT: ..Why it does that?
From what I see in the code of the method line 701 to 708 they must do it. They just skip them. As to the reason why they do it, I still am not sure.
EDIT2:
OK reading the doc for the method answers it all. They do it so they can interpret accordingly special characters. Thus when reading the replacement they spot a slash the algorithm assumes it can be a part of special character and in result skips it.
if (nextChar == '\\') {
cursor++;
nextChar = replacement.charAt(cursor);
result.append(nextChar);
cursor++;
} else if (nextChar == '$') {
// Skip past $
cursor++;
Ok so in Windows the default slashes look like so '\' whereas on *nix the slashes look like so '/' . The simplest way to get through this problem is to invoke the replace function with the following parameters '\\' and '/' . That way you path will have its slashes all facing the same way.

Categories

Resources