Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java NIO file path issue

Tags:

java

nio

I used the following code to get the path

Path errorFilePath = FileSystems.getDefault().getPath(errorFile); 

When I try to move a file using the File NIO, I get the error below:

java.nio.file.InvalidPathException: Illegal char <:> at index 2: \C:\Sample\sample.txt 

I also tried using URL.encode(errorFile) which results in the same error.

like image 964
Kathir Avatar asked Mar 23 '12 05:03

Kathir


People also ask

What is Java NIO file paths?

Advertisements. As name suggests Path is the particular location of an entity such as file or a directory in a file system so that one can search and access it at that particular location.

How do I give path to Classpathresource?

Map<String, Object> env = new HashMap<>(); try (FileSystem fs = FileSystems. newFileSystem(uri, env)) { Path path = fs. getPath("/path/myResource"); try (Stream<String> lines = Files. lines(path)) { .... } }

What is import Java NIO file files?

The java. nio. file package defines classes to access files and file systems. The API to access file and file system attributes is defined in the java.

How do you get the path of the file in the file Java?

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.


2 Answers

You need to convert the found resource to URI. It works on all platforms and protects you from possible errors with paths. You must not worry about how full path looks like, whether it starts with '\' or other symbols. If you think about such details - you do something wrong.

ClassLoader classloader = Thread.currentThread().getContextClassLoader(); String platformIndependentPath = Paths.get(classloader.getResource(errorFile).toURI()).toString(); 
like image 62
Alexandr Avatar answered Sep 28 '22 04:09

Alexandr


The path \C:\Sample\sample.txt must not have a leading \. It should be just C:\Sample\sample.txt

like image 29
Jim Garrison Avatar answered Sep 28 '22 06:09

Jim Garrison