I've this brief snippet:
String target = baseFolder.toString() + entryName;
target = target.substring(0, target.length() - 1);
File targetdir = new File(target);
if (!targetdir.mkdirs()) {
throw new Exception("Errore nell'estrazione del file zip");
}
doesn't mattere if I leave the last char (that is usually a slash). It's done this way to work on both unix and windows. The path is actually obtained from the URI of the base folder. As you can see from baseFolder.toString() (baseFolder is of type URI and is correct). The base folder actually exists. I can't debug this because all I get is true or false from mkdir, no other explanations.The weird thing is that baseFolder is created as well with mkdir and in that case it works.
Now I'm under windows.
the value of target just before the creation of targetdir is "file:/C:/Users/dario/jCommesse/jCommesseDB"
if I cut and paste it (without the last entry) in windows explore it works...
The path you provide is not a file path, but a URI.
I suggest you try the following :
URI uri = new URI("file://c:/foo/bar");
File f = new File(uri).
It looks, to me, as if the "file:/" at the beginning is the problem... Try getAbsolutePath() instead of toString().
The File constructor taking a String expects a path name. A path name is not an URI.
Remove the file:/ from the front of the String (or better yet, use getPath() instead of toString()) to get to the path you need.
Related
Is any difference? First solution has "new" and second hasn't. I see only this difference.
You should always use new File in this case.
(Also your second possibility will not work the way you use it here).
There are other cases where you for example only have a Path object and you'd like to convert it into a File. Then you would use the toFile method on the Path-Object to get a File back.
In your case you access the File, convert it into a Path and then back into a File, which isn't necessary at all.
For example if you have a Path and want the file from it:
//existing Path object
void receivePath(Path path) {
File = path.toFile();
}
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
}
I am using the new Path object of java 7 and I am running into an issue.
I have a file storage system with a base directory and I create my own relative path. In the end I want to store just this relative path somewhere. I am running into a problem with Path.relativize though.
I have two usecases.
1.
Path baseDir = Paths.get("uploads");
Path filename = Paths.get("uploads/image/test.png")
return baseDir.relativize(filename);
This returns a Path image/test.png, which is perfect.
However, usecase 2:
Path baseDir = Paths.get("uploads");
Path filename = Paths.get("image/test.png")
return baseDir.relativize(filename);
returns ../image/test.png. I just want it to return "image/test.png"
In the Path tutorial it says
In the absence of any other information, it is assumed that 2 Paths are siblings
What I want is to be able to detect that this is the case. In this case, I want to just return the filename and ignore the baseDir.
I currently solve it like this, but I was hoping there was a better way:
Path rootEnding = getRootDirectory().getName(getRootDirectory().getNameCount() - 1);
for (Path part : path) {
if (part.equals(rootEnding)) {
return getRootDirectory().relativize(path);
}
}
return path;
So my question is, is there any better way of checking this?
Try adding a normalize() after relativize(). It seems to intended to do exactly this (remove unnecessary .. and . ). Don't miss the caution about symlinks in the javadoc.
This isn't 100% equivalent to what you wrote above, but I think it does what you want. Basically, let baseDir be a relative path. Pretend that whatever baseDir is relative to is the root of the file system. Then allow filename to be either relative or absolute from this "simulated root".
What about:
if (filename.startsWith(baseDir)) {
filename = baseDir.relativize(filename);
}
I have get this exception. but this exception is not reproduced again. I want to get the cause of this
Exception Caught while Checking tag in XMLjava.net.URISyntaxException:
Illegal character in opaque part at index 2:
C:\Documents and Settings\All Users\.SF\config\sd.xml
stacktrace net.sf.saxon.trans.XPathException.
Why this exception occured. How to deal with so it will not reproduce.
A valid URI does not contain backslashes, and if it contains a : then the characters before the first : must be a "protocol".
Basically "C:\Documents and Settings\All Users\.SF\config\sd.xml" is a pathname, and not a valid URI.
If you want to turn a pathname into a "file:" URI, then do the following:
File f = new File("C:\Documents and Settings\All Users\.SF\config\sd.xml");
URI u = f.toURI();
This is the simplest, and most reliable and portable way to turn a pathname into a valid URI in Java. It should work on Windows, Mac, Linux and any other platform that supports Java. (Other solutions that involve using string bashing on a pathname are not portable.)
But you need to realize that "file:" URIs have a number of caveats, as described in the javadocs for the File.toURI() method. For example, a "file:" URI created on one machine usually denotes a different resource (or no resource at all) on another machine.
The root cause for this is file path contains the forward slashes instead of backward slashes in windows.
Try like this to resolve the problem:
"file:" + string.replace("\\", "/");
You must have the string like so:
String windowsPath = file:/C:/Users/sizu/myFile.txt;
URI uri = new URI(windowsPath);
File file = new File(uri);
Usually, people do something like this:
String windowsPath = file:C:/Users/sizu/myFile.txt;
URI uri = new URI(windowsPath);
File file = new File(uri);
or something like this:
String windowsPath = file:C:\Users\sizu\myFile.txt;
URI uri = new URI(windowsPath);
File file = new File(uri);
It needs a complete uri with type/protocol
e.g
file:/C:/Users/Sumit/Desktop/s%20folder/SAMPLETEXT.txt
File file = new File("C:/Users/Sumit/Desktop/s folder/SAMPLETEXT.txt");
file.toURI();//This will return the same string for you.
I will rather use direct string to avoid creating extra file object.
I had the same "opaque" error while passing a URI on the command line to a script. This was on windows. I had to use forward slashes, NOT backslashes. This resolved it for me.
it doesn't like spaces as well and it has to be / instead of \ or `\ or //
zipFilePath = "C:/test/v";
I'm a bit confused with all these new File I/O classes in JDK7.
Let's say, I have a Path and want to rename the file it represents. How do I specify the new name, when again a Path is expected?
Path p = /* path to /home/me/file123 */;
Path name = p.getName(); /* gives me file123 */
name.moveTo(/* what now? */); /* how to rename file123 to file456? */
NOTE: Why do I need JDK7? Handling of symbolic links!
Problem is: I have to do it with files whose names and locations are known at runtime. So, what I need, is a safe method (without exceptional side-effects) to create a new name-Path of some old name-Path.
Path newName(Path oldName, String newNameString){
/* magic */
}
In JDK7, Files.move() provides a short and concise syntax for renaming files:
Path newName(Path oldName, String newNameString) {
return Files.move(oldName, oldName.resolveSibling(newNameString));
}
First we're getting the Path to the new file name using Path.resolveSibling()
and the we use Files.move() to do the actual renaming.
You have a path string and you need to create a Path instance. You can do this with the getPath method or resolve. Here's one way:
Path dir = oldFile.getParent();
Path fn = oldFile.getFileSystem().getPath(newNameString);
Path target = (dir == null) ? fn : dir.resolve(fn);
oldFile.moveTo(target);
Note that it checks if parent is null (looks like your solution don't do that).
OK, after trying everything out, it seems I found the right method:
// my helper method
Path newName(Path oldFile, String newNameString){
// the magic is done by Path.resolve(...)
return oldFile.getParent().resolve(newNameString);
}
// so, renaming is done by:
oldPath.moveTo(newName(oldFile, "newName"));
If you take a look at Apache Commons IO there's a class called FileNameUtils. This does a ton of stuff wrt. file path names and will (amongst other things) reliably split up path names etc. I think that should get you a long way towards what you want.
If the destination path is identical to the source path except for the name of the file, it will be renamed rather than moved.
So for your example, the moveto path should be
/home/me/file456
If you can't get Java to do what you want with Unix I recommend Python scripts (run by your Java program). Python has get support for Unix scripting and it's not Perl :) This might sound inelegant to you but really in a larger program you'll benefit from using the right tool for the job.