How to remove single quotes with double quotes in java - java

I don't have any idea about regex pattern matching, and I am having a problem with single quotes in file path when when I run batch file through exec() command, I get the following error i.e
Error is-
Windows cannot find 'C:\Program'.
I am having trouble with single quotes when CMD tries to get into the desired directory.
So, anyone could tell me what to do here??
I created a batch file to compile and run java programs I have a function called createrunbat(String,String), and following code:
private File createrunbat(String str,String par)
{
if(str.startsWith("Text Editor-",0))
{
str=str.replaceFirst("Text Editor-","");
}
String sng,s2;
File fe;
try{
FileOutputStream fos;
DataOutputStream dos;
sng=str;
int a=sng.indexOf(".");
sng=sng.substring(0,a);
file=new File(jfc.getSelectedFile().getParent(),sng+".bat");
fd=file.getAbsoluteFile();
str=fd.getParent().substring(0, 2);
fos=new FileOutputStream(file);
dos=new DataOutputStream(fos);
dos.writeBytes("#echo off \n");
dos.writeBytes("cd\\"+"\n");
if(fd.getParentFile().isDirectory())
{
dos.writeBytes(str+"\n");
}
s2=jfc.getSelectedFile().getParent();//I am having single quote problem from here
dos.writeBytes("cd "+s2+"\\"+"\n");
dos.writeBytes("javac "+sng+".java"+"\n");
dos.writeBytes("java "+sng+" "+par+"\n");
dos.writeBytes("pause \n");
dos.writeBytes("exit \n");
dos.close();
}
catch(FileNotFoundException ex)
{
}
catch(IOException ex2)
{
JOptionPane.showMessageDialog(this,ex2.toString());
}
return fd;
}

I think this is a rather more of a case that the blank in the path name is causing trouble and you will need to wrap quotes around the path
dos.writeBytes ("cd \"" + s2 +"\""+"\n");

You are perhaps confusing the error output with the input.
Windows cannot find 'C:\Program'.
The single quotes there are used to wrap the problematic data so you the developer know the boundaries of the input causing issues. The single quotes are not part of what your program interprets.
As others have suggested I imagine the real issue is the whitespace in your path. Your command line is reading the path as two separate arguments instead of one. Ironically, wrapping the path in quotes should fix the issue.
'C:\Program Files\SomePlace\...'
^ gets cut on whitespace and becomes two arguments instead of one:
'C:\Program' and 'Files\SomePlace\...'
'"C:\Program Files\SomePlace\..."'
^ quotes will keep the path together as a single argument
Edit: How to wrap the path.
Java1 has a good solution in their answer so I'll offer an alternative one that uses String formatting.
String safePath = String.format("\"%s\"", jfc.getSelectedFile().getParent().getAbsolutePath());
In this instance, the first argument to the String.format() method is the pattern to use, the second is the variable to substitute.
The actual quotes that will be around the path must be escaped (\") as they have a special meaning in java to denote the start or end of a String. You must escape them to use them inside a String. The place-holder is where your path will be placed (%s).
Side note:
You should really use much more descriptive variable names in your code. It is quite bad practice to use names like s2, sng, fe, fd and so on. Be descriptive and exact with your naming and following, debugging and writing your code will become easier.

Related

Creating a text file with java without using absolute path

following the question I asked before How to have my java project to use some files without using their absolute path? I found the solution but another problem popped up in creating text files that I want to write into.here's my code:
private String pathProvider() throws Exception {
//finding the location where the jar file has been located
String jarPath=URLDecoder.decode(getClass().getProtectionDomain().getCodeSource().getLocation().getPath(), "UTF-8");
//creating the full and final path
String completePath=jarPath.substring(0,jarPath.lastIndexOf("/"))+File.separator+"Records.txt";
return completePath;
}
public void writeRecord() {
try(Formatter writer=new Formatter(new FileWriter(new File(pathProvider()),true))) {
writer.format("%s %s %s %s %s %s %s %s %n", whichIsChecked(),nameInput.getText(),lastNameInput.getText()
,idInput.getText(),fieldOfStudyInput.getText(),date.getSelectedItem().toString()
,month.getSelectedItem().toString(),year.getSelectedItem().toString());
successful();
} catch (Exception e) {
failure();
}
}
this works and creates the text file wherever the jar file is running from but my problem is that when the information is been written to the file, the numbers,symbols, and English characters are remained but other characters which are in Persian are turned into question marks. like: ????? 111 ????? ????.although running the app in eclipse doesn't make this problem,running the jar does.
Note:I found the code ,inside pathProvider method, in some person's question.
Your pasted code and the linked question are complete red herrings - they have nothing whatsoever to do with the error you ran into. Also, that protection domain stuff is a hack and you've been told before not to write data files next to your jar files, it's not how OSes (are supposed to) work. Use user.home for this.
There is nothing in this method that explains the question marks - the string, as returned, has plenty of issues (see above), but NOT that it will result in question marks in the output.
Files are fundamentally bytes. Strings are fundamentally characters. Therefore, when you write code that writes a string to a file, some code somewhere is converting chars to bytes.
Make sure the place where that happens includes a charset encoding.
Use the new API (I think you've also been told to do this, by me, in an earlier question of yours) which defaults to UTF-8. Alternatively, specify UTF-8 when you write. Note that the usage of UTF-8 here is about the file name, not the contents of it (as in, if you put persian symbols in the file name, it's not about persian symbols in the contents of the file / in the contents you want to write).
Because you didn't paste the code, I can't give you specific details as there are hundreds of ways to do this, and I do not know which one you used.
To write to a file given a String representing its path:
Path p = Paths.get(completePath);
Files.write("Hello, World!", p);
is all you need. This will write as UTF_8, which can handle persian symbols (because the Files API defaults to UTF-8 if you specify no encoding, unlike e.g. new File, FileOutputStream, FileWriter, etc).
If you're using outdated APIs: new BufferedWriter(new OutputStreamWriter(new FileOutputStream(thePath), StandardCharsets.UTF-8) - but note that this is a resource leak bug unless you add the appropriate try-with-resources.
If you're using FileWriter: FileWriter is broken, never use this class. Use something else.
If you're converting the string on its own, it's str.getBytes(StandardCharsets.UTF_8), not str.getBytes().

PrintWriter the output file is not there although no exception thrown

I have just started learning Java and I have got following problem I have been struggling for hours with. I want to use PrintWriter in order to produce a simple text file.
I do not get any runtime exception, still the file is not appearing in the specified directory.
public class Main {
public static void main(String[] args) {
try (final PrintWriter writer = new PrintWriter(
new File("c:\test\new\notes.txt"))) {
writer.write("Test note");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
What am I doing wrong?
\ represents an escape character so needs to be escaped itself for literal backslash characters. You can also use / and Java will resolve the correct separation character for the platform
try (final PrintWriter writer = new PrintWriter("c:\\test\new\\notes.txt")) {
Add writer.flush() after writer.write("Test note"), and use double backslashes for Windows paths (as other answers are suggesting).
As Reimeus already said, \ is an escape character in java.
That means that a string containing "\n" or "\t" does not represent the stringliteral \n or \t!
'\n' represents the newline character and '\t' represents the TAB character!
For the better understanding, the following code:
System.out.println("c:\test\new\notes.txt");
would not print c:\test\new\notes.txt to the console, it would print
c: est
ew
otes.txt
to the console!
To be able to write the backslash in a string you'll need to use '\\'!
I see your question as having 2 parts:
Why doesn't the code work?
Why was no exception thrown?
The first question has already been answered, but I think the answer to the second question is at least as important because your current code will still fail silently if there is any problem writing to the file.
From the documentation of PrintWriter (http://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html):
Methods in this class never throw I/O exceptions, although some of its
constructors may. The client may inquire as to whether any errors have
occurred by invoking checkError().
Therefore it is essential that you call checkerror() after every call to a PrintWriter method or your code will not be reliable.

Is their any way to eliminate two backward slash to one in Eclipse

I came to a scenario while using eclipse, in which if i use two back slash in below mention function.
"private Keywords(){
try{
OR=new Properties();
FileInputStream fs=new FileInputStream(System.getProperty("user.dir")+"**\\src\\com\\config\\OR.properties"**);
OR.load(fs);
"
this function works but if I use single slash it won't work . Is their way that i would be able to use single backward slash only while giving a source path..
Your question has nothing to do with Eclipse.
You need to escape back-slashes in Strings, as they are themselves an escape character.
What you can eventually use to somewhat "shorten" your code is the system property System.getProperty("file.separator"), then assign it to some constant and use that reference instead.
But that's close to cosmetics.
You can use the 2 backslashes as a single variable say,
String separator = "\\";
String file_path = "src"+separator +"com"+separator +"config"+separator +"OR.properties";
System.out.println("File Path is :: " + file_path);
Or as Mena Suggested, you can use:
String separator = System.getProperty("file.separator");
Get it straight with your String literals
http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html

Java regex for Windows file path

I'm trying to build a Java regex to search a .txt file for a Windows formatted file path, however, due to the file path containing literal backslashes, my regex is failing.
The .txt file contains the line:
C\Windows\SysWOW64\ntdll.dll
However, some of the filenames in the text file are formatted like this:
C\Windows\SysWOW64\ntdll.dll (some developer stuff here...)
So I'm unable to use String.equals
To match this line, I'm using the regex:
filename = "C\\Windows\\SysWOW64\\ntdll.dll"
read = BufferedReader.readLine();
if (Pattern.compile(Pattern.quote(filename), Pattern.CASE_INSENSITIVE).matcher(read).find()) {
I've tried escaping the literal backslashes, using the replace method, i.e:
filename.replace("\\", "\\\\");
However, this is failing to find, I'm guessing this is because I need to further escape the backslashes after the Pattern has been built, I'm thinking I might need to escape upto an additional four backslashes, i.e:
Pattern.replaceAll("\\\\", "\\\\\\\\");
However, each time I try, the pattern doesn't get matched. I'm certain it's a problem with the backslashes, but I'm not sure where to do the replacement, or if there's a better way of building the pattern.
I think the problem is further being compounded as the replaceAll method also uses a regex, with means the pattern will have it's own backslashes in there, to deal with the case insensitivity.
Any input or advice would be appreciated.
Thanks
Seems like you're attempting to to a direct comparison of String against another. For exact matches, you could do (
if (read.equalsIgnoreCase(filename)) {
of simply
if (read.startsWith(filename)) {
Try this :
While reading each line from the file, replace '\' by '\\'.
Then :
String lLine = "C\\Windows\\SysWOW64\\ntdll.dll";
Pattern lPattern = Pattern.compile("C\\\\Windows\\\\SysWOW64\\\\ntdll\\.dll");
Matcher lMatcher = lPattern.matcher(lLine);
if(lMatcher.find()) {
System.out.println(lMatcher.group());
}
lLine = "C\\Windows\\SysWOW64\\ntdll.dll (some developer stuff here...)";
lMatcher = lPattern.matcher(lLine);
if(lMatcher.find()) {
System.out.println(lMatcher.group());
}
The correct usage will be:
String filename = "C\\Windows\\SysWOW64\\ntdll.dll";
String file = filename.replace('\\', ' ');

Scanner's nextLine(), Only fetching partial

So, using something like:
for (int i = 0; i < files.length; i++) {
if (!files[i].isDirectory() && files[i].canRead()) {
try {
Scanner scan = new Scanner(files[i]);
System.out.println("Generating Categories for " + files[i].toPath());
while (scan.hasNextLine()) {
count++;
String line = scan.nextLine();
System.out.println(" ->" + line);
line = line.split("\t", 2)[1];
System.out.println("!- " + line);
JsonParser parser = new JsonParser();
JsonObject object = parser.parse(line).getAsJsonObject();
Set<Entry<String, JsonElement>> entrySet = object.entrySet();
exploreSet(entrySet);
}
scan.close();
// System.out.println(keyset);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
as one goes over a Hadoop output file, one of the JSON objects in the middle is breaking... because scan.nextLine() is not fetching the whole line before it brings it to split. ie, the output is:
->0 {"Flags":"0","transactions":{"totalTransactionAmount":"0","totalQuantitySold":"0"},"listingStatus":"NULL","conditionRollupId":"0","photoDisplayType":"0","title":"NULL","quantityAvailable":"0","viewItemCount":"0","visitCount":"0","itemCountryId":"0","itemAspects":{ ... "sellerSiteId":"0","siteId":"0","pictureUrl":"http://somewhere.com/45/x/AlphaNumeric/$(KGrHqR,!rgF!6n5wJSTBQO-G4k(Ww~~
!- {"Flags":"0","transactions":{"totalTransactionAmount":"0","totalQuantitySold":"0"},"listingStatus":"NULL","conditionRollupId":"0","photoDisplayType":"0","title":"NULL","quantityAvailable":"0","viewItemCount":"0","visitCount":"0","itemCountryId":"0","itemAspects":{ ... "sellerSiteId":"0","siteId":"0","pictureUrl":"http://somewhere.com/45/x/AlphaNumeric/$(KGrHqR,!rgF!6n5wJSTBQO-G4k(Ww~~
Most of the above data has been sanitized (not the URL (for the most part) however... )
and the URL continues as:
$(KGrHqZHJCgFBsO4dC3MBQdC2)Y4Tg~~60_1.JPG?set_id=8800005007
in the file....
So its slightly miffing.
This also is entry #112, and I have had other files parse without errors... but this one is screwing with my mind, mostly because I dont see how scan.nextLine() isnt working...
By debug output, the JSON error is caused by the string not being split properly.
And almost forgot, it also works JUST FINE if I attempt to put the offending line in its own file and parse just that.
EDIT:
Also blows up if I remove the offending line in about the same place.
Attempted with JVM 1.6 and 1.7
Workaround Solution:
BufferedReader scan = new BufferedReader(new FileReader(files[i]));
instead of scanner....
Based on your code, the best explanation I can come up with is that the line really does end after the "~~" according to the criteria used by Scanner.nextLine().
The criteria for an end-of-line are:
Something that matches this regex: "\r\n|[\n\r\u2028\u2029\u0085]" or
The end of the input stream
You say that the file continues after the "~~", so lets put EOF aside, and look at the regex. That will match any of the following:
The usual line separators:
<CR>
<NL>
<CR><NL>
... and three unusual forms of line separator that Scanner also recognizes.
0x0085 is the <NEL> or "next line" control code in the "ISO C1 Control" group
0x2028 is the Unicode "line separator" character
0x2029 is the Unicode "paragraph separator" character
My theory is that you've got one of the "unusual" forms in your input file, and this is not showing up in .... whatever tool it is that you are using to examine the files.
I suggest that you examine the input file using a tool that can show you the actual bytes of the file; e.g. the od utility on a Linux / Unix system. Also, check that this isn't caused by some kind of character encoding mismatch ... or trying to read or write binary data as text.
If these don't help, then the next step should be to run your application using your IDE's Java debugger, and single-step it through the Scanner.hasNextLine() and nextLine() calls to find out what the code is actually doing.
And almost forgot, it also works JUST FINE if I attempt to put the offending line in its own file and parse just that.
That's interesting. But if the tool you are using to extract the line is the same one that is not showing the (hypothesized) unusual line separator, then this evidence is not reliable. The process of extraction may be altering the "stuff" that is causing the problems.

Categories

Resources