Java android get path

How to get the filepath of a file in Java

By mkyong | Last updated: August 24, 2020

Viewed: 516,464 (+5,406 pv/w)

In Java, for NIO Path, we can use path.toAbsolutePath() to get the file path; For legacy IO File, we can use file.getAbsolutePath() to get the file path.

For symbolic links or file path contains . or .. , we can use path.toRealPath() or file.getCanonicalPath() to get the real file pah.

Below is the mapping of File and Path .

  1. file.getAbsolutePath() path.toAbsolutePath()
  2. file.getCanonicalPath() path.toRealPath()
  3. file.getParent() path.getParent()

1. Get file path of a file (NIO Path).

For java.nio.file.Path , we can use the following APIs to get the file path of a file.

  1. path.toAbsolutePath() – Full file path.
  2. path.toRealPath()) – For symbolic links or resolving the . or .. symbols in the path name, default it follow link.
  3. path.getParent() – Get parent directory of the path.

1.1 Path = /home/mkyong/test/file.txt

1.2 Path = file.txt , the file is refer to the current working directory + file.txt .

1.3 Path = /home/mkyong/test/soft-link , a symbolic link.

1.4 Path = /home/mkyong/test/../hello.txt

1.5 Below is a complete Java example to get the file path of different Path .

2. Get file path of a file (legacy File)

For the legacy IO java.io.File , we can use the following APIs to get the file path of a file.

  1. file.getAbsolutePath() = path.toAbsolutePath()
  2. file.getCanonicalPath() = path.toRealPath()
  3. file.getParent() = path.getParent()

Download Source Code

References

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

WHAT.
“File file = File(“C:\abcfolder\textfile.txt”);
System.out.println(“Path : ” + file.getAbsolutePath());

It will display the full path : “Path : C:\abcfolder\textfile.txt“.
Well, this is EXACTLY what you typed in. IE:you KNEW the path …

haha funny, we updated the example again.

And how to get the path of a file if you don’t know the path?

Hi,
My requirement is to transfer the excel file from client to server by manually entering the path in text field.
User don’t want the browse button.
When I am entering manually the file path, server(linux) didn’t recognized the path and file not found exception is thrown.

Please let me know how this can be possible.

You can try File Transfer using SFTP in Java (JSch)

File file = File(“textfile.txt”);

If i only know the name of the file (textfile.txt) as shown above , can i know the whole path of where that file is stored. Bcoz i tried using method file.get absolutePath(). It dosent return the correct path. I am using netbeans IDE.

The file refer to current working directory + textfile.txt

you can try file.getParent()

Thank you of your comment.

Images Folder – Using NetBeans IDE 12.x

Save images e.g. ‘Sample.png’ in ‘resources’ folder which will be in the same hierarchy with ‘java’ folder.
(The resources folder contents will be automatically extracted when building the project and sent to a jar file together with compiled classes.)
The jar file will be stored to ‘target’ folder just under the parent project folder.

Next copy all the contents of resources folder manually to the project folder just as files in the project folder.
(these will be used for code testing in the IDE)

For coding image access in the code e.g

img = ImageIO.read(new File(“Sample.png”));

Just type the image filename thats all needed.
Build the project and you will see the images files included with java classes in the “target” folder, in a jar file.
open the jar file to see compiled classes and the images.

Execute the class files normally using java command “java classname”.

To run class files from command line first extract the jar to any location on the computer and cd to that folder.
*** Ensure to copy resources folder contents directly to project folder all the time after updating or replacing resources ***

Any resources outside these folders will require extra code for handling the absolute path for those locations in the computer.

Источник

Get File Path From URI in Android JAVA

In Android when we pick an image, video, or any other type of file from the gallery, documents folder, or capture directly from the camera, we receive a URI object in intent. We have different ways to get a full file path from URI based on content providers. In this article, we will discuss how to get a file path from URI in Android for the coming files picked through Storage, Documents, as well as depending upon the _data field for the MediaStore and other file-based ContentProviders.

Following is the Java code if you are looking for Kotlin solution visit this Get Path From URI In Kotlin.

Utility Class to Get File Path From URI in Android

Create a file UriUtils.java and copy the following class in that file.

Читайте также:  Перехват паролей через wifi андроид без рут

How to use UriUtils class

You might think that this class is too lengthy, but as mentioned above it handles all scenarios. It checks all android versions and the folders to what the Uri is appointing. It handles different types of content providers. There are different methods depending upon documents path, is it coming through downloads folder or media directory. It also checks is it picked through SECONDARY_STORAGE or EXTERNAL_STORAGE. Few other scenarios like Google Photos Uri, Google drive Uri are also handled properly. Just copy this class in your project as a utility class and rest will be handled by it.

That’s it. This is how to get file path from URI in Java Android.

Источник

Java android get path

A Path represents a path that is hierarchical and composed of a sequence of directory and file name elements separated by a special separator or delimiter. A root component, that identifies a file system hierarchy, may also be present. The name element that is farthest from the root of the directory hierarchy is the name of a file or directory. The other name elements are directory names. A Path can represent a root, a root and a sequence of names, or simply one or more name elements. A Path is considered to be an empty path if it consists solely of one name element that is empty. Accessing a file using an empty path is equivalent to accessing the default directory of the file system. Path defines the getFileName , getParent , getRoot , and subpath methods to access the path components or a subsequence of its name elements.

In addition to accessing the components of a path, a Path also defines the resolve and resolveSibling methods to combine paths. The relativize method that can be used to construct a relative path between two paths. Paths can be compared , and tested against each other using the startsWith and endWith methods.

This interface extends Watchable interface so that a directory located by a path can be registered with a WatchService and entries in the directory watched.

WARNING: This interface is only intended to be implemented by those developing custom file system implementations. Methods may be added to this interface in future releases.

Accessing Files

Paths may be used with the Files class to operate on files, directories, and other types of files. For example, suppose we want a BufferedReader to read text from a file » access.log «. The file is located in a directory » logs » relative to the current working directory and is UTF-8 encoded.

Interoperability

Paths associated with the default provider are generally interoperable with the java.io.File class. Paths created by other providers are unlikely to be interoperable with the abstract path names represented by java.io.File . The toPath method may be used to obtain a Path from the abstract path name represented by a java.io.File object. The resulting Path can be used to operate on the same file as the java.io.File object. In addition, the toFile method is useful to construct a File from the String representation of a Path .

Concurrency

Implementations of this interface are immutable and safe for use by multiple concurrent threads.

Method Summary

Methods
Modifier and Type Method and Description
int compareTo(Path other)
boolean endsWith(Path other) boolean endsWith(String other) boolean equals(Object other) WatchKey register(WatchService watcher, WatchEvent.Kind . events) WatchKey register(WatchService watcher, WatchEvent.Kind [] events, WatchEvent.Modifier. modifiers) boolean startsWith(Path other) boolean startsWith(String other) Path subpath(int beginIndex, int endIndex)

Method Detail

getFileSystem

isAbsolute

An absolute path is complete in that it doesn’t need to be combined with other path information in order to locate a file.

getRoot

getFileName

getParent

The parent of this path object consists of this path’s root component, if any, and each element in the path except for the farthest from the root in the directory hierarchy. This method does not access the file system; the path or its parent may not exist. Furthermore, this method does not eliminate special names such as «.» and «..» that may be used in some implementations. On UNIX for example, the parent of » /a/b/c » is » /a/b «, and the parent of «x/y/. » is » x/y «. This method may be used with the normalize method, to eliminate redundant names, for cases where shell-like navigation is required.

If this path has one or more elements, and no root component, then this method is equivalent to evaluating the expression:

getNameCount

getName

The index parameter is the index of the name element to return. The element that is closest to the root in the directory hierarchy has index 0 . The element that is farthest from the root has index count -1 .

subpath

The beginIndex and endIndex parameters specify the subsequence of name elements. The name that is closest to the root in the directory hierarchy has index 0 . The name that is farthest from the root has index count -1 . The returned Path object has the name elements that begin at beginIndex and extend to the element at index endIndex-1 .

startsWith

This path starts with the given path if this path’s root component starts with the root component of the given path, and this path starts with the same name elements as the given path. If the given path has more name elements than this path then false is returned.

Whether or not the root component of this path starts with the root component of the given path is file system specific. If this path does not have a root component and the given path has a root component then this path does not start with the given path.

If the given path is associated with a different FileSystem to this path then false is returned.

startsWith

endsWith

If the given path has N elements, and no root component, and this path has N or more elements, then this path ends with the given path if the last N elements of each path, starting at the element farthest from the root, are equal.

If the given path has a root component then this path ends with the given path if the root component of this path ends with the root component of the given path, and the corresponding elements of both paths are equal. Whether or not the root component of this path ends with the root component of the given path is file system specific. If this path does not have a root component and the given path has a root component then this path does not end with the given path.

If the given path is associated with a different FileSystem to this path then false is returned.

endsWith

normalize

The precise definition of this method is implementation dependent but in general it derives from this path, a path that does not contain redundant name elements. In many file systems, the » . » and » .. » are special names used to indicate the current directory and parent directory. In such file systems all occurrences of » . » are considered redundant. If a » .. » is preceded by a non-» .. » name then both names are considered redundant (the process to identify such names is repeated until is it no longer applicable).

This method does not access the file system; the path may not locate a file that exists. Eliminating » .. » and a preceding name from a path may result in the path that locates a different file than the original path. This can arise when the preceding name is a symbolic link.

resolve

If the other parameter is an absolute path then this method trivially returns other . If other is an empty path then this method trivially returns this path. Otherwise this method considers this path to be a directory and resolves the given path against this path. In the simplest case, the given path does not have a root component, in which case this method joins the given path to this path and returns a resulting path that ends with the given path. Where the given path has a root component then resolution is highly implementation dependent and therefore unspecified.

resolve

resolveSibling

resolveSibling

relativize

Relativization is the inverse of resolution . This method attempts to construct a relative path that when resolved against this path, yields a path that locates the same file as the given path. For example, on UNIX, if this path is «/a/b» and the given path is «/a/b/c/d» then the resulting relative path would be «c/d» . Where this path and the given path do not have a root component, then a relative path can be constructed. A relative path cannot be constructed if only one of the paths have a root component. Where both paths have a root component then it is implementation dependent if a relative path can be constructed. If this path and the given path are equal then an empty path is returned.

For any two normalized paths p and q, where q does not have a root component,

When symbolic links are supported, then whether the resulting path, when resolved against this path, yields a path that can be used to locate the same file as other is implementation dependent. For example, if this path is «/a/b» and the given path is «/a/x» then the resulting relative path may be «../x» . If «b» is a symbolic link then is implementation dependent if «a/b/../x» would locate the same file as «/a/x» .

toUri

This method constructs an absolute URI with a scheme equal to the URI scheme that identifies the provider. The exact form of the scheme specific part is highly provider dependent.

In the case of the default provider, the URI is hierarchical with a path component that is absolute. The query and fragment components are undefined. Whether the authority component is defined or not is implementation dependent. There is no guarantee that the URI may be used to construct a java.io.File . In particular, if this path represents a Universal Naming Convention (UNC) path, then the UNC server name may be encoded in the authority component of the resulting URI. In the case of the default provider, and the file exists, and it can be determined that the file is a directory, then the resulting URI will end with a slash.

The default provider provides a similar round-trip guarantee to the File class. For a given Path p it is guaranteed that

When a file system is constructed to access the contents of a file as a file system then it is highly implementation specific if the returned URI represents the given path in the file system or it represents a compound URI that encodes the URI of the enclosing file system. A format for compound URIs is not defined in this release; such a scheme may be added in a future release.

toAbsolutePath

If this path is already absolute then this method simply returns this path. Otherwise, this method resolves the path in an implementation dependent manner, typically by resolving the path against a file system default directory. Depending on the implementation, this method may throw an I/O error if the file system is not accessible.

toRealPath

The precise definition of this method is implementation dependent but in general it derives from this path, an absolute path that locates the same file as this path, but with name elements that represent the actual name of the directories and the file. For example, where filename comparisons on a file system are case insensitive then the name elements represent the names in their actual case. Additionally, the resulting path has redundant name elements removed.

If this path is relative then its absolute path is first obtained, as if by invoking the toAbsolutePath method.

The options array may be used to indicate how symbolic links are handled. By default, symbolic links are resolved to their final target. If the option NOFOLLOW_LINKS is present then this method does not resolve symbolic links. Some implementations allow special names such as » .. » to refer to the parent directory. When deriving the real path, and a » .. » (or equivalent) is preceded by a non-» .. » name then an implementation will typically cause both names to be removed. When not resolving symbolic links and the preceding name is a symbolic link then the names are only removed if it guaranteed that the resulting path will locate the same file as this path.

toFile

If this path was created by invoking the File toPath method then there is no guarantee that the File object returned by this method is equal to the original File .

register

In this release, this path locates a directory that exists. The directory is registered with the watch service so that entries in the directory can be watched. The events parameter is the events to register and may contain the following events:

  • ENTRY_CREATE — entry created or moved into the directory
  • ENTRY_DELETE — entry deleted or moved out of the directory
  • ENTRY_MODIFY — entry in directory was modified

The context for these events is the relative path between the directory located by this path, and the path that locates the directory entry that is created, deleted, or modified.

The set of events may include additional implementation specific event that are not defined by the enum StandardWatchEventKinds

The modifiers parameter specifies modifiers that qualify how the directory is registered. This release does not define any standard modifiers. It may contain implementation specific modifiers.

Where a file is registered with a watch service by means of a symbolic link then it is implementation specific if the watch continues to depend on the existence of the symbolic link after it is registered.

register

An invocation of this method behaves in exactly the same way as the invocation

Usage Example: Suppose we wish to register a directory for entry create, delete, and modify events:

iterator

The first element returned by the iterator represents the name element that is closest to the root in the directory hierarchy, the second element is the next closest, and so on. The last element returned is the name of the file or directory denoted by this path. The root component, if present, is not returned by the iterator.

compareTo

This method may not be used to compare paths that are associated with different file system providers.

equals

If the given object is not a Path, or is a Path associated with a different FileSystem , then this method returns false .

Whether or not two path are equal depends on the file system implementation. In some cases the paths are compared without regard to case, and others are case sensitive. This method does not access the file system and the file is not required to exist. Where required, the isSameFile method may be used to check if two paths locate the same file.

This method satisfies the general contract of the Object.equals method.

hashCode

The hash code is based upon the components of the path, and satisfies the general contract of the Object.hashCode method.

toString

If this path was created by converting a path string using the getPath method then the path string returned by this method may differ from the original String used to create the path.

The returned path string uses the default name separator to separate names in the path.

  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method

Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2020, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.

Источник

Читайте также:  Twrp для android что это
Оцените статью