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.
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.
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)) { .... } }
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.
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.
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();
The path \C:\Sample\sample.txt
must not have a leading \
. It should be just C:\Sample\sample.txt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With