简体   繁体   中英

Java.nio.file.Paths is giving incorrect path for current directory?

I am trying to read the contents of a file using Java.nio.file.Paths class, my code looks like this

package com.test.json;

Path currentDir = Paths.get(".");
System.out.println(currentDir.toAbsolutePath());

It is giving me the path

/home/rohit/workspace/MapReduceExample/.

while the output should be

home/rohit/workspace/MapReduceExample/src/com/test/json/

It is ignoring the component of src folder and packages. Could someone please tell me what I am doing wrong?

I can't give absolute path because I need this code for a map-reduce path, I have to construct path in relative manner. So, my approach is to do

getCurrentDirectoryPath + filename

It appears to me that you are expecting the Path of the directory where your source Java file (that calls Paths.get(".") ) resides. But that's not what the path "." will fetch. When a JVM runs your class on the host file system, the value of "." refers to the current working directory of the JVM process. It's very likely that the JVM that runs your class is actually started in that folder: /home/rohit/workspace/MapReduceExample . If you did a

System.out.println(Paths.get(
   System.getProperty("user.dir")).toAbsolutePath());

you'll see that it prints the same folder, without the trailing "." .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM