Java file path linux

How to get the filepath of a file in Java

By mkyong | Last updated: August 24, 2020

Viewed: 507,045 (+1,353 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 ***

Читайте также:  Микшер для наушников windows 10

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

Источник

Create a file path that adapts to Windows and Linux in Java

In the development process, the average programmer is developing on the IDE on Windows, so there is generally no problem when creating files, but if the program is deployed to Linux, it may be due to the file system of Linux and Windows. The file creation failed because of the difference.

This directory will be available under Windows:

At this point, we will not have any problems creating a new file in this directory, but if it is under Linux, because the Linux system does not have a C drive, the creation of the file will naturally fail, and the program will naturally run incorrectly.

Therefore, when creating a file, we can’t take it for granted by default. There are other computers on the computer. After all, everyone’s computer is different. Even if it is the same Windows system, every computer has only C. Disks, as for D, E, and F disks, are created according to personal preference, not to mention the different file systems on Linux, so we need to consider the different file systems and the different partitions when programming.

1. When splicing the file path, the path is not connected to «\\», instead using the file separator of the adaptive operating system:

fileSeperator will use the correct file separator for the operating system.

2. When writing a file path, do not write the file path on the computer yourself. Make sure that the file path used is different from the computer, that is:

At this time, userHome is the user’s home directory. It has nothing to do with the operating system. If you create a file in this folder, it will be created successfully. Therefore, there will be no program running failure when deploying the program to the Linux system.

Note: Java common system path and get method:

Источник

linux-notes.org

Не знаете как установить переменные JAVA_HOME и PATH для каждого пользователя в соответствии с вашей системой Linux? Тогда эта статья «Установка переменных JAVA_HOME / PATH в Linux» именно для Вас. Я напишу ее в качестве заметки, чтобы потом быстренько вспомнить и прописать Java_Home и Path на ОС для каждого пользователя ( если понадобится).

Установка переменных JAVA_HOME / PATH в Unix/Linux

/ .bash_profile является сценарий запуска, который обычно выполняется один раз. Это конкретный файл используется для команд, которые выполняются, когда нормальные входе пользователя в систему. Common использует для .bash_profile должны установить переменные окружения, такие как PATH, JAVA_HOME, чтобы создать псевдонимы для команд оболочки, и установить права доступа по умолчанию для вновь создаваемых файлов.

Установка JAVA_HOME / PATH для одного пользователя

Зайдите в свой аккаунт (учетную запись) и откройте файл .bash_profile в любом редакторе:

Установите JAVA_HOME как показано используя синтаксис export JAVA_HOME=

. Если ваш путь такой как у меня /usr/lib/jvm/java-1.6.0-openjdk-i386/bin/java, то тогда пропишите:
export JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk-i386/bin/java

Чтобы установить PATH пропишите:

Замените путь /usr/java/jdk1.5.0_07 на свой. Сохраните и закройте файл. Просто выйдите и зайдите обратно (перелогиньетсь), чтобы увидеть изменения или чтобы все изменения вступили в силу, выполните команду:

Чтобы проверить отображение новых настроек, используйте команды:

Совет: Используйте следующую команду, чтобы узнать точный путь Java под UNIX / Linux:

Пожалуйста, обратите внимание, что файл

/.bashrc похож на

/.bash_profile но работает только для оболочки Bash и .bashrc работает для каждой новой Bash оболочки.

Установка JAVA_HOME / PATH для всех пользователей

Вам нужно добавить строки в глобальный файл конфигурации в /etc/profile ИЛИ /etc/bash.bashrc чтобы внести изменения для всех пользователей:

Добавьте переменные PATH / JAVA_PATH следующим образом:

Сохраните и закройте файл. Еще раз вам нужно ввести следующую команду, чтобы немедленно активировать настройки:

Но если не будет работать, есть еще 1 способ прописать все это дело! Сейчас я покажу как это можно сделать.

1. Устанавливаем переменные среды:

2. Выполните команду чтобы перезапустить все только что прописанные настройки:

3. Тест, если среда Java успешно установлена, введите команду в терминале чтобы проверить работу:

Установка переменных JAVA_HOME / PATH в Unix/Linux завершена.

One thought on “ Установка переменных JAVA_HOME / PATH в Unix/Linux ”

Спасибо за гайд, работает как часы. Первых пунктов до bash_profile включительно хватило. Версия х64. Пути и названия свои. Проверил еще javac -version. Вопрос к автору. Где эту информацию искать на сайте оракла?

Читайте также:  Таймер выкл компьютера windows 10

Добавить комментарий Отменить ответ

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.

Источник

Path Operations

The Path class includes various methods that can be used to obtain information about the path, access elements of the path, convert the path to other forms, or extract portions of a path. There are also methods for matching the path string and methods for removing redundancies in a path. This lesson addresses these Path methods, sometimes called syntactic operations, because they operate on the path itself and don’t access the file system.

This section covers the following:

Creating a Path

A Path instance contains the information used to specify the location of a file or directory. At the time it is defined, a Path is provided with a series of one or more names. A root element or a file name might be included, but neither are required. A Path might consist of just a single directory or file name.

You can easily create a Path object by using one of the following get methods from the Paths (note the plural) helper class:

The Paths.get method is shorthand for the following code:

The following example creates /u/joe/logs/foo.log assuming your home directory is /u/joe , or C:\joe\logs\foo.log if you are on Windows.

Retrieving Information about a Path

You can think of the Path as storing these name elements as a sequence. The highest element in the directory structure would be located at index 0. The lowest element in the directory structure would be located at index [n-1] , where n is the number of name elements in the Path . Methods are available for retrieving individual elements or a subsequence of the Path using these indexes.

The examples in this lesson use the following directory structure.

Sample Directory Structure

The following code snippet defines a Path instance and then invokes several methods to obtain information about the path:

Here is the output for both Windows and the Solaris OS:

Method Invoked Returns in the Solaris OS Returns in Microsoft Windows Comment
toString /home/joe/foo C:\home\joe\foo Returns the string representation of the Path . If the path was created using Filesystems.getDefault().getPath(String) or Paths.get (the latter is a convenience method for getPath ), the method performs minor syntactic cleanup. For example, in a UNIX operating system, it will correct the input string //home/joe/foo to /home/joe/foo .
getFileName foo foo Returns the file name or the last element of the sequence of name elements.
getName(0) home home Returns the path element corresponding to the specified index. The 0th element is the path element closest to the root.
getNameCount 3 3 Returns the number of elements in the path.
subpath(0,2) home/joe home\joe Returns the subsequence of the Path (not including a root element) as specified by the beginning and ending indexes.
getParent /home/joe \home\joe Returns the path of the parent directory.
getRoot / C:\ Returns the root of the path.

The previous example shows the output for an absolute path. In the following example, a relative path is specified:

Here is the output for Windows and the Solaris OS:

Method Invoked Returns in the Solaris OS Returns in Microsoft Windows
toString sally/bar sally\bar
getFileName bar bar
getName(0) sally sally
getNameCount 2 2
subpath(0,1) sally sally
getParent sally sally
getRoot null null

Removing Redundancies From a Path

Many file systems use «.» notation to denote the current directory and «..» to denote the parent directory. You might have a situation where a Path contains redundant directory information. Perhaps a server is configured to save its log files in the » /dir/logs/. » directory, and you want to delete the trailing » /. » notation from the path.

The following examples both include redundancies:

The normalize method removes any redundant elements, which includes any » . » or » directory/.. » occurrences. Both of the preceding examples normalize to /home/joe/foo .

It is important to note that normalize doesn’t check at the file system when it cleans up a path. It is a purely syntactic operation. In the second example, if sally were a symbolic link, removing sally/.. might result in a Path that no longer locates the intended file.

Читайте также:  Windows com моя семья

To clean up a path while ensuring that the result locates the correct file, you can use the toRealPath method. This method is described in the next section, Converting a Path.

Converting a Path

You can use three methods to convert the Path . If you need to convert the path to a string that can be opened from a browser, you can use toUri . For example:

The toAbsolutePath method converts a path to an absolute path. If the passed-in path is already absolute, it returns the same Path object. The toAbsolutePath method can be very helpful when processing user-entered file names. For example:

The toAbsolutePath method converts the user input and returns a Path that returns useful values when queried. The file does not need to exist for this method to work.

The toRealPath method returns the real path of an existing file. This method performs several operations in one:

  • If true is passed to this method and the file system supports symbolic links, this method resolves any symbolic links in the path.
  • If the Path is relative, it returns an absolute path.
  • If the Path contains any redundant elements, it returns a path with those elements removed.

This method throws an exception if the file does not exist or cannot be accessed. You can catch the exception when you want to handle any of these cases. For example:

Joining Two Paths

You can combine paths by using the resolve method. You pass in a partial path , which is a path that does not include a root element, and that partial path is appended to the original path.

For example, consider the following code snippet:

Passing an absolute path to the resolve method returns the passed-in path:

Creating a Path Between Two Paths

A common requirement when you are writing file I/O code is the capability to construct a path from one location in the file system to another location. You can meet this using the relativize method. This method constructs a path originating from the original path and ending at the location specified by the passed-in path. The new path is relative to the original path.

For example, consider two relative paths defined as joe and sally :

In the absence of any other information, it is assumed that joe and sally are siblings, meaning nodes that reside at the same level in the tree structure. To navigate from joe to sally , you would expect to first navigate one level up to the parent node and then down to sally :

Consider a slightly more complicated example:

In this example, the two paths share the same node, home . To navigate from home to bar , you first navigate one level down to sally and then one more level down to bar . Navigating from bar to home requires moving up two levels.

A relative path cannot be constructed if only one of the paths includes a root element. If both paths include a root element, the capability to construct a relative path is system dependent.

The recursive Copy example uses the relativize and resolve methods.

Comparing Two Paths

The Path class supports equals , enabling you to test two paths for equality. The startsWith and endsWith methods enable you to test whether a path begins or ends with a particular string. These methods are easy to use. For example:

The Path class implements the Iterable interface. The iterator method returns an object that enables you to iterate over the name elements in the path. The first element returned is that closest to the root in the directory tree. The following code snippet iterates over a path, printing each name element:

The Path class also implements the Comparable interface. You can compare Path objects by using compareTo which is useful for sorting.

You can also put Path objects into a Collection . See the Collections trail for more information about this powerful feature.

When you want to verify that two Path objects locate the same file, you can use the isSameFile method, as described in Checking Whether Two Paths Locate the Same File.

Источник

Оцените статью