Unable to get path even though it is correct - java

I'm trying to get my file path, to make sure it's the same I even used a function to return the path to the file, even though the path to the file is correct, it never works, I've tried to remove the .txt, to just have the file name (since it's on the same package as this class) but nothing seems to work.
Here's the code:
StringBuilder contentBuilder = new StringBuilder();
try
{
String filetest="text.txt";
Path pathToFile = Paths.get(filetest);
String name = pathToFile.toAbsolutePath().toString();
System.out.println("Path name: " + name);
Stream<String> stream = Files.lines( Paths.get(name), StandardCharsets.UTF_8);
stream.forEach(s -> contentBuilder.append(s).append("\n"));
String filename = contentBuilder.toString();
System.out.println(filename);
}
catch (IOException e)
{
e.printStackTrace();
System.out.println("Error: " + e);
}
Output
Path name: C:\Users\Dias\eclipse-workspace\pds\text.txt
java.nio.file.NoSuchFileException: C:\Users\Dias\eclipse-workspace\pds\text.txt
at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:230)
at java.nio.file.Files.newByteChannel(Files.java:361)
at java.nio.file.Files.newByteChannel(Files.java:407)
at java.nio.file.spi.FileSystemProvider.newInputStream(FileSystemProvider.java:384)
at java.nio.file.Files.newInputStream(Files.java:152)
at java.nio.file.Files.newBufferedReader(Files.java:2784)
at java.nio.file.Files.lines(Files.java:3744)
at lab7.Client.main(Client.java:23)
Error: java.nio.file.NoSuchFileException: C:\Users\Dias\eclipse-workspace\pds\text.txt

If this is the expected path
C:\Users\Dias\eclipse-workspace\pds\text.txt
then the explanation is surely that the file does not exist.
If that is not the expected path then the explanation is that you need to either:
Code the path correctly in to your program, or
Change your current working directory
'toAbsolutePath' does not look around and find the file so it knows the absolute path; rather it sees that your specified path is relative, and prefixes it with the current workig directory.

Related

Files.exists() returning false when a regular file is tested and true when a directory is tested

I created a directory called "examples" inside my current working directory (C) and inside it I created a .txt file called "test.txt", but when I test the file using Files.exists(), it returns false.
System.out.println(Files.exists(Path.of("\\examples\\test.txt")));
So, I replaced the text file "test.txt" with a directory with the same name, ie, "test.txt". Now Files.exists() returns true.
This might mean that the path is correct but something is wrong with my regular file.
why is'nt exists() returning true in both cases?
Try to create a directory and a file as follows:
try {
Path examples = Paths.get("examples");
if (Files.notExists(examples)) // if path not exists
Files.createDirectories(examples); // create as directory
Path path = examples.resolve("test.txt"); // resolve file
if (Files.notExists(path)) // if not exists
Files.createFile(path); // create file
System.out.println("path = " + path);
System.out.println("Files.exists(path) = " + Files.exists(path));
} catch (IOException ex) {
ex.printStackTrace();
}

Issue while moving file using java.nio

Getting below exception while trying to move a file after renaming it, issue is that it is occurring intermittently i.e. sometimes the code works and sometimes it does not and is not replicable, would be helpful if anyone can provide insight on the same
Caused by: java.nio.file.AccessDeniedException: /data/Inprocess/DEMO.20191026.csv -> /data/Inprocess/DEMO.20191026.csv.inprogress
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:84)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
at sun.nio.fs.UnixCopyFile.move(UnixCopyFile.java:457)
at sun.nio.fs.UnixFileSystemProvider.move(UnixFileSystemProvider.java:262)
at java.nio.file.Files.move(Files.java:1395)
Path fromPath = inputFile.toPath();
Path toPath = new File(inputFile.getAbsolutePath() + ".inprogress").toPath();
LOGGER.info("Moving file to Path: " + inputFile.getAbsolutePath() + ".inprogress");
try {
Files.move(fromPath, fromPath.resolveSibling(toPath),StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
// Handle Exception
throw new TradeProcessorException("Error while marking file Inprogress: ", e);
}
One difference between the old File (pure disk files/directories) and the newer, more powerful Path is, that the latter maintains its "file" system (which could be a zip, ram disk, remote disk). So once using Path, keep using it.
Path fromPath = inputFile.toPath();
String toName = inputFile.getFileName().toString() + ".inprogress";
Path toPath = inputFile.resolveSibling(toName);
LOGGER.info("Moving file to Path: " + toPath);
try {
Files.move(fromPath, toPath, StandardCopyOption.REPLACE_EXISTING);
Your usage of resolveSibling seems to add a full path.
(Above the superfluous .toString() is just a reminder that getFileName() returns a Path.)

NoSuchFileException when creating a file using nio

I am trying to create a new file using java nio, and I'm running into a createFile error. Error looks like this:
createFile error: java.nio.file.NoSuchFileException: /Users/jchang/result_apache_log_parser_2015/06/09_10:53:49
code segment looks like this:
String filename = "/Users/jchang/result_apache_log_parser_" + filename_date;
Path file = Paths.get(filename);
try {
Files.createFile(file);
} catch (FileAlreadyExistsException x) {
System.err.format("file named %s" +
" already exists%n", file);
} catch (IOException x) {
System.err.format("createFile error: %s%n", x);
}
Anyone have any idea how to fix this? Thanks for your help!
I would say that Turing85 was correct. Your filename_date variable has slashes in it. So /Users/jchang/result_apache_log_parser_2015 has to exist as a directory. That is the cause of the NoSuchFileException, missing directory.
Your code has at least two problems. First: you have path delimiters in your filename (/). Second: at least under Windows, your solution has illegal characters within the filname (:).
To get rid of the first problem, you can go down two routes: a) create all the folders you need or b) change the delimiters to something different. I will explain both.
To create all folders to a path, you can simply call
Files.createDirectories(path.getParent());
where path is a file (important!). By calling getParent() on file, we get the folder, in which path resides. Files.createDirectories(...) takes care of the rest.
b) Change the delimiters: Nothing easier than this:
String filename = "/Users/jchang/result_apache_log_parser_"
+ filename_date.replace("/", "_")
.replace(":", "_");
This should yield something like /User/jchang/result_apache_parser_2015_06_09_10_53_29
With b) we have taken care of the second problem as well.
Now lets set it all together and apply some minor tricks of nio:
String filename = "/Users/jchang/result_apache_log_parser_"
+ filename_date.replace('/', '_')
.replace(':', '_');
Path file = Paths.get(filename);
try {
// Create sub-directories, if needed.
Files.createDirectories(file.getParent());
// Create the file content.
byte[] fileContent = ...;
// We do not need to create the file manually, let NIO handle it.
Files.write(file
, fileContent
// Request permission to write the file
, StandardOpenOption.WRITE
// If the file exists, append new content
, StandardOpenOption.APPEND
// If the file does not exist, create it
, StandardOpenOption.CREATE);
} catch (IOException e) {
e.printStackTrace();
}
For more information about nio click here.
As many said, you need to create intermediate directories, like ../06/..
So use this, before creating the file to create dirs which don't exist,
Files.createDirectories(mPath.getParent());
So your code should be:
Path file = Paths.get(filename);
try {
Files.createDirectories(file.getParent());
Files.createFile(file);
} catch (FileAlreadyExistsException x) {
System.err.format("file named %s" +
" already exists%n", file);
} catch (IOException x) {
System.err.format("createFile error: %s%n", x);
}

Unable to access/run executable jar placed within the project

I am trying to run an executable jar places in the resources folder of my project. If I place the jar in any directory of my File System and provide the absolute path, it works fine.
Please see the code below:
String jarPath = "C:\\JarFolder\\myJar.jar";
String command = "java -jar";
String space = " ";
String params = "-a abc";
try {
proc = Runtime
.getRuntime()
.exec(command + space + jarPath + space + params);
} catch (IOException e) {
e.printStackTrace();
}
But when I place the jar inside the resources folder, and set the relative jar path as:
String jarPath = "..\\..\\..\\resources\\myJar.jar";
I get an error: Error: Unable to access jarfile ..\\..\\..\\resources\\myJar.jar
I have verified the path, it is valid.
Am I doing something wrong here? Is this the correct way to do this?
Use the ClassLoader to get the path of your resource.
String jarPath = this.getClass().getClassLoader().getResource("myJar.jar").getPath();
String command = "java -jar";
String space = " ";
String params = "-a abc";
try {
proc = Runtime
.getRuntime()
.exec(command + space + jarPath + space + params);
} catch (IOException e) {
e.printStackTrace();
}
If this is being ran from a main static method, then just replace this.getClass() with YourClass.class.
Relative path should work straight forward. Need more details of the error description you see and project folder structure (where the executing jar is placed and where is the import folder placed.)
Other alternate solution is to find the absolute file location of the currently executing jar file. You can fetch it with below code snippet.
MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
Other jar file to be executed must be placed somewhere in the same folder or in some child folders.
Now remove the current jar file name from the absolute path and append the relative path of the other jar file and execute it. It should work.
If you are on window, you can use as follow. I have tested this code and it works.
public class test {
public static void main(String[]args) throws IOException{
String jarPath = test.class.getClass().getResource("/resources/b.jar").getPath();
System.out.println("jarPath "+ jarPath);
//the result path have extra "/" so we have to remove it as follow.
jarPath = jarPath.substring(1);
//and again the result is encoded so we need to decode it back
jarPath = URLDecoder.decode(jarPath);
Runtime
.getRuntime()
.exec("java -jar \""+jarPath+"\"");
}
}
Note: I put my runnable jar in my resources folder with name "b.jar".
And the above codes need some modification to meet your needs.
Good Luck

Hot to get rid of an java.io.Exception at java.io.WinNTFileSystem.createFileExclusively?

I currently have the problem that I encounter an exception I never saw before and that's why I don't know how to handle it.
I want to create a file according to given parameters, but it won't work.
public static Path createFile(String destDir, String fileName) throws IOException {
FileAccess.createDirectory( destDir);
Path xpath = new Path( destDir + Path.SEPARATOR + fileName);
if (! xpath.toFile().exists()) {
xpath.toFile().createNewFile();
if(FileAccess.TRACE_FILE)Trace.println1("<<< createFile " + xpath.toString() );
}
return xpath;
}
public static void createDirectory(String destDir) {
Path dirpath = new Path(destDir);
if (! dirpath.toFile().exists()) {
dirpath.toFile().mkdir();
if(TRACE_FILE)Trace.println1("<<< mkdir " + dirpath.toString() );
}
}
Every time I run my application the following exception occurs:
java.io.IOException: The system cannot find the path specified
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(Unknown Source)
[...]
How do I get rid of it? (I am using Win7 64bit btw)
The problem is that a file can't be created unless the entire containing path already exists - its immediate parent directory and all parents above it.
If you have a path c:\Temp and no subdirectories below it, and you try to create a file called c:\Temp\SubDir\myfile.txt, that will fail because C:\Temp\SubDir doesn't exist.
Before
xpath.toFile().createNewFile();
add
xpath.toFile().mkdirs();
(I'm not sure if mkdirs() requires just the path in the object; if it does, then change that new line to
new File(destDir).mkdirs();
Otherwise, you'll get your filename created as a subdirectory instead! You can verify which is correct by checking your Windows Explorer to see what directories it created.)

Categories