- Как получить текущий рабочий каталог на Java
- 1. Рабочий каталог
- 2. Рабочий каталог для файла JAR?
- Скачать Исходный Код
- Рекомендации
- Get the User Home Directory in Java
- Get the User’s Home Directory Using the System.getProperty() Method in Java
- Get the User’s Home Directory Using the Apache CommonsIO Library in Java
- Get the User’s Home Directory Using the System.getenv() Method in Java
- Summary
- Related Article — Java Home
- Related Article — Java Directory
- How to get home directory in java
- Java program:
- Was this post helpful?
- Related posts
- Count Files in Directory in Java
- How to Remove Extension from Filename in Java
- How to Get Temp Directory Path in Java
- Convert Outputstream to Byte Array in Java
- How to get current working directory in java
- Difference between Scanner and BufferReader in java
- Read UTF-8 Encoded Data in java
- Write UTF-8 Encoded Data in java
- Java read file line by line
- Java FileWriter Example
- Java FileReader Example
- Java – Create new file
- Share this
- Related Posts
- Author
- Related Posts
- Count Files in Directory in Java
- How to Remove Extension from Filename in Java
- How to Get Temp Directory Path in Java
- Convert Outputstream to Byte Array in Java
- How to get current working directory in java
- Difference between Scanner and BufferReader in java
Как получить текущий рабочий каталог на Java
В Java мы можем использовать “System.getProperty(“user.dir”)”, чтобы получить текущий рабочий каталог, каталог, из которого была запущена ваша программа.
В Java мы можем использовать System.getProperty(«user.dir») для получения текущего рабочего каталога, каталога, из которого была запущена ваша программа.
String dir = System.getProperty("user.dir"); // directory from where the program was launched // e.g /home/mkyong/projects/core-java/java-io System.out.println(dir);
Одна из хороших сторон этого системного свойства user.dir мы можем легко переопределить системное свойство с помощью аргумента -D , например:
java -Duser.dir=/home/mkyong/ -jar abc.jar
1. Рабочий каталог
В приведенной ниже программе показаны различные способы, такие как Файл , Пути , Файловые системы или системное свойство для получения текущего рабочего каталога; все методы вернут один и тот же результат.
package com.mkyong.io.howto; import java.io.File; import java.nio.file.FileSystems; import java.nio.file.Paths; public class CurrentWorkingDirectory < public static void main(String[] args) < printCurrentWorkingDirectory1(); printCurrentWorkingDirectory2(); printCurrentWorkingDirectory3(); printCurrentWorkingDirectory4(); >// System Property private static void printCurrentWorkingDirectory1() < String userDirectory = System.getProperty("user.dir"); System.out.println(userDirectory); >// Path, Java 7 private static void printCurrentWorkingDirectory2() < String userDirectory = Paths.get("") .toAbsolutePath() .toString(); System.out.println(userDirectory); >// File("") private static void printCurrentWorkingDirectory3() < String userDirectory = new File("").getAbsolutePath(); System.out.println(userDirectory); >// FileSystems private static void printCurrentWorkingDirectory4() < String userDirectory = FileSystems.getDefault() .getPath("") .toAbsolutePath() .toString(); System.out.println(userDirectory); >>
/home/mkyong/projects/core-java/java-io /home/mkyong/projects/core-java/java-io /home/mkyong/projects/core-java/java-io /home/mkyong/projects/core-java/java-io
Обычно мы используем System.getProperty(«user.dir») для получения текущего рабочего каталога.
2. Рабочий каталог для файла JAR?
Не используйте System.getProperty («user.dir») , Файл или Путь для доступа к файлу, который находится внутри файла JAR , это не сработает. Вместо этого мы должны использовать getClassLoader().getResourceAsStream() .
// get a file from the resources folder, root of classpath in JAR private InputStream getFileFromResourceAsStream(String fileName) < // The class loader that loaded the class ClassLoader classLoader = getClass().getClassLoader(); InputStream inputStream = classLoader.getResourceAsStream(fileName); // the stream holding the file content if (inputStream == null) < throw new IllegalArgumentException("file not found! " + fileName); >else < return inputStream; >>
Примечание Приведенный выше код извлечен из этого Прочитайте файл из папки ресурсов . Обратитесь к примеру 2 для доступа к файлу, который находится внутри файла JAR.
Скачать Исходный Код
Рекомендации
- Java – Чтение файла из папка ресурсов
- Файл JavaDoc
- Путь JavaDoc
- Как отобразить все системные свойства
- Википедия – Рабочий каталог
Get the User Home Directory in Java
- Get the User’s Home Directory Using the System.getProperty() Method in Java
- Get the User’s Home Directory Using the Apache CommonsIO Library in Java
- Get the User’s Home Directory Using the System.getenv() Method in Java
- Summary
This tutorial introduces how to get the user home directory in Java and lists some example codes to guide you on the topic.
For a multi-user operating system, there exists a file system directory for every user; this directory is known as the user’s home directory. There are different ways to find the user home directory in Java. Let’s look at each one of them.
Get the User’s Home Directory Using the System.getProperty() Method in Java
The System class in Java has a Properties object used to store different properties and configurations of the current working environment. It also holds the user’s home directory.
We can access these properties by using the getProperty() method of this class. We need to pass the name of the system property that we want to view. In our case, it would be user.home .
The following code demonstrates how it works.
public class Main public static void main(String[] args) String userHomeDir = System.getProperty("user.home"); System.out.printf("The User Home Directory is %s", userHomeDir); > >
The User Home Directory is C:\Users\Lenovo
If you’re curious and want to view all the system properties, you can use the getProperties() method. The code for the getProperties() method is shown below.
import java.util.Map; import java.util.Properties; public class Main public static void main(String[] args) Properties props = System.getProperties(); for(Map.EntryObject, Object> prop : props.entrySet()) System.out.println("Property: +" + prop.getKey() + "\tValue: " + prop.getValue()); > >
Get the User’s Home Directory Using the Apache CommonsIO Library in Java
Apache Commons is a very powerful library, and the FileUtils class of the CommonsIO library can be used to fetch the home directory.
We can simply use the getUserDirectory() method of this class to view the user’s home directory. It returns a File object that represents the home directory. We can also get a String path of the home directory by using the getUserDirectoryPath() method.
The code and output for these methods are shown below.
import java.io.File; import org.apache.commons.io.FileUtils; public class Main public static void main(String[] args) File homeDir = FileUtils.getUserDirectory(); String homeDirPath = FileUtils.getUserDirectoryPath(); System.out.printf("The User Home Directory is %s\n", homeDir); System.out.printf("The path of User Home Directory is %s", homeDirPath); > >
The User Home Directory is C:\Users\Lenovo The path of User Home Directory is C:\Users\Lenovo
Get the User’s Home Directory Using the System.getenv() Method in Java
The getenv() method of the System class is used to get the value of system environment variables. We need to pass the name of the environment variable that we want to access.
To get the user’s home directory, we need to use the string USERPROFILE . The following program demonstrates the working of the getenv() method.
public class Main public static void main(String[] args) String userHomeDir = System.getenv("USERPROFILE"); System.out.printf("The User Home Directory is %s", userHomeDir); > >
The User Home Directory is C:\Users\Lenovo
You can also use this method to view all the environment variables. Run the following program if you are curious to know more about your system’s environment variables.
import java.util.Map; public class Main public static void main(String[] args) MapString, String> envVars = System.getenv(); for(Map.EntryString, String> var : envVars.entrySet()) System.out.println(var.getKey() + " ---> " + var.getValue()); > >
Summary
In this guide, we learn how to get the user’s home directory in Java. For some Windows platforms running older Java versions (before Java 8), the System.getProperty() method may not give the desired result due to the presence of a bug with ID 4787931.
Another similar bug (Bug ID 6519127) also exists. Because of this, the getProperty() method gives undesirable results. However, both of these bugs have already been resolved.
In most cases, the getProperty() method will work just fine, but we can use the alternative System.getenv() method to get the user home directory.
Related Article — Java Home
Related Article — Java Directory
How to get home directory in java
In this post, we will see how to get user profile’s home directory in java. It is quite simple, we can use System.getProperty(“user.home”) to get it.
Java program:
Was this post helpful?
Related posts
Count Files in Directory in Java
How to Remove Extension from Filename in Java
How to Get Temp Directory Path in Java
Convert Outputstream to Byte Array in Java
How to get current working directory in java
Difference between Scanner and BufferReader in java
Read UTF-8 Encoded Data in java
Write UTF-8 Encoded Data in java
Java read file line by line
Java FileWriter Example
Java FileReader Example
Java – Create new file
Share this
Related Posts
Author
Related Posts
Count Files in Directory in Java
Table of ContentsUsing java.io.File ClassUse File.listFiles() MethodCount Files in the Current Directory (Excluding Sub-directories)Count Files in the Current Directory (Including Sub-directories)Count Files & Folders in Current Directory (Excluding Sub-directories)Count Files & Folders in Current Directory (Including Sub-directories)Use File.list() MethodUsing java.nio.file.DirectoryStream ClassCount Files in the Current Directory (Excluding Sub-directories)Count Files in the Current Directory (Including Sub-directories)Count […]
How to Remove Extension from Filename in Java
Table of ContentsWays to Remove extension from filename in javaUsing substring() and lastIndexOf() methodsUsing replaceAll() methodUsing Apache common library In this post, we will see how to remove extension from filename in java. Ways to Remove extension from filename in java There are multiple ways to remove extension from filename in java. Let’s go through […]
How to Get Temp Directory Path in Java
Table of ContentsGet Temp Directory Path in JavaUsing System.getProperty()By Creating Temp File and Extracting Temp PathUsing java.io.FileUsing java.nio.File.FilesOverride Default Temp Directory Path In this post, we will see how to get temp directory path in java. Get Temp Directory Path in Java Using System.getProperty() To get the temp directory path, you can simply use System.getProperty(«java.io.tmpdir»). […]
Convert Outputstream to Byte Array in Java
Table of ContentsConvert OutputStream to Byte array in JavaConvert OutputStream to ByteBuffer in Java In this post, we will see how to convert OutputStream to Byte array in Java. Convert OutputStream to Byte array in Java Here are steps to convert OutputStream to Byte array in java. Create instance of ByteArrayOutputStream baos Write data to […]
How to get current working directory in java
Difference between Scanner and BufferReader in java
Table of ContentsIntroductionScannerBufferedReaderDifference between Scanner and BufferedReader In this post, we will see difference between Scanner and BufferReader in java. Java has two classes that have been used for reading files for a very long time. These two classes are Scanner and BufferedReader. In this post, we are going to find major differences and similarities […]