Copy all files from Source to Destination Java - java

I have to code a java method public void public void copyTo(Path rSource, Path rDest) that copies all files from existing directory rSource to a new directory rDest with the same name. rSource must exist and rDest must not exist, runtime exception if not true. I can't seem to make it work, help!
What I tried :
public void copyTo(Path rSource, Path rDest){
if(!(Files.exists(rSource) && Files.isDirectory(rSource)) || (Files.exists(rDest))){
throw new RuntimeException();
}
try {
Files.createDirectory(rDest);
if(Files.exists(rDest)){
try(DirectoryStream<Path> stream = Files.newDirectoryStream(rSource)) {
for(Path p : stream) {
System.out.println(p.toString());
Files.copy(p, rDest);
}
} catch( IOException ex) {
}
}
} catch (IOException e) {
}
}

Files.copy() at least takes two parameters, source and destination files path or stream. The problem in your case is that you are passing rDest folder Path, not the actual file Path. Just modify the code inside your for loop to append the files name from the source to the destination folder Path:
Path newFile = Paths.get(rDest.toString() + "/" + p.getFileName());
Files.copy(p, newFile);
Correct me if I'm wrong

Related

Java file copy fails

I have written a very simple Java program to copy a file passed as an argument to the /tmp directory. The program produces several Java exceptions.
public class CopyFile {
public static void main(String[] args) throws IOException {
String fqp2File = "";
if (new File(args[0]).isFile()) {
fqp2File = args[0];
}
else {
System.out.println("Passed argument is not a file");
}
copy(fqp2File, "/tmp");
}
private static boolean copy(String from, String to) throws IOException{
Path src = Paths.get(from);
Path dest = Paths.get(to);
try {
Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);
return true;
} catch (IOException ioe) {
System.err.format("I/O Error when copying file");
ioe.printStackTrace();
return false;
}
}
}
When I run this program I get these errors:
java -jar CopyFile.jar /home/downloads/dfA485MVSZ.ncr.pwgsc.gc.ca.1531160874.13500750
I/O Error when copying filejava.nio.file.FileSystemException: /tmp:
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:103)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:114)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:119)
at sun.nio.fs.UnixCopyFile.copy(UnixCopyFile.java:578)
at sun.nio.fs.UnixFileSystemProvider.copy(UnixFileSystemProvider.java:265)
at java.nio.file.Files.copy(Files.java:1285)
at ca.gc.ssc.gems.esnap.cipo.CopyFile.copy(CopyFile.java:39)
at ca.gc.ssc.gems.esnap.cipo.CopyFile.main(CopyFile.java:31)
To test your code I used C:/tmp/test.txt; as your args[0]. I fixed the issue by giving the output a filename to write to shown below:
Path dest = Paths.get(to);
to
Path dest = Paths.get(to, "test2.txt");
And it now successfully copied the file into that name, you can modify the filename however you want or add logic to change filename automatically.

How to get the path of file when make a jar file in Java

I am building a game in java and everything works just fine when I run it in intellij idea with no error .
The problem start when i build my project as jar file.
I have this method :
public void addImageOfObject(String add, String dir, ArrayList<ImageIcon> linkedList, Dimension size) {
Image image;
String dirc;
File file = null;
try {
file = new File(classLoader.getResource(dir).getFile());
} catch (Exception e) {
JOptionPane.showMessageDialog(StaticVariables.mainClass, e.getStackTrace());
}
try {
for (int i = 0; file.listFiles().length > i; i++) {
try {
dirc = dir + i + ".png";
image = loadImage(dirc);
linkedList.add(new ImageIcon(image.getScaledInstance(size.width, size.height, 4)));
} catch (Exception e) {
JOptionPane.showMessageDialog(StaticVariables.mainClass, e.getStackTrace());
e.printStackTrace();
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(StaticVariables.mainClass, e.getStackTrace());
JOptionPane.showMessageDialog(StaticVariables.mainClass, "file not found ");
}
}
This is the class loader :
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
I can't get the right path of the file ..when i run it in jar file its give an error file not found on :
file = new File(classLoader.getResource(dir).getFile());
I call to method with this line :
imageLoader.addImageOfObject("src/main/java/","ImageHandel/Photos/character/male/attack/down/",aMale,new Dimension(500,400));
This is the path of files
The number of files I want to get file.listFiles()
In the male folder there is 44 files .. that's the number I want to get in order to run on the loop 44 time and i just can't find the right way to do it! I tried a lot of thing but nothing help me ..
Have any idea what is the problem ?
Simply you can create folder on location where your running jar file,
ImageHandel/Photos/character/male/attack/down/
Run it in jar file by considering that location.
use to add static folder for serving images e.g In spring boot we can configure static folder as follows:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/ImageHandel/**")
.addResourceLocations("file:ImageHandel/")
.setCachePeriod(0);
}

Moving a directory in java throws java.nio.file.FileAlreadyExistsException

I am creating a rollback feature and here is what I have and wanna achieve:
a tmp folder is created in the same location as the data folder;
before doing any operation I copy all the contents from data folder to tmp folder (small amount of data).
On rollback I want to delete the data folder and rename tmp folder to data folder.
This is what I tried
String contentPath = "c:\\temp\\data";
String tmpContentPath = "c:\\temp\\data.TMP";
if (Files.exists(Paths.get(tmpContentPath)) && Files.list(Paths.get(tmpContentPath)).count() > 0) {
FileUtils.deleteDirectory(new File(contentPath));
Files.move(Paths.get(tmpContentPath), Paths.get(contentPath), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
}
but this throws FileAlreadyExistsException even though I deleted the target directory in the same method.
Once the program exits I don't see the c:\temp\data directory, so the directory is actually deleted.
Now if I try StandardCopyOption.ATOMIC_MOVE it throws an java.nio.file.AccessDeniedException.
What is the best way to move tmp dir to data dir in these kind of situations?
Actually in java 7 or above you can just use the Files to achieve the folder moving even there is a conflict, which means the target folder already exists.
private static void moveFolder(Path thePath, Path targetPath) {
if (Files.exists(targetPath)) { // if the target folder exists, delete it first;
deleteFolder(targetPath);
}
try {
Files.move(thePath, targetPath);
} catch (IOException ignored) {
ignored.printStackTrace();
}
}
private static void deleteFolder(Path path) {
try {
if (Files.isRegularFile(path)) { // delete regular file directly;
Files.delete(path);
return;
}
try (Stream<Path> paths = Files.walk(path)) {
paths.filter(p -> p.compareTo(path) != 0).forEach(p -> deleteFolder(p)); // delete all the children folders or files;
Files.delete(path); // delete the folder itself;
}
} catch (IOException ignored) {
ignored.printStackTrace();
}
}
Try This
public class MoveFolder
{
public static void main(String[] args) throws IOException
{
File sourceFolder = new File("c:\\temp\\data.TMP");
File destinationFolder = new File("c:\\temp\\data");
if (destinationFolder.exists())
{
destinationFolder.delete();
}
copyAllData(sourceFolder, destinationFolder);
}
private static void copyAllData(File sourceFolder, File destinationFolder)
throws IOException
{
destinationFolder.mkdir();
String files[] = sourceFolder.list();
for (String file : files)
{
File srcFile = new File(sourceFolder, file);
File destFile = new File(destinationFolder, file);
copyAllData(srcFile, destFile); //call recursive
}
}
}
Figured out the issue. In my code before doing a rollback, I am doing a backup, in that method I am using this section to do the copy
if (Files.exists(Paths.get(contentPath)) && Files.list(Paths.get(contentPath)).count() > 0) {
copyPath(Paths.get(contentPath), Paths.get(tmpContentPath));
}
Changed it to
try (Stream<Path> fileList = Files.list(Paths.get(contentPath))) {
if (Files.exists(Paths.get(contentPath)) && fileList.count() > 0) {
copyPath(Paths.get(contentPath), Paths.get(tmpContentPath));
}
}
to fix the issue

Java file deletion fails

I need to delete files from within a java program and have written this code. It fails to delete the file and I can't figure why. The File is not in use and not write protected.
public static void delfile(String filetodel) {
try {
File file = new File("filetodel");
if (file.delete()) {
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed." + filetodel);
}
} catch (Exception e) {
e.printStackTrace();
}
}
I guess the issue is this:
File file = new File("filetodel");
This should possibly be (inferred from the parameter filetodel passed in the method):
File file = new File(filetodel);
Everything else seems fine, and is working on my machine.
If you just want to delete the file, there is no need for loading it.
java.nio.file.Files.deleteIfExists(filetodel); (where filetodel contains the path to the file)
Returns true if the file was deleted, so you can even put it in your if-clause.
hey buddy you should use a path as parameter in delete
static void delete(Path path)
Deletes a file.
static boolean deleteIfExists(Path path)
Deletes a file if it exists.
search here: http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html
so in your case
File file = new File("c://user//filetodel");
file.delete();
or use getAbsolutePath(filename) and use it in file path
Here is my code to delete file.
public class deletef
{
public static void main(String[] args)
{
try{
File file = new File("/home/rahul/Downloads/ou.txt");
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
your code is also right but you have to put extension also in your file
File file = new File("filetodel");
here add extension also of file other wise your code will not delete file

How to find sub-directories in a directory/folder?

I'm looking for a way to get all the names of directories in a given directory, but not files.
For example, let's say I have a folder called Parent, and inside that I have 3 folders: Child1 Child2 and Child3.
I want to get the names of the folders, but don't care about the contents, or the names of subfolders inside Child1, Child2, etc.
Is there a simple way to do this?
If you are on java 7, you might wanna try using the support provided in
package java.nio.file
If your directory has many entries, it will be able to start listing them without reading them all into memory first. read more in the javadoc: http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#newDirectoryStream(java.nio.file.Path,%20java.lang.String)
Here is also that example adapted to your needs:
public static void main(String[] args) {
DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
#Override
public boolean accept(Path file) throws IOException {
return (Files.isDirectory(file));
}
};
Path dir = FileSystems.getDefault().getPath("c:/");
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, filter)) {
for (Path path : stream) {
// Iterate over the paths in the directory and print filenames
System.out.println(path.getFileName());
}
} catch (IOException e) {
e.printStackTrace();
}
}
You can use String[] directories = file.list() to list all file names,
then use loop to check each sub-files and use file.isDirectory() function to get subdirectories.
For example:
File file = new File("C:\\Windows");
String[] names = file.list();
for(String name : names)
{
if (new File("C:\\Windows\\" + name).isDirectory())
{
System.out.println(name);
}
}
public static void displayDirectoryContents(File dir) {
try {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
System.out.println("Directory Name==>:" + file.getCanonicalPath());
displayDirectoryContents(file);
} else {
System.out.println("file Not Acess===>" + file.getCanonicalPath());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
====inside class/Method provide File=URL ======
File currentDir = new File("/home/akshya/NetBeansProjects/");
displayDirectoryContents(currentDir);
}

Categories