I have my java code like below-
string folderName = "d:\my folder path\ActualFolderName";
File folder = new File( folderName );
folder.mkdirs();
So here as given directory path has space in it. folder created is d:\my, not the one I am expecting.
Is there any special way to handle space in file/folder paths.
You should us \\ for path in java. Try this code
String folderName = "D:\\my folder path\\ActualFolderName";
File folder = new File( folderName );
folder.mkdirs();
Or use front-slashes / so your application will be OS independent.
String folderName = "D:/my folder path1/ActualFolderName";
Unless you are running a really old version of Java, use the Path API from JDK7:
Path p = Paths.get("d:", "my folder path", "ActualFolderName");
File f = p.toFile();
It will take care of file separators and spaces for you automatically, regardless of OS.
Following alternatives should work in Windows:
String folderName = "d:\\my\\ folder\\ path\\ActualFolderName";
String folderName = "\"d:\\my folder path\\ActualFolderName\"";
You need to escape your path (use \\ in your path instead of \) and you also need to use String, with an uppercase S, as the code you posted does not compile. Try this instead, which should work:
String folderName = "D:\\my folder path\\ActualFolderName";
new File(folderName).mkdirs();
If you are getting your folder name from user input (ie.not hardcoded in your code), you don't need to escape, but you should ensure that it is really what you expect it is (print it out in your code before creating the File to verify).
If your are still having problems, you might want to try using the system file separator character, which you can get with System.getProperty(file.separator) or accesing the equivalent field in the File class. Also check this question.
You need to escape path seprator:
String folderName = "D:\\my folder path\\ActualFolderName";
File file = new File(folderName);
if (!file.exists()) {
file.mkdirs();
}
First of all, the String path you have is incorrect anyway as the backslash must be escaped with another backslash, otherwise \m is interpreted as a special character.
How about using a file URI?
String folderName = "d:\\my folder path\\ActualFolderName";
URI folderUri = new URI("file:///" + folderName.replaceAll(" ", "%20"));
File folder = new File(folderUri);
folder.mkdirs();
Related
I'm currently reading a txt file in Java, which is located in a package with the scanner object.
To receive the file location I use a quick and dirty method:
File currentDirectory = new File(new File(".").getAbsolutePath());
String location = currentDirectory.getAbsolutePath().replace(".", "")+"\\corefiles\\src\\filereadingexample\\";
Is there a better way of doing so?
I'd love to improve my code.
Greetings
J
Use a URL
URL resource = getClass().getResource("/path/to/text/file.txt");
As the path, since your text file is inside a package, use the package structure. For example, assume your file(myfile.txt) is inside
com.myproject.files
package, your path should be
"/com/myproject/files/myfile.txt"
(mind the leading slash. It's necessary)
Now you can create a File using the URL
new File(resource.getFile());
The "resource.getFile()" returns the absolute path to the file also.
Hope this helps
Get current diretory path
String currentDirPath = System.getProperty("user.dir");
String ohterPackages = currentDirPath + File.separator + "filereadingexample\\fileName.txt";
User home directory
String homePath = System.getProperty("user.home");
I have a URL that I get as below:
String jarFilePath = getClass().getProtectionDomain().getCodeSource().getLocation()
This would get me the complete path to the jar file. Now how do I jump one folder up and append some other path to it? For example., if the jarFilePath is something like:
c:/path/to/jar/file.jar
I want to jump one folder up and append another relative path like below:
c:/path/to/resources/path/to/resources/
Where the folders resources and jar are at the same directory level in the file system.
File f = new File("C:/path/to/jar/file.jar");
File dest = new File(f.getParentFile().getParentFile(), "resources/path/to/resources");
Just use the File-Object, that makes a lot of things easier:
import java.io.File;
String pathname = "c:/path/to/jar/file.jar";
File f = new File(pathname);
String p = f.getParent();
Try and use a File object:
File jarFile = new File(jarFilePath);
File newFolder = new File( jarFile.getParentFile().getParentFile(), "resources/path/to/resources");
If you want to use the path as a string, try using Apache Commons IO's FilenameUtils:
String resourcesPath = FilenameUtils.normalize( FilenameUtils.getPath(jarFilePath) + "/../resources/path/to/resources");
You have several ways.
You can split the path into it's elements and rebuild it until array.length -3 (-1 would be filename, -2 the last folder)
You could simple remove the file and append another ../ (which just means: "Go one directory back") (that would be something like this then: c:/path/to/jar/../resources/path/to/resources/)
You gould use a regex to get rid of the last folder and file. something like /[^/]+/[^/]+$
How do we actually discard last file from java string and just get the file path directory?
Random Path input by user:
C:/my folder/tree/apple.exe
Desired output:
C:/my folder/tree/
closest solution i found is from here . The answer from this forum only display last string acquired not the rest of it. I want to display the rest of the string.
The easiest and most failsafe (read: cross-platform) solution is to create a File object from the path.
Like this:
File myFile = new File( "C:/my folder/tree/apple.exe" );
// Now get the path
String myDir = myFile.getParent();
Try that:
String path = "C:/my folder/tree/apple.exe";
path = path.substring(0, path.lastIndexOf("/")+1);
I have two File Object oldFile and newFile and I would like to exchange the corresponding file names. So I rename oldFile to a tmpFile name first. I get the oldFile's absolute path and append ".bak" for it:
String tmpFile = oldFile.getAbsolutePath().toString()+".bak";
oldFile.renameTo(new File(tmpFile));
The problem is that tmpFile contains the raw string of path,while the constructor of File class treat the '\' as the escape.So the tmpFile may be "D:\oldfile.java.bak",however what the constructor need is
new File("D:\\oldfile.java.bak");
How can I deal with it?
The constructor of File does NOT treat \ as escape. You need to escape \ with \ in a string literal. The String literal "\\" contains a single character: '\'.
String path = "D:\\oldFile";
System.out.println(path); // prints D:\oldFile
File f = new File(path);
System.out.println(f.getAbsolutePath()); // prints D:\oldFile
You have to escape the escapes with .replace("\", "\\") but if you have to do that then realize you don't have to use \ on Windows. Java supports / just as fine and it doesn't have these problems. You can do replace("\", "/") and it works just as well.
You also need to read and understand how to create new files in Java. File.createNewFile() is required to be called. Just creating a File object with the constructor doesn't actual create a file on the filesystem nor does it guarantee that a file at that location exists.
Is it possible to move to a directory one level down in Java?
For example in command prompt:
C:\Users\foo\
I can use cd.. to go to:
C:\Users\
Is it possible to do this in Java, because I'm getting a directory using System.getProperty("user.dir"); however that is not the directory I'd want to work at, but rather 1 level down the directory.
I have thought of using the Path class method; subpath(i,j), but if the "user.dir" were to be changed to another directory, then the returned subpath would be different.
The File class can do this natively.
File upOne = new File(System.getProperty("user.dir")).getParentFile()
http://docs.oracle.com/javase/6/docs/api/java/io/File.html#getParentFile%28%29
On my system, the ".." is a valid component of a path.
Here is an example.
File file;
String userDir = System.getProperty("user.dir");
file = new File(userDir);
System.out.println(file.getCanonicalPath());
file = new File(userDir+"/..");
System.out.println(file.getCanonicalPath());
Output is:
C:\ano\80g\workaces\_JAV_1.0.0\CODE_EXAMPLE
C:\ano\80g\workaces\_JAV_1.0.0
As the previous answers have pointed out, you can do this using File. Alternatively, using the Java 7 NIO classes, as you appear to be doing, the following should do the same:
Paths.get(System.getProperty("user.dir") + "/..").toRealPath();
Note that "/" is a valid directory separator on the Windows file system as well (though I tested this code on Linux).
private static void downDir(int levels) {
String oldPath = System.getProperty("user.dir");
String[] splitedPathArray = oldPath.split("/");
levels = splitedPathArray.length - levels;
List<String> splitedPathList = Arrays.asList(splitedPathArray);
splitedPathList = splitedPathList.subList(0, levels);
String newPath = String.join("/", splitedPathList);
System.setProperty("user.dir", newPath);
}
Should work. For the levels, just specify 1.