ZhaoGang
ZhaoGang

Reputation: 4915

How to understand the java Path.toString() method

My codes:

Path uploadPath = Paths.get("D:\\0.hzg\\");
System.out.println(uploadPath);

output:

D:\0.hzg

How to understand the design of the toString() method of Path here?

I thought it should output D:\0.hzg\ since 0.hzgis a path instead of a file.


update:

        System.out.println(Paths.get("-","A", "B")); 
        System.out.println(Paths.get("/","A", "B")); 
        System.out.println(Paths.get("\\","A", "B"));

outputs:

-\A\B
\\A\B\
\\A\B\

Upvotes: 1

Views: 1740

Answers (2)

Imran
Imran

Reputation: 3024

[Paths] gets method only creates path by taking care system-file-separator which will helps in cross platform execution of programs e.g.

System.out.println(Paths.get(File.separator,"A", "B"));

will returns

On Windows : \\A\B\

On Unix : /A/B/

Details of File.separator are

The system-dependent default name-separator character. This field isinitialized to contain the first character of the value of the systemproperty file.separator. On UNIX systems the value of thisfield is '/'; on Microsoft Windows systems it is '\'.

Specific to question asked

i believe it is because of Absolute Path
e.g. on windows JDK 1.7

System.out.println(Paths.get("C:","A", "B")); **Output** : C:\A\B
System.out.println(Paths.get("C:","A", "0.hzg")); **Output** : C:\A\0.hzg


System.out.println(Paths.get(File.separator,"A", "B")); **Output** : \\A\B\
System.out.println(Paths.get(File.separator,"A", "0.hzg")); **Output** : \\A\0.hzg\

Hopes that helps

Upvotes: 1

Some Name
Some Name

Reputation: 9540

Path does not do any I/O to check if this is a directory or a regular file. It is an utility class for working with platform dependent string representation of filesystem path (you definitely do not want to split strings by / or find the drive letter by yourself). Citing javadoc https://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html#toString()

An object that may be used to locate a file in a file system. It will typically represent a system dependent file path.

Also, trailing separators are not.taken into account (see e.g. endsWith method description)

Note that trailing separators are not taken into account, and so invoking this method on the Path"foo/bar" with the String "bar/" returns true.

Upvotes: 1

Related Questions