How do I save a new path on File - java

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?

Related

FileNotFoundException while trying to open a File

I am trying to d file = new file (location) while location of file is absolute path with somethign like this : \\test\hold\REPO/TEST/Letter/123.pdf
I am getting file not found exception while files are there in this path. what could be going wrong? can i have path with both forward and backward slash?
String separator = System.getProperty("file.separator");
So location can be rewritten to
location=separator+"test"+separator+"hold"+separator +"REPO"+separator "TEST"+separator+"Letter"+separator+"123.pdf";
In this case no need to think about underlying OS
You need two slashes in a string literal to represent one in the filename. Try
"\\\\test\\hold\\REPO/TEST/Letter/123.pdf"
or better still
"//test/hold/REPO/TEST/Letter/123.pdf"
There is never a need to use a backslash in a filename in Java.
Try adding quotes around the filename.
You can write your code without single backward slashes.if you want to use back-word slashes use \\ instead of \ .A single backward slashes create a problem if you put it inside the String literal.So you can write you code in multiple ways to avoid your exceptions.
1) File f=new File("\\test/hold/REPO/TEST/Letter/123.pdf");
2) File f=new File("\\test\\hold\\REPO/TEST/Letter/123.pdf");
3) File f=new File("\\test\\hold\\REPO\\TEST\\Letter\\123.pdf");
4) File f=new File("/test/hold/REPO/TEST/Letter/123.pdf");
you can use :-
InputStream input = new URL("\\test\hold\REPO/TEST/Letter/123.pdf").openStream();
or
File file = new File(location);
where location=\\test\hold\REPO/TEST/Letter/123.pdf; and Check Using SOP statement whether URL is Call properly or not . hope it will help you to fine better solution

How to name File objects and their corresponding path strings in Java

Often times, I find myself creating two objects like these:
String pathString = "/foo/bar";
File path = new File(pathString);
Though variable naming is a fairly subjective issue, what's the most common naming convention for File objects and their corresponding absolute file path stored in a String?
I guess there is no naming convention. I would either take a look at the constructor argument of File and name it after that, e.g.
String pathname = "/foo/bar";
File file = new File(pathname);
Normally the file has a meaning in your application. So I would choose a name that describes it. E.g.
String errorLogFilepath = "/var/log/error.log";
File errorLogFile = new File(errorLogFilepath);
Do you need to idependently identify the path?
If not, Id suggest just using:
File path = new File("/foo/bar");
Similarly, pass around File objects, not string paths.
If you are not reusing this path for further reference in the code , suggest you to initialize the file by passing an arguement. eg
File file = new File("/foo/bar");
This will prevent the creation of an extra string variable.
I always use double backslash and I've never have problem with that:
File outputfile = new File("c:\\Selenium\\workspace\\....\\input.txt");

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

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.

File object with white space in directory name

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?

Categories

Resources