Moving file into a different directory - java

I am trying to move the failed files to different directory.
Currently, everything seems to work fine except that it creates a file(just plan file without extension). I want directory to be created and all the failed files to go into that directory. Here is my code below. what seems to be wrong?
Path source= Paths.get(("C:/Users/aa/Desktop/whatever" + originalfilename));
Path target = Paths.get("C:/Users/aa/Desktop/Directory1 " );
Files.move(source,target, REPLACE_EXISTING, COPY_ATTRIBUTES);
PS: originalfilename(String) are the filenames of the directory. If I execute it, it gives a file Directory1, but it's not a directory folder.

Try this code instead:
File yourFile=new File("D:\\irectory\\Afile.txt");
if(yourFile.renameTo(new File("D:\\irectory\\" + yourFile.getName())))
System.out.println("File moved succesfully bro!");
else
System.out.println("Errors moving the file.");

From the JavaDoc:
Path source = ...
Path newdir = ...
Files.move(source, newdir.resolve(source.getFileName()), REPLACE_EXISTING);
http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#move%28java.nio.file.Path,%20java.nio.file.Path,%20java.nio.file.CopyOption...%29

Related

Packaged Jar unable to read files from mapped network drive (Windows)

I have a Spring Boot application which reads files in folders on a mapped network drive, i.e. m:/PRODUCTION
The problem is, when I execute the jar file, my debugging output shows that no files exist in the folder, even though the folder is full of a files.
I have IntelliJ installed on the same machine, and if I run the application from it's source code, it works absolutely fine.
The method I have that reads filename to an array is;
private File[] getFilesInPath(String path) {
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
if (listOfFiles != null) {
Arrays.sort(listOfFiles, Comparator.comparingLong(File::lastModified));
}
return listOfFiles;
}
Then, I call this function from a number of places in the application, here's an example;
public void manuallyProcessAttritionData(List<Line> lines) {
Handler handler = new AttritionHandler().setLines(lines).setService(this);
String pathToProcess = dataFolder + attritionFolder;
log.debug("Processing path: " + pathToProcess);
File[] listOfFiles = getFilesInPath(pathToProcess);
if (listOfFiles != null) {
log.debug("Number of files to process: " + listOfFiles.length);
for (File file : listOfFiles) {
handler.processFile(file);
}
} else {
log.debug("No files to process");
}
}
The output from running the above is;
Processing ATTRITION data...
Processing path: m:/PRODUCTION
No files to process
...Finished processing ATTRITION data
I've confirmed the path is correct, running the following commands from the command line works fine and there are files in the result;
cd m:\PRODUCTION
M:\PRODUCTION>
Does anyone know of a reason why the folder can be read perfectly find from the application running in IntelliJ, but not when packaged as a JAR file?
Looks like your development account Intellij has access to this drive where as the account which started this spring-boot doesn't have access to it.
I would suggest using full path instead of a mapped network path.
There should be no difference in running the code from intelliJ or running it from the built jar. But there may be other factors comming into play. Maybe you run intelliJ with a different user than the jvm that runs the jar? I propose the following steps to resolve the issue:
1. Use the Path Class to avoid platform specific problems (eg. file separators)
Instead of
new File("path/to/my/directory");
you should use
Paths.get("path", "to", "my", "directory").toFile()
or
Paths.get("path/to/my/directory").toFile()
2. Check the file attributes
Use the code below to investigate if the directory exists, if you have the correct permissions etc.
Path directory = Paths.get("e:/TEMP");
System.out.println("Absolute Path of directory: " + directory.toAbsolutePath());
System.out.println("Directory exists: " + directory.toFile().exists());
System.out.println("Directory is a directory: " + directory.toFile().isDirectory());
System.out.println("Directory isReadable: " + directory.toFile().canRead());
System.out.println("Directory isWriteable: " + directory.toFile().canWrite());
this should output something like:
Absolute Path of directory: e:\TEMP
Directory exists: true
Directory is a directory: true
Directory isReadable: true
Directory isWriteable: true

How to move a directory recursively using Apache commons-io, if destination exists?

I've been trying to get the following simple code to work and I don't understand why it's failing:
File dir = new File("/foo/bar"); // A path to a directory
File destDir = new File("/blah"); // The destination dir
FileUtils.moveDirectoryToDirectory(dir, destDir, !destDir.exists());
The dir directory contains files and directories. The destDir may, or may not contain bar.
The error I get is:
Caused by: org.apache.commons.io.FileExistsException: Destination '/blah/bar' already exists
What am I doing wrong here?
Would the built-in Files.move(...) do a better job (I am using JDK 1.8)? I tried that as well, but I couldn't seem to get it to work. This is simple stuff and I can't get why it's so much of an effort to implement...
Try copyDirectoryToDirectory() instead and then delete the original source...

Get directory from classpath (getting a file now)

I want to search for files in a directory. Therefore I want to get the directory in a File object but i'm getting a file instead of a directory. This is what I'm doing, it prints false but I want it to be true.
URL url = getClass().getResource("/strategy/viewconfigurations/");
File folder = new File(url.toString());
System.out.println(folder.isDirectory());
How can I load this way a directory?
It seems path or String you will got from the URL object cause problem.
You passed file path which you will got from the url.toString().
You need to change below line
File folder = new File(url.toString());
with this line
File folder = new File(url.getPath());
You need path of that folder which will you get from URL.getPath() function.
I hope this is what you need.
If you need an alternative for Java 7+ to Yagnesh Agola's post for finding a directory from a classpath folder, you could you also the newer java.nio.file.Path class.
Here is an example:
URL outputXml = Thread.currentThread().getContextClassLoader().getResource("outputXml");
if(outputXml == null) {
throw new RuntimeException("Cannot find path in classpath");
}
Path path = Paths.get(outputXml.toURI());

How to specify a directory when creating a File object?

This should be a really simple question but Google + my code isn't working out.
In Eclipse on Windows, I want my program to look inside a certain folder. The folder is directly inside the Project folder, on the same level as .settings, bin, src, etc. My folder is called surveys, and that's the one I want my File object to point at.
I don't want to specify the full path because I want this to run on both of my computers. Just the path immediately inside my Project.
I'm trying this code but it isn't working - names[] is coming back null. And yes I have some folders and test junk inside surveys.
File file = new File("/surveys");
String[] names = file.list();
for(String name : names)
{
if (new File("/surveys/" + name).isDirectory())
{
System.out.println(name);
}
}
I'm sure my mistake is within the String I'm passing to File, but I'm not sure what's wrong?
In your question you didn't specify what platform you are running on. On non-Windows, a leading slash signifies an absolute path. Best to remove the leading slash. Try this:
File file = new File("surveys");
System.out.println("user.dir=" + System.getProperty("user.dir"));
System.out.println("file is at: " + file.getCanonicalPath());
String[] names = file.list();
for(String name : names)
{
if (new File(file, name).isDirectory())
{
System.out.println(name);
}
}
Make sure the in your run configuration, the program is running from the projects directory (user.dir = <projects>)
Make sure that your file is a directory before using file.list() on it, otherwise you will get a nasty NullPointerException.
File file = new File("surveys");
if (file.isDirectory()){
...
}
OR
if (names!=null){
...
}
If you checked the full path of your file with
System.out.println(file.getCanonicalPath())
the picture would immediately become clear. File.getCanonicalPath gives you exactly the full path. Note that File normalizes the path, eg on Windows "c:/file" is converted to "C:\file".

Problem with moving a file to another folder

I am using:
// File (or directory) to be moved
File file = new File(output.toString());
// Destination directory
File dir = new File(directory_name);
// Move file to new directory
boolean success = file.renameTo(new File(dir, new_file.getName()));
if (!success) {
// File was not successfully moved
}
In this case file is main.vm, and folder is seven
the program shows that it works(the file exists and all) but the file is not moving to the seven directory.
Any ideas why?
Is it ok that the file name is main.vm or do i need to enter full path? the same for the folder.
Thanks
Maybe you wanna take a look at the Apache Commons FileUtils
Works for me. (run with java -ea opt.)
File f = new File("foo.mv");
if(!f.exists())
assert f.createNewFile() : "failed to create foo.mv";
File folder = new File("7");
if(!folder.exists())
assert folder.mkdir() : "failed to create new directory";
File fnew = new File(folder, f.getName());
assert !fnew.exists() : "fnew already exists";
f.renameTo(fnew);
assert fnew.exists() : "fnew does not exist -- move failed";
System.out.format("moved %s to %s\n",f, fnew);
Try to do following steps:
check if you move the file inside same filesystem - otherwise it will fail;
create destination directory;
define "new_file" variable.
You need to enter full path of the file, not only the filename. And would be nice if you'll show up your full source code in the future, for better understanding/answers.

Categories

Resources