File object with white space in directory name - java

I am trying to list the number of files in a directory. But I am unable to get so and I suspect it has got to do with the white space in the parent directory names.
What I am doing is in a .properties file I set the value as -
dir.loc=H:/Main/dir one/dir - two/dir3/dir four
dir.name=Run
Now in a jave file I set these values to String variables as -
String s1 = properties.getProperty("dir.loc");
String s2 = properties.getProperty("dir.name");
I create a File object as -
File f = new File(s1, s2);
File[] fList = f.listFiles();
Now here the fList is null;
The H drive is on another remote machine and I reckon the java program tries to locate the 'Run' directory locally rather than finding it on H drive and because it does not find 'Run' the list return null.
When I tried in a simple java class as -
File f = new File("H:/Main/dir one/dir - two/dir3/dir four", "Run");
then I do get the result with f.listFiles().length;
So I guess it might have to do something with extracting the value from properties file and assigning it to a String variable.
Am I correct in my assumption?
What could be possible solution to this problem?

Yes, you are right. Values are screwed up when reading them from the properties file.
Do this instead:
dir.loc="H:/Main/dir one/dir - two/dir3/dir four"

Ok, I found the solution for my problem, quite simple actually.
I did the following -
In properties file -
dir.loc=H:/Main/dir one/dir - two/dir3/dir four/Run
In a config java file -
String s1 = properties.getProperty("dir.loc");
In my java program -
File tempF = new File(s1);
File dirLoc = new File(tempF.getAbsolutePath());
dirLoc.listFiles().length; gives out a number.
The comment by #barti_ddu about getAbsolutePath() got me into bit of thinking about may be using that.
Is anything wrong with this solution or is not quite a decent one?
Thank you all.

It looks like you simply need to trim the value of your properties.
In the code you have shown, the
dir.loc=H:/Main/dir one/dir - two/dir3/dir four
has trailing spaces.
Does this:
String s1 = properties.getProperty("dir.loc").trim();
String s2 = properties.getProperty("dir.name").trim();
fix it?

Related

Directory and Filename Concatenating does NOT work

I am working in Netbeans IDE.
What I want to do is:
Get The directory of the Current Java Application (Ex: "F:\PadhooWorld")
Join a file name to it. (Ex: "\Somestuff.txt")
Check if that File exists (Ex: "F:\PadhooWorld\Somestuff.txt")
Do a if.. else activity
When I tam trying to Join Directory + Filename, it is throwing lots of error messages like Path cannot be converted to string etc . Searching the net the whole day, doesn't yield any simple usable solution
Please specify a very simple solution.
EDIT
I have only 2 lines of code as yet
String AppPath = System.getProperty("user.dir");
String fullPath = AppPath + "\Surabhi.txt";
The First Line resolves alright
The Second line (I tried different variations) No Luck. It is underlined in red. Error hints say stuffs like 'Path cannot be converted to string'..
I cannot RUN the code.
It sounds like you're overthinking it. You can just create a File object with the file name you want (the path to the current directory will be used by default) and then call exists() on it:
File f = new File("filename.txt");
System.out.println(f.getAbsolutePath()); //Just for debug if you want to check the path
if(f.exists()) {
//Whatever
}
Alternatively, if you want to specify the path as well as the file name:
String AppPath = System.getProperty("user.dir");
String fileName = "Surabhi.txt";
File f = new File(AppPath, fileName); //f.getAbsolutePath() will give the concatenated name
if(f.exists()) {
//Whatever
}

How do I save a new path on File

I am making a simple MP3 player and have imported mp3 files from a certain directory. I want to change the path to have double backslashes, however it's not registering.
matchingFiles = dir.listFiles(textFilter);
for(int i = 0; i<matchingFiles.length; i++){
String s = matchingFiles[i].toString();
String t = s.replace("\\", "\\\\");
matchingFiles[i] = new File(t);
System.out.println(matchingFiles[i]);
fileList.add(matchingFiles[i]);
}
The print gives single backslashes, while t has double. File.renameTo() didn't seem to work either, so I'm wondering how to change the path in an existing File.
The File class aims at representing system paths in its own way, well, the system way. In other words, File understands paths as folders seperated by \, not \\. You can't change that. The question is, why would you?

Concatenating Strings in Java generates between-in null

This question looks like very similar to: Concatenating null strings in Java
But my issue is some different.
I want to build an absolute path to a file:
String path = properties.get("path"); // returns /home/myuser/relativepath/ , ends with bar /
String file = currentFile; // currentFile values "file.txt"
String result = path + file; // this results in /home/myuser/relativepath/nullfile.txt
Why is there than 'null' text? That's the reason my application does not work now.
I have review it in Windows and Linux.
In Windows it works perfectly.
In Linux, I have this issue.
I uploaded properties file and then, edited with vi command.
Maybe is this the problem?
Shouldn't I use this way to generate an absolute path, and use File.Separator property in Java?
EDIT: I have post my final right answer with detailed steps. I hope it would be useful.
My bet (though I have not seen Java behave this way) is there's a null-ish character (such as a carriage return) of some sort in your properties file which Windows handles at the OS level so Java/Properties doesn't see it.
As a first pass, try printing the length and last few characters of your path string, e.g.:
for(int i = Math.max(0, path.length()-5); i < path.length(); i++) {
System.out.print(path.charAt(i)+":"+((int)path.charAt(i))+" ");
}
System.out.println(path.length());
Willing to bet the last character, on Linux, is not what you'd expect. The right fix would then be to clean up your properties file so that it's compatible on both OSes.
Well, the complete and detailed steps to fix my issue are these (maybe any of them could not be necessary, but I prefer to write them all):
Create config file in Linux with vi, emacs, ... (not upload file from Windows).
Edit file with vi, emacs... At the end of each path, do not include directory separator character ( / ).
Check variables before contatenate them. Make sure they don't have any space and other unexpected character.
Concatenate variables with:
String result = path + File.separator + file;
I hope this would be useful. Thank you all for your suggestions.
Regards
What do you expect?
Yo´re doing a String result = path + result;
int a = 1 + a would be similar... don´t use a variable to init itself.
(That can´t be your code in the first place, if you´re getting this output.)
result is path+file :
String path = properties.get("path");
String file = currentFile;
String result = path + file;
^
change here
the result is: /home/myuser/relativepath/file.txt

Delete a file name with spaces in between

i read on several posts that we for deleting a file through java which has spaces in the name, i can use delete() method (Java 6). eg:
File f = new File("/mnt/test ex.txt");
f.delete();
but when I'm making a file object like this () :
StringBuilder fullFileName = "C:/Temp_Folder\week month.xlsx";
fileToRead = new File(fullFileName.toString());
fileToRead.delete();
I'm not able to do so and i get the following exception :
java.io.FileNotFoundException: "C:\Temp_Folder\week month.xlsx" (The filename, directory name, or volume label syntax is incorrect)
What am i missing here?
P.s. : I tried using quotes on the filename as well without success
fileToRead = new File('"'+fullFileName.toString()+'"');
Edit : I've edited the quotes on the stringBuilder (a type from my end). Actually the StringBuilder object is a parameter and we are appending objects to fetch the actual name. I just gave you the final declaration.
As far as week month.xlsx goes, that is the name of the file and not two different variables (which means the filename DOES have spaces in between; it could be something like
Name with spaces.xlsx
Thanks for the quick turnaround everyone.
You do NOT need a specific treatment for file names with spaces in Java -- or any other programming language with a file access API for that matter.
Do not mix Java with a command interpreter.
In your case, your File should be declared as:
new File("C:\\Temp_Folder\\name with spaces.xlsx")
and that's it.
If Java reports a FileNotFoundException then there is a problem. Unfortunately, the File API is broken and this exception can be thrown if the file exists but you cannot read it, for instance. Have a look at the complete stack trace.
Do yourself a favour: use Java 7 and the new Files API. With this API, exceptions actually make some sense -- and a delete operation will not "silently" fail either.
As to building the filename itself, you can for example use String.format():
final String filename = String.format("C:\\Temp_Folder\\%s %s.xlsx", month, week);
According to the exception:
java.io.FileNotFoundException: "C:\Temp_Folder\week month.xlsx"
You are looking for the following file:
"C:\Temp_Folder\week month.xlsx"
Note the quotes! This file does not exist.
You will have to modify your code to ensure that your file name does not include the surrounding quotes (not needed).
I.e. (Assuming java 6 here)
File file = new File("C:\\Temp_Folder\\week month.xlsx");
file.delete();
Note, the backslash is an escape character hence it is doubled in the string.

reconstructing a file path in java

I have a file path location as such:
Properties readProp = \\192.168.41.84\dev\config\dev\config.properties
how can I manipulate it so I remove the portion of config.properties
and replace it with test\config.properties
so the new Properties location would be:
Properties readProp = \\192.168.41.84\dev\config\dev\test\newconfig.properties
?
thanks for your time and effort
Make sure you escape any backslashes you have as you build the string.
String path = "\\\\192.168.41.84\\dev\\config\\dev\\config.properties";
System.out.println(path);
int lastBackSlash = path.lastIndexOf("\\");
//+1 to include lastBackSlash
String newPath = path.substring(0, lastBackSlash + 1) + "test" + path.substring(lastBackSlash);
System.out.println(newPath);
Prints
\\192.168.41.84\dev\config\dev\config.properties
\\192.168.41.84\dev\config\dev\test\config.properties
This article like this is also decent read. Treating paths as strings can be dangerous.
http://twistedoakstudios.com/blog/Post4872_dont-treat-paths-like-strings
However, if your careful, know what how your string functions behave(or look them up), and you don't have off by 1 errors... then treating the paths like strings should be pain free. But you will have no guarantee that the path is valid... while a path builder library would give you that assurance.

Categories

Resources