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.
Related
The return value of a value from getPath() from the File Class is something like this
"C:\Users\Daniel\Desktop\ASDF.mp3".
To use the Desktop class from java to play a file, the path would have to be fed into a file, with a path similar to
"C:\\Users\\Daniel\\Desktop\\ASDF.mp3"
Since the \ is a reserved character(From my understanding) to make a new file you must use a double backslash to dictate that it is a file. My problem is that when I try to get the path I need to transform it into a double slash version. The .replaceAll() method doesn't allow for '\' since it's a reserved character but the .replace() method does.
To work around this would I just have to loop through to find all instances and replace them one at a time? Or is there a simpler work around? Also I would like to know if I am receiving this error due to it being a reserved character, or if I am completely wrong.
The two strings above are actually exactly the same.
When Java or other language outputs a string it only displays one slash '\', but when you are typing the string into double quotes you need double backslash '\\' so the Java parser knows it's one slash. Backslash is used for many other escape characters, so this is only way parser will know.
(Even when typing this answer, I needed 4 backslashes to make only 2!
the file is aa.txt in the directory /home/user
the code I wrote is
input=new FileInputStream("//home//user//aa.txt");
but the program can not open the file. when I run it on windows, it works
what is the format of the path in fedora to be read correctly by the program???
Since \ is used as an escape character (for instance \n = new line and \t = tab) we need to write \\ to mean a single \ when placing this character in a String.
This issue does not exist with a forward slash /
For linux directories the forward slash / is used; windows uses the backslash. Writing OS independent code could be a pain, but it's not an issue. Just use the forward slash when dealing with files and Java automagically translates it for you to the correct OS specific format.
For instance C:/Users/Owner/Documents becomes C:\Users\Owner\Documents on windows.
Or you could write "C:\\Users\\Owner\\Documents" but the simple forward slash format looks simpler.
You don't have to escape the / (slash) character.
So you basically need this:
input=new FileInputStream("/home/user/aa.txt");
However, it is far wiser to use File.separator instead:
input=new FileInputStream(File.separator+"home"+File.separator+"user"+File.separator+"aa.txt");
I'm reviewing my code
My Java application runs on Windows and Unix using Java 6 and manipulates files. I know I can use the file.separator to get the file separator in a filesystem independent way but if I ever use specify windows file separator char directly because is the '\' which is also the Java escape character I can't do manipulation of the file path. So in my code I've always stored the filepath in unix notation by replacing \' with '/' ,and these paths are stored in a database so I thought there was an escaping problem there as well. So I was under the illusion that trying to use file.separator would also fail because it would return '\' rather than '\' but now realise only need \ if I actually explicity specify it myself in quotes.
Now I'm thinking this is all unnecessary and as long as I always use file.separator I don't need to do this conversion, am I right ?
EDIT:
Found a case where it seems to be a problem
"C:\Fred\test1.txt".split("\\\\");
"C:\Fred\test1.txt".split(System.getProperty("file.separator"));
if I want to split the string by \ I have double it up because \ has special meaning in a regular expression, so the line using file.separator fails with
java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
^
at java.util.regex.Pattern.error(Pattern.java:1713)
at java.util.regex.Pattern.compile(Pattern.java:1466)
at java.util.regex.Pattern.<init>(Pattern.java:1133)
at java.util.regex.Pattern.compile(Pattern.java:823)
but on unix no such requirement the corresponding '/' should not be escaped
EDIT 2:
This question has been asked before Splitting filenames using system file separator symbol the solution boils down to using Pattern.quote() around the input or trying to use file methods rather regular expressions. Both a little uneccessary I would prefer it if files could be viewed ins a system independent way, I not that Path in Java 7 has the same problem.
EDIT 3:
Also seeing a problem with reading/writing from db, created a separate question on that Storing Windows Path in Database and retrieving with Hibernate using java
Yes, you are right - if you use File.Seperator you dont need any additional escaping because in Windows it is already escaped for you. From the java documentation.
separatorChar
public static final char separatorChar
The system-dependent default name-separator character.
This field is initialized to contain the first character of the value of the system property file.separator.
On UNIX systems the value of this field is '/';
on Microsoft Windows systems it is '\\'.
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.
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.