get a file path - java

Is there a way to get the full path for a file exists on the computer ?
For example , I want to get the full path for a file in a folder on desktop
I tried using :
File f = new File("help.chm");
String f2=f.getAbsolutePath();
f3=f3.replaceAll("\\\\","/" );
System.out.println("Path:"+f3);
but it gave me the path of the project like this:
C:/Users/toshiba/Documents/NetBeansProjects/test/help.chm
although the file is not located there .

If you create a file using new File("filename") which is the relative path, you cannot get the absolute path of the file using file.getAbsolutePath(), because the relative path is build according to the default user home directory or the JVM path.
Take a look at Java Doc: -
A pathname, whether abstract or in string form, may be either absolute
or relative. An absolute pathname is complete in that no other
information is required in order to locate the file that it denotes.
A relative pathname, in contrast, must be interpreted in terms of
information taken from some other pathname. By default the classes in
the java.io package always resolve relative pathnames against the
current user directory. This directory is named by the system property
user.dir, and is typically the directory in which the Java virtual
machine was invoked.
So, to get the absolute path for this case, you would actually have to write the path yourself. Get the absolute path till the directory where you saved the file, and append the file name to it.

Since the other answers do not cover your question, here is my comment:
To get a file's path, you first need to tell your java program where it is or how to find it.
For your specific example you can get the desktop path using: System.getProperty("user.home") + "/Desktop"; then you can search through folders on your desktop for a matching file name.
Read here to learn how to search for files: docs.oracle.com/javase/tutorial/essential/io/find.html

A File is a representation of a file path, not necessarily an existent file on disk - ie the file doesn't have to exist on disk for a File object to be not null.
That's why there's the File.exists() method.

The path "help.chm" will be relative to the directory from which you started the JVM, which in your case appears to be C:/Users/toshiba/Documents/NetBeansProjects/test/
To get a path to the desktop, you need to use the absolute path of the desktop directory in Windows, which will be something along the lines of C:/Users/toshiba/Desktop/help.chm

You are attempting to read the file from (default folder)
C:/Users/toshiba/Documents/NetBeansProjects/test/
File doesn't exist but the would-be-file's path will be
C:/Users/toshiba/Documents/NetBeansProjects/test/
If you read the file from where it really is:
File f = new File("C:/Users/toshiba/Desktop/help.chm");
You will see that exists() returns true.
System.out.println(f.exists());
Then:
String f2=f.getCanonicalPath();

Related

Scanner cannot find (correct) file path

I'm programming in Java with IntelliJ and have been trying to use the Scanner class to read the file. Even with the correct path, I still get a "No such file or directory" error. Does anyone have any suggestions?
My working directory is /Users/kevinliu/Desktop/test
Here is a picture of how the project is set-up.
Are you trying to create a swing/console application using maven?
If yes, maven is not able to find the source. You have to add it on the pom file. See here on how to add it on pom file.
if no, do you have rights to access the address of the image file? Some times, folder are protected by the OS.
You can also use YourClassName.class.getResource("input/input1.txt") to locate file/s under the directory that your class was in.
Even with the correct path, I still get a "No such file or directory" error.
The path is NOT correct. That path says look for a directory called "src" in the root directory of your computer. That is almost certainly not where the input file lives.
If you are going to use an absolute pathname for a file within the working directory that you stated, it should look like this:
/Users/kevinliu/Desktop/test/src/input/input1.txt
(You can check what it will actually be using a file browser ... outside of Intellij.)
If you want to use a relative pathname, try this
src/input/input1.txt
Notes:
There is no leading "/" on a relative pathname. A leading "/" means it is an absolute pathname. Absolute pathnames start at the root directory.
A relative path is resolved relative to the >>current<< working directory. That will depend on where and how you run the application ...
For a production application, you would not want to refer to a file in the source tree. The end user typically won't have the source tree.
Consider making the path a command line argument or configuration setting for your application.
Consider making the file a "resource" that is part of the application's JAR file. (You would open it a different way ...)
If you ever get a "No such file or directory" message, that means that the path is not correct in some sense. You might be in the wrong place, you might not have permission on a parent directory, the file may have been removed or renamed, there may be a you, or something else. Either way, that error comes from the operating system and the OS doesn't make mistakes about these things. The mistake will be yours (or the user's).

What is the path in the memory for new File("test") [duplicate]

This question already has answers here:
Get the filePath from Filename using Java
(5 answers)
Closed 6 years ago.
What is the exact location in the memory when we write
File file = new File("test");
Instead we know that
File file = new File("C:\test");
will create it in C drive
It is gonna be your workspace by default. You can see it with this;
System.out.println(file.getAbsolutePath());
Unless you do anything to put it in a different directory or change Java's current working directory, the File object corresponds to a logical path underneath
System.getProperty("user.dir")
However, File doesn't necessarily correspond to a file on the file system; creating a new File(...) doesn't actually create a file on the file system. For example, you can call
file.exists()
and that may return false.
Ideone demo
The default is the workspace of your Java project.
If you somehow want to know where the default is you can show it with the following:
file.getAbsolutePath();
This returns a String object that you can then use to display in the Console.
See this list for future refrencens:
File file = new File("./../eclipse.ini");
file.createNewFile();
System.out.println(file.getAbsolutePath());// prints "C:\work\java\WS\java-io\.\..\eclipse.ini"
System.out.println(file.getCanonicalPath());// prints "C:\work\java\WS\eclipse.ini"
System.out.println(file.getParent()); // prints ".\.."
System.out.println(file.getAbsoluteFile().getParent());// prints "C:\work\java\WS\java-io\.\.."
System.out.println(file.getName()); // prints "eclipse.ini"
System.out.println(file.getPath());// prints ".\..\eclipse.ini"
System.out.println(file.isAbsolute());// prints "false"
Link to source: Click here
Assumptions
I assume that by in memory, you mean in disk.
Definitions
There are two types of paths. Quoting the definition from the wiki:
Absolute paths:
An absolute or full path points to the same location in a file system
regardless of the current working directory. To do that, it must
contain the root directory.
and, Relative Paths:
By contrast, a relative path starts from some given working directory,
avoiding the need to provide the full absolute path. A filename can be
considered as a relative path based at the current working directory.
If the working directory is not the file's parent directory, a file
not found error will result if the file is addressed by its name.
In order to help, we need to know which one you need (the absolute path, or the relative one).
Examples / Answer
For example, if you want to know the absolute path of your test.txt file, we need to know your working directory as well as its structure.
Imagining that you have a working directory like the following:
MyProject
---- Code
---- ----Main.c
---- Assets
---- ---- MyImage.png
---- Text.txt
In windows, it could look something like this:
C:\User\Aakash\Desktop\Myproject\text.txt
If you want to know the relative path, we just need to know the structure of your working directory:
text.txt
Hope it helps!

Java - getting image from file path

Hey is it possible to get an image from file without using the full file location in java? My code below will only work with the full file path:
Icon icon = new ImageIcon("/Users/MyMac/Documents/Project/Software/Project/src/UI/Images/default_pic.png");
Is it possible to use the file path as such?:
Icon icon = new ImageIcon("/src/UI/Images/default_pic.png");
"/src/UI/Images/default_pic.png" is an absolute path, so it will look for a src directory in the root directory, then a UI subdirectory in it, etc. Not what you want.
You can use a relative path such as "src/UI/Images/default_pic.png" (notice it doesn't start with a "/"), but as its name says, it is relative to the current directory. So it will work if your current directory is /Users/MyMac/Documents/Project/Software/Project (or any directory that contains the file in the same subpath), otherwise it won't.
Finally, another way is to access the file through the classpath. Considering that the project could be packed in a jar file, the image file might not be a separate file on the disk, but you can still get a URL or InputStream to access it. Search for getResource and getResourceAsStream in Class and ClassLoader.

File object not working in Java Web App

I have a simple java class in my web application in which i have written the below code but its not working
File test= new File("/templates/xmdForModel.xsd");
templates folder is inside the root folder of the application.
the location of the file is ----> application-root/package/test.java
location of the file is --------> application-root/testRoot/template/xmdForModel.xsd
Error
Failed to read schema document 'file:/templates/xmdForModel.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not .
If you want to look up the file name for files inside of your web application, you can use ServletContext#getRealPath.
However, I would recommend loading your resources using the classloader with Class#getResourceAsStream. This way, it even works if the file does not really exist as a file (for example only inside of a jar).
If this is a file that a user is supposed to edit (or that you write to), I would place it outside of the web application, and then specify an absolute path (for example "/etc/myapp/conf/xmd.xsd") with a configurable prefix.
Path in the File constructor can be absolute or relative. When you start the path with '/' (in a linux based os), it is going to consider that path as an absolute path and create a file/folder in the root of your file structure (not in the root of the project). It will be like specifying c:\templates in windows machine.
Try removing the first slash and running your program. Removing first slash will make the part relative from your .java file. So you can use ../ to switch to parent folder.
java: application-root/package/test.java
file: application-root/testRoot/template/xmdForModel.xsd
So from your java file you will need to change directory to application root folder and then select template folder. Like following.
File x = new File("../testRoot/template/xmdForModel.xsd");
src:http://docs.oracle.com/javase/tutorial/essential/io/path.html
/home/sally/statusReport is an absolute path. All of the information
needed to locate the file is contained in the path string.
A relative path needs to be combined with another path in order to
access a file. For example, joe/foo is a relative path. Without more
information, a program cannot reliably locate the joe/foo directory in
the file system.

Opening a local file in Groovy

I want to use a File object to read a local file in the same directory as a groovlet. However, using a relative path to the file (either "example.txt" or "./example.txt") doesn't do the trick. If I give it an absolute path (e.g., "/example.txt"), then it works.
Is there any way to get the working directory or context path of the groovlet programmatically?
new File("${request.getContextPath()}/example.txt")

Categories

Resources