Issue while moving file using java.nio - java

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.)

Related

Java NIO | Paths & Files | How to create custom file and folder with custom name fetched from other object?

Following is code:
public void storePartsFile(MultipartFile file, Long jobNumber) {
Path path = Paths.get("C:\\DocumentRepository\\" +jobNumber + "\\Parts\\" + file.getOriginalFilename() );
try {
Files.write(path, file.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Following is exception:
java.nio.file.NoSuchFileException: C:\DocumentRepository\12\Parts\b.pdf
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.spi.FileSystemProvider.newOutputStream(FileSystemProvider.java:434)
at java.nio.file.Files.newOutputStream(Files.java:216)
at java.nio.file.Files.write(Files.java:3292)
It looks for file on path and says no such file found.
This is new file i need to store at local.
Tried StandardOpenOption.CREATE_NEW but no effect.
The error indicates that C:\DocumentRepository\12\Parts isn't an existing directory. Files.write() will not make directories, no matter what you pass as standard open option.
Also your exception handling is broken. Fix your IDE template, that's just not okay. I've fixed that in the below snippet.
If your intent is to always create the directory if it doesn't yet exist:
public void storePartsFile(MultipartFile file, Long jobNumber) throws IOException {
Path path = Paths.get("C:\\DocumentRepository\\" +jobNumber + "\\Parts\\" + file.getOriginalFilename() );
Files.createDirectories(path.getParent());
Files.write(path, file.getBytes());
}
NB: If you don't want your method to throw IOException (you're probably wrong on that, a method named 'savePartsFile' should definitely be throwing that), the right ¯\(ツ)/¯ I dunno how to deal with it code for an exception handler is throw new RuntimeException("Uncaught", e);, not what you have. throwing the runtimeexception means all relevant info about the error is preserved, and code execution stops, instead of just more or less silently chugging on, oblivious that errors have occurred.

Unable to get path even though it is correct

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.

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);
}

Error in file is :- java.io.FileNotFoundException: \files\storetime.txt (The system cannot find the path specified)

i am using eclipse for develop the java desktop application and working with file but got the above error
my code is as following please try to help me how to give path in eclipse and also get same problem to load image from the given task
i have put the "files" folder out side the "src" folder
how to give path dynamically
my code is ass following
public int getTimeId()
{
LOG.info("The File name is :- " + fileName);
LOG.info("The path is :- ");
int count=0;
FileInputStream fileInputStream;
ObjectInputStream objectInputStream;
try
{
fileInputStream=new FileInputStream("/files/storetime.txt");
objectInputStream=new ObjectInputStream(fileInputStream);
while(objectInputStream.readObject()!=null)
{
count++;
}
}
catch(IOException e)
{
System.out.println("Error in file is :- " + e);
} catch (ClassNotFoundException e) {
System.out.println("Error in class not found :- " + e);
}
return count;
}
}
You are providing the absolute path by prep-ending / in the path. It means root directory in Unix file system. so, you have to give a relative path of the file from the current directory.You can put files directory in the root directory of your project folder and use
fileInputStream=new FileInputStream("files/storetime.txt");
So, it will be picked up
Use FileInputStream(new File("files/storetime.txt")); don't use /file -> it will check for /file partition in linux as /root

how do i create http visible files from java web application?

How can I create files visible by http protocol from java web application in web/myFiles folder ?
Is this even possible ?
for the following code :
String realPath = getServletContext().getRealPath("/");
System.out.println(realPath);
try {
BufferedWriter out = new BufferedWriter(new FileWriter( realPath + "\\myFiles\\test.txt"));
out.write("aString\nthis is a\nttest");
out.close();
} catch (IOException e) {
System.out.println("Exception " + e);
}
i keep getting the error :
Exception java.io.FileNotFoundException: C:\Documents and Settings\Andrei\My Documents\NetBeansProjects\SemanticCashUpV1.0\build\web\myFiles\test.txt (The system cannot find the path specified)
Yes possible,
You need to create file in public web area.
near to WEB-INF Dir.
you can get path to public web space by
request.getServletContext().getRealPath("/");

Categories