Issues with path for java.io.File - java

I am getting file path in eclipse plugin using org.eclipse.swt.widgets.FileDialog and saving the path in XML files.
In web.xml , path is stored as below (I can't change backsladh to forwardslash or escape backslash since the value is coming from SWT FileDialog)
<init-param>
<param-name>filePath</param-name>
<param-value>c:\new\demo\next\version.txt</param-value>
</init-param>
In my filter , i have below code in init() method but am not able to get File reference due to special characters
String filePath = filterConfig.getInitParameter("filePath");
// Tried filePath.replace('\\','/') --> Didnot work since \n is a single character
File f = new File(path)

i could not get the actual path since \n is considered as new line.
That suggests that whatever's reading the file is assuming escaping which simply isn't the case.
Unfortunately, you haven't told us what code is used to write the data or the code used to read the data. Is it under your control in either path?
Basically you need to be escaping in the same way as you unescape - so either you can escape c:\new\demo\next\version.txt to c:\\new\\demo\\next\\version.txt when you're writing the data, or you can remove the code which tries to unescape when you're reading the data.
Note that if you literally tried:
string.replace('\\', '/');
then that certainly won't help at all - as you're ignoring the return value. If you tried
string = string.replace('\\', '/');
then that should have performed the relevant replacements, but you didn't say where you were trying to do that, or in what way it didn't work.
I would actually treat the forward vs back-slashes as a red herring here: fundamentally you need to escape in the same way as you unescape. Replacing backslashes with forward slashes may help for filenames, but you'll just get problems elsewhere in cases where you can't just perform that replacement.

I am getting file path in eclipse plugin using
org.eclipse.swt.widgets.FileDialog and saving the path in XML files.
In web.xml , path is stored as below (I can't change backsladh to
forwardslash or escape backslash since the value is coming from SWT
FileDialog)
The SWT File Dialog does not write web.xml files. You are doing that, so you can fix the backslashes. Change them to forward slashes.
I have below code in init() method but am not able to get File
reference due to special characters
that did not work because \n is considered a single character [from one of your comments]
That implies that the data is wrong in the web.xml file. Nothing you can do in code can fix that. This is not a coding question. You don't need to process backslashes in Java. The compiler already does that, and so in this case did the XML parser in the web-app container. You need to get the file format correct up front.

Related

Directorial problems using Java FileReader

I was following a youtube tutorial explaining the FileReader method and how you had to have a .txt file to read from.
So i created a textfile called JavaText with the directory:
"C:\Users\Computer\Desktop\JavaText.txt"
However eclipse is having problems with the backslashes since they are reserved for e.g "tab" = \t and "new line" = \n
doublechecking the tutorial I was looking, at the FileReader directory the youtuber was using only had slashes "/" and gave no erreros.
I changed my backslashes into regular slashes but now it gave me an error that it couldn't find the file. I suspect I somehow need to specify that the backslashes are indeed part of a String and not to be used for some sort of command but I don't really know how or even if that's 100% the issue.
To clarify I am using Windows 7 and latest version of eclipse.
In order to use a backslash in a string literal you must also escape it as \\:
String file = "C:\\Users\\Computer\\Desktop\\JavaText.txt";
Usually Java also accepts forward slashes as file separator, so you should check if the file does not exist when the program could not find it.

How to escape forward slash in java so that to use it in path

I am trying to escape forward slash in String which can be used in path using Java.
For example: String:: "Test/World"
Now I want to use above string path.At the same time I have to make sure that "Test/World" will come as it is in path. Sorry if its duplicate but I couldn't find any satisfactory solution for this.
My purpose is to use above string to create nodes in Zookeeper.
Example:
If I use following string to create node in Zokkeeper then I should get "Test/World" as a single node not separate. Zookeeper accepts "/" as path separator which in some cases I dont require.
/zookeeper/HellowWorld/Test/World
Thanks
You should know about File.separator ... This is safer than \ or / because Linux and Windows use different file separators. Using File.separator will make your program run regardless of the platform it is being run on, after all, that is the point of the JVM. -- forward slash will work, however, File.separator will make you end users more confident that it will.
And you don't need to escape "/ ... you should also see the answer to this question
String fileP = "Test" + File.separator + "World";
In order to escape a character in Java use "\"
for example:
String strPath = "directory\\file.txt".
I believe you do not need to escape forward slashes such as: "/"
Let me rephrase your question. You are trying to create a node in zookeeper and it should be /zookeeper/HelloWorld/NodeName. But the last part "NodeName" is actually "Test/World", and you are looking for ways to escape "/" so the node name can be "Test/World".
I don't think it would work escaping the char, unless you tried with unicode.
Try \u002F which is the equivalent for /.
We are trying to solve exactly the same problem (using filesystem path as node name in zookeeper) a we haven't found a way how to have '/' in node name.
Solution would be either to replace '/' with some character, that cannot appear in your node name. For paths that would be '/' or '\0', which wont help us in this case.
Other possibility is to replace '/' with string of characters allowed in node name, e.g. "Test/World" -> "Test%#World", "Test%World" -> "Test%%World" and add escaping/de-escaping to saving and loading.
If there is any more straightforward way, I'd love to hear it.
I don't know anything about Zookeeper. But it looks to me as though you're trying to keep a list of strings like "zookeeper", "HellowWorld", "Test/World", that you then want to use either to create Zookeeper nodes or to create a pathname in a file system. (I'm assuming that if you're working with a file system, you're going to have a subdirectory Test and a file or subdirectory World in the Test subdirectory. If you're actually trying to create a single file or directory named Test/World, give up. Both Linux and Windows will fight with you.)
If that's the case, then don't try to represent the "path" as a simple String that you pass around in your program. Instead, represent it as a String[] or ArrayList<String>, and then convert it to a filesystem path name only when you need a filesystem path name. Or, better, define your own class with a getFilesystemPath method. Converting your list of node names to a pathname String too early, and then trying to reconstruct the list from the String later, is a poor approach because you throw away data that you need later (in particular, you're throwing away information about which / characters are separators and which ones are part of node names).
EDIT: If you also need a single path name for Zookeeper, as you mentioned in another comment, I can't help you since I don't know Zookeeper and haven't found anything in a quick look at the docs. If there is a way to escape the slash for Zookeeper, then I still recommend defining your own class, with a getFilesystemPath method and a getZookeeperPath method, since the two methods will probably return different Strings in certain cases. The class would internally keep the names as an array or ArrayList.

Properties file escape a value

I've looking through How to escape the equals sign in properties files but didn't find my answer.
I have a Java Properties File that includes sets such as:
SOME_KEY = SOME_VALUE
This is normal. However, some of the values actually contain escape/control characters, such as URL's. This properties file is to be hand edited by a user on a rare occasion. I want the user to be able to simply paste in a URL and not worry about special rules, etc.
So I have this showing in my file now:
SOME_KEY = http://www.example.com/something.asp?some=
where some= is the base of dynamic URL where something after the = will cause the URL to respond differently.
From reading http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html it doesn't seem to make mention of needing to escape any escape/control characters after the first unescaped = or : is encountered, but I need/want to make sure.
I know that if my KEY had one of those characters present, then it would have to be escaped otherwise it'd be misread... such as:
SOME\=KEY = SOME_VALUE
Would make for a literal SOME=KEY as the key value.
In this above situation, excluding the obvious escaping of the KEY, is it necessary to hand-escape the values?
After the first = without escape, no.
If you use eclipse, you might want install the JBoss Tools Properties Editor. You not need to worry about escaping values ​​manually as you mention SOME=KEY or Unicode. However, the pluging escapes the characters to avoid reading and coding problems.
http://www.jboss.org/tools

Java on Windows: prevent '/' slash in file name from acting as a separator

I have to create a file based on a string provided to me.
For this example, let's say the file name is "My file w/ stuff.txt".
When Java creates the file using
File file = new File("My file w/ stuff.txt")
Even though the default windows separator is '\', it assumes that the '/' slash is a file separator. So a future call to file.getName() would return " stuff.txt". This causes problems for my program.
Is there any way to prevent this behaviour?
According to this Wikipedia page, the Windows APIs treat / as equivalent to \. Even if you somehow managed to embed a / in a pathname component in (for example) a File object, the chances are that Windows at some point will treat it as a path separator.
So your options are:
Let Windows treat the / as it would normally; i.e. let it treat the character as a pathname separator. (Users should know this. It is a "computer literacy" thing ... for Windows users.)
As above, but with a warning to the user about the /.
Check for / AND \ characters, and reject both saying that a filename (i.e. a pathname component) cannot contain pathname separators.
Use some encoding scheme to encode reserved characters before attempting to create the files. You must also then apply the (reverse) decoding scheme at all points where you need to show the user their "file name with slashes".
Note: if the user can see the actual file paths (e.g. via a command shell) you can't hide the encoding / decoding from them. Arguably, that is worse than the "problem" you were trying to solve in the first place.
There is no escaping scheme that the Windows OS will accept for this purpose. You would need to use something like % encoding; e.g. replace / with %2F. Basically you need to "hide" the slash character from Windows by replacing it with other characters in the OS-level pathname!
The best option depends on details of your application; e.g. whether you can report problems to the person who entered the bogus filename.
If a string is being provided to you (from an external source), it doesn't sound like you can prevent that string from containing certain characters. If you have some sort of GUI to create the string, then you can always restrict it there. Otherwise, whatever method is creating your file should check for a slash and either return an error or handle it as you see fit.
Since neither forward nor backward slashes are allowed in windows file names, they should be cleaned out of the Strings used to name files.
Well, how could you stop it being a folder separator? It is a folder separator. If you could just decide for yourself what was and what wasn't a folder separator, then the whole system would come crashing down.

Error when using Runtime.getRuntime().exec method to invoke an exe, if exe path has non-english chars

I am using Runtime.getRuntime.exec() Method to invoke an exe. The problem what I face with this method is that when I pass some exe path (c:\JPN_char_folder\mypath\myexe.exe) with other language chars (ex.Japanese) "it's saying "System cannot find the file specified". Would you please suggest some ideas to get around this? I even tried passing that exe path after converting to UTF-8 as well, but still I could not solve this.
-Robert.
I don't think that Japanese characters are the issue; it's the c: drive.
You need to write it this way:
String path = "c:\\\JPN_char_folder\\mypath\\myexe.exe";
See if that helps.
Most probably you have an encoding problem somewhere.
There are several steps here that the path value takes:
InstallAnywhere retrieves the path
InstallAnywhere puts it into a variable
Java reads the variable
Java puts it into a String
Java creates a java.io.File instance from String
Java runtime passes path (via File) to OS
Somehwere along this sequence something goes wrong with the path :-(.
It's hard to tell where; your best bet probably is to try and print out the value at every step along the path, to see where it goes wrong.
At least from inside Java, you should probably print out the String both as text, and as a list of Unicode code points (using String.codePointAt). That way you can see the real data Java uses.
Another approach:
Print out the value Java gets from InstallAnywhere (as text & as codepoints, as above)
Try to put the path into your Java program as a String literal, and fiddle until you can open the file that way. Then print that String as well.
Now you can compare the two results; that should give you an idea where the path gets messed up.
Note:
Does the path contain characters outside the Basic Multilingual Plane (BMP)? Java handles these a bit awkwardly, so you need to pay extra attention. Maybe you can check this first.
Even if you're using Windows, you can use slashes when specifying directories. This will help you with escaping backslash hell.
For example, on my system, 7z is located in directory c:\Program Files\7-Zip\.
Executing this
File file = new File("c:/Program Files/7-Zip/7z.exe");
if(file.exists()) {
System.out.println(file.getAbsolutePath());
}
Results in
c:\Program Files\7-Zip\7z.exe
being printed on the console.
I'd suggest you try using this idiom, i.e. check if .exe file exits before trying to execute it.

Categories