Java file home dir

Class File

The conversion of a pathname string to or from an abstract pathname is inherently system-dependent. When an abstract pathname is converted into a pathname string, each name is separated from the next by a single copy of the default separator character. The default name-separator character is defined by the system property file.separator , and is made available in the public static fields separator and separatorChar of this class. When a pathname string is converted into an abstract pathname, the names within it may be separated by the default name-separator character or by any other name-separator character that is supported by the underlying system.

Читайте также:  Тег OPTION, атрибут selected

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.

The parent of an abstract pathname may be obtained by invoking the getParent() method of this class and consists of the pathname’s prefix and each name in the pathname’s name sequence except for the last. Each directory’s absolute pathname is an ancestor of any File object with an absolute abstract pathname which begins with the directory’s absolute pathname. For example, the directory denoted by the abstract pathname «/usr» is an ancestor of the directory denoted by the pathname «/usr/local/bin» .

  • For UNIX platforms, the prefix of an absolute pathname is always «/» . Relative pathnames have no prefix. The abstract pathname denoting the root directory has the prefix «/» and an empty name sequence.
  • For Microsoft Windows platforms, the prefix of a pathname that contains a drive specifier consists of the drive letter followed by «:» and possibly followed by «\\» if the pathname is absolute. The prefix of a UNC pathname is «\\\\» ; the hostname and the share name are the first two names in the name sequence. A relative pathname that does not specify a drive has no prefix.
Читайте также:  Как распарсить html php

Instances of this class may or may not denote an actual file-system object such as a file or a directory. If it does denote such an object then that object resides in a partition. A partition is an operating system-specific portion of storage for a file system. A single storage device (e.g. a physical disk-drive, flash memory, CD-ROM) may contain multiple partitions. The object, if any, will reside on the partition named by some ancestor of the absolute form of this pathname.

A file system may implement restrictions to certain operations on the actual file-system object, such as reading, writing, and executing. These restrictions are collectively known as access permissions. The file system may have multiple sets of access permissions on a single object. For example, one set may apply to the object’s owner, and another may apply to all other users. The access permissions on an object may cause some methods in this class to fail.

Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change.

Interoperability with java.nio.file package

The java.nio.file package defines interfaces and classes for the Java virtual machine to access files, file attributes, and file systems. This API may be used to overcome many of the limitations of the java.io.File class. The toPath method may be used to obtain a Path that uses the abstract path represented by a File object to locate a file. The resulting Path may be used with the Files class to provide more efficient and extensive access to additional file operations, file attributes, and I/O exceptions to help diagnose errors when an operation on a file fails.

Читайте также:  Php метод внутри метода

Источник

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?

Count Files in Directory in Java

Count Files in Directory in Java

How to Remove Extension from Filename in Java

How to Remove Extension from Filename in Java

How to Get Temp Directory Path in Java

How to Get Temp Directory Path in Java

Convert OutputStream to byte array in java

Convert Outputstream to Byte Array in Java

How to get current working directory in java

How to get current working directory in java

Difference between Scanner and BufferReader in java

Difference between Scanner and BufferReader in java

Read UTF-8 Encoded Data in java

Read UTF-8 Encoded Data in java

WriteUTF-8NewBufferWriter

Write UTF-8 Encoded Data in java

Java read file line by line

Java read file line by line

Java FileWriter Example

Java FileWriter Example

Java FileReader Example

Java FileReader Example

Java - Create new file

Java – Create new file

Share this

Author

Count Files in Directory in Java

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

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 […]

Источник

Get the User Home Directory in Java

Get the User Home Directory in Java

  1. Get the User’s Home Directory Using the System.getProperty() Method in Java
  2. Get the User’s Home Directory Using the Apache CommonsIO Library in Java
  3. Get the User’s Home Directory Using the System.getenv() Method in Java
  4. 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

Источник

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