I'm learning how we can access resources in java independently. So I have tried different ways as the listed below using File class.
System.out.println("File .: " + new File(".").getAbsolutePath());
System.out.println("File /: " + new File("/").getAbsolutePath());
System.out.println("File /.: " + new File("/.").getAbsolutePath());
System.out.println("File ./: " + new File("./").getAbsolutePath());
System.out.println("File ..: " + new File("..").getAbsolutePath());
System.out.println("File ../: " + new File("../").getAbsolutePath()); // why / not printed at the end?
System.out.println("File /..: " + new File("/..").getAbsolutePath());
System.out.println("File /../: " + new File("/../").getAbsolutePath()); // why / also not here
System.out.println("File //: " + new File("//").getAbsolutePath()); // why output is only \\ No path even
System.out.println("File ..//: " + new File("..//").getAbsolutePath()); // why not printed // at the end?
System.out.println("File //..//: " + new File("//..//").getAbsolutePath()); // why output \\.. only. No path even
Output is listed as below.
File .: D:\8th Semester\Java\CMDProjects\ClassPathTest\out\.
File /: D:\
File /.: D:\.
File ./: D:\8th Semester\Java\CMDProjects\ClassPathTest\out\. // I'm expecting / at the end too.
File ..: D:\8th Semester\Java\CMDProjects\ClassPathTest\out\..
File ../: D:\8th Semester\Java\CMDProjects\ClassPathTest\out\.. // same above question
File /..: D:\..
File /../: D:\.. // same above question
File //: \\ // Here why D:\ path not printed?
File ..//: D:\8th Semester\Java\CMDProjects\ClassPathTest\out\..
File //..//: \\.. //strange same above.
Then I tried same things with class's getResource() method. It works same as expected but on the last three lines I found exception by checking one by one Why?
URL dot = Test.class.getResource(".");
URL dotS = Test.class.getResource("./");
URL S = Test.class.getResource("/");
URL Sdot = Test.class.getResource("/.");
URL ddot = Test.class.getResource("..");
URL ddotS = Test.class.getResource("../");
URL sdd = Test.class.getResource("/..");
URL sdds = Test.class.getResource("/../");
URL ss = Test.class.getResource("//");
System.out.println("getR .: " + dot.toString());
System.out.println("getR /:" + S.toString());
System.out.println("getR /.:" + Sdot.toString());
System.out.println("getR ./:" + dotS.toString());
System.out.println("getR ..:" + ddot.toString());
System.out.println("getR ../:" + ddotS.toString());
// System.out.println("getR /..:" + sdd.toString()); // Exception Here
// System.out.println("getR /../:" + sdds.toString()); // Exception Here
// System.out.println("getR //:" + ss.toString()); // Exception Here
I would like to ask Why class's method getResource() throws NullPointer exception? and why the above File's output is different? see the top code where I wrote // why?
I'm using Windows 10.
As I already mentioned, I'm learning resource accessing different ways. Then if you have any useful links please share that too.
The null pointer exception is because Test.class.getResource() is returning null for those last three path strings. This happens whenever the indicated resource could not be found. For security reasons, Java code isn't allowed to access (or even know about) resources outside the class path. The path "/" maps to the root directory of the class path used to load class Test. It looks from your output that this is D:\8th Semester\Java\CMDProjects\ClassPathTest (or possibly D:\8th Semester\Java\CMDProjects\ClassPathTest\out; you don't report the output from the second part of your experiment).
As to why the trailing slash disappears from your file paths, that's part of how File#toString() is supposed to work. According to the docs, File#toString() returns the same string as File#getPath(). The docs for that method, in turn, say:
The resulting string uses the default name-separator character to separate the names in the name sequence.
Note that the name separator character is used to separate the names. It doesn't preserve trailing separators (that don't separate anything).
I'm not sure why the absolute path for "//..//" is "\\..". (Or, for that matter, why "//.." results in "\\". It's easy to understand why the trailing // is suppressed; those are name separator characters that don't separate anything. On my Mac the output for both of those is "/..". This behavior is obviously OS-dependent. I suspect that on Windows, the leading "//" represents a network path to a computer and the computer name is just absent.
Related
I have tried the following Java code I found with the use of BufferedReader class to read a stream of text.
public void editTexts(Path inputFile) throws IOException{
BufferedReader reader = Files.newBufferedReader(inputFile)){
// ----------
}
}
As in this code, the parameter type is mentioned as Path. I have a problem with passing arguments into that.
I want to know how can I pass arguments to the Path parameter type?
Let's say, you have a Path pointing to a directory, let's say the root directory of a Windows machine.
You can create that Path like this:
Path rootPath = Paths.get("C:\\");
If you now want to pass an argument like a file name, then you can do this
String fileName = "some_file.txt";
Path filePath = rootPath.resolve(fileName);
To make sure everything is working correctly, print the absolute paths of both Paths
System.out.println("root path is " + rootPath.toAbsolutePath().toString());
System.out.println("path to the file in root is " + fileInRootPath.toAbsolutePath().toString());
You can perform checks on those Paths since having them created in memory doesn't necessarily mean the paths are correct and the file system objects are present.
// check if the path exists
if (Files.exists(filePath)) {
// check if the path points to a regular file (not a directory or symbolic link)
if (Files.isRegularFile(filePath)) {
System.out.println(filePath.toAbsolutePath().toString()
+ " exists and is a regular file");
} else {
System.out.println(filePath.toAbsolutePath().toString()
+ " exists, but is not a regular file");
}
} else {
System.out.println(filePath.toAbsolutePath().toString()
+ " does not exist");
}
Try Paths.get(...).
Path path = Paths.get("root", "sub", "subsub", "InterestingFile.txt");
I am uploading one file that is kind of multipart. I want this file to save with different name.
tried with renameTo method but did not work.
tried moveto but did not work
below is my code
here graphic is multipart file
String picName = graphic.getOriginalFilename();EN_LENGTH) + "." + graphic.getContentType();
Path dirLocation = Paths.get(dirPath);
String newName = CommonUtil.getToken(Constants.STANDRAD_TOKEN_LENGTH) + "." + graphic.getContentType();
try {
InputStream is = graphic.getInputStream();
Files.copy(is, dirLocation.resolve(picName), StandardCopyOption.REPLACE_EXISTING);
boolean a = new File(dirLocation+picName).renameTo(new File(dirLocation+newName));
for security reasons I want it to save with different name.
Solved the issue by correcting the filename. The file name which I was generating randomly was not correct. it had some slash etc.
I'm trying to create an empty .properties file on my filesystem using java.io.File.
My code is:
File newFile = new File(new File(".").getAbsolutePath() + "folder\\" + newFileName.getText() + ".properties");
if (newFile.createNewFile()){
//do sth...
}
It says that it's impossible to find the specified path.
Printing the Files's constructor's argument it shows correctly the absolute path.
What's wrong?
You can use new File("folder", newFileName.getText() + ".properties") which will create a file reference to the specified file in the folder directory relative to the current working directory
You should make sure that the directory exists before calling createNewFile, as it won't do this for you
For example...
File newFile = new File("folder", newFileName.getText() + ".properties");
File parentFile = newFile.getParentFile();
if (parentFile.exists() || parentFile.mkdirs()) {
if (!newFile.exists()) {
if (newFile.createNewFile()){
//do sth...
} else {
throw new IOException("Could not create " + newFile + ", you may not have write permissions or the file is opened by another process");
}
}
} else {
throw new IOException("Could not create directory " + parentFile + ", you may not have write permissions");
}
I think the "." operator might be causing the error not sure what you are trying to do there, may have misunderstood your intentions but try this instead:
File newFile = new File(new File("folder\\").getAbsolutePath() + ".properties");
Trivially I missed that new File(".").getAbsolutePath() returns the project's absolute path with the . at the end so my folder whould be called as .folder. Next time I'll check twice.
Hello there I want to create the directories and sub directories with the java.
My directory structure is starts from the current application directory, Means in current projects directory which looks like following...
Images
|
|+ Background
|
|+ Foreground
|
|+Necklace
|+Earrings
|+Etc...
I know how to create directory but I need to create sub directory I tried with following code what should be next steps ?
File file = new File("Images");
file.mkdir();
You can use File.mkdir() or File.mkdirs() to create a directory. Between the two, the latter method is more tolerant and will create all intermediate directories as needed. Also, since I see that you use "\\" in your question, I would suggest using File.separator for a portable path separator string.
Starting from Java 7, you can use the java.nio.file.Files & java.nio.file.Paths classes.
Path path = Paths.get("C:\\Images\\Background\\..\\Foreground\\Necklace\\..\\Earrings\\..\\Etc");
try {
Files.createDirectories(path);
} catch (IOException e) {
System.err.println("Cannot create directories - " + e);
}
This is a tricky solution (because I used only one path to go to the whole structure).
If you don't like tricky solutions, you can use 4 simple paths instead:
Path p1 = Paths.get("C:\\Images\\Background");
Path p2 = Paths.get("C:\\Images\\Foreground\\Necklace");
Path p3 = Paths.get("C:\\Images\\Foreground\\Earrings");
Path p4 = Paths.get("C:\\Images\\Foreground\\Etc");
and then call the createDirectories method for all of them:
Files.createDirectories(p1);
Files.createDirectories(p2);
Files.createDirectories(p3);
Files.createDirectories(p4);
You can create all parent directories by using File.mkdirs().
File.mkdirs() - Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.
You could do it with File#mkdirs() and something like,
// The "/" is cross-platform safe as a path-separator in Java.
// So is "\\" but that's twice the characters!
String path = createImages.getAbsolutePath() + "/Images";
File f = new File(path);
if (!f.isDirectory()) {
boolean success = f.mkdirs();
if (success) {
System.out.println("Created path: " + f.getPath());
} else {
System.out.println("Could not create path: " + f.getPath());
}
} else {
System.out.println("Path exists: " + f.getPath());
}
Per the linked Javadoc,
Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.
You can just use file.mkdirs(), it will create sub-directory.
String path = images + File.separator + Background + File.separator + Foreground + File.separator + Necklace + File.separator + Earrings ;
File file = new File( path );
file.mkdirs();
Adding up to #ROMANIA_engineer's answer..
I used Path.resolve() method to create sub-directories using variables lika DateTime and others:
private final Path root = Paths.get("target\\");
private final Path batchFilePath = Paths.get(root.resolve(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyymmdd_HHmmss"))).toString());
Files.createDirectory(root);
Files.createDirectory(batchFilePath);
And the result was:
directory/subdirectory example
I have written a short program that will find a file I have made and print some of its details. It executes all right, but it cannot detect the file size or if it is hidden or not. E.G.
file path: C:\temp\filetext.txt last modified: 0 file size: 0 Is file hidden?false
The file does exist in the temp folder on C. I'm not really sure what the problem is
public void Q1()
{
String fileName = "filetext.txt";
getFileDetails(fileName);
}
public void getFileDetails(String fileName)
{
String dirName = "C:/temp/";
File productsFile = new File(dirName + fileName);
long size = productsFile.length();
System.out.println("file path: " + productsFile.getAbsolutePath() + " last modified: " + productsFile.lastModified() + " file size: " + productsFile.length() + " Is file hidden?" + productsFile.isHidden());
}
File does not need a physical file to work with. Therefore your File object can exist even if the physical file it is supposed to represent does not exist/cannot be found. Check the JavaDoc for length() and lastModified(), they both return 0L in case for example the file does not exist. So make sure your File objects is linked to an existing file on your file system by calling file.exists() before calling the other methods.