How to download a file into the specific folder in java? - java

I am working on an application which will download 3rd party dependencies to a particular folder and then execute dependency check on it. The files downloaded can be of any type, they can be zip, jar or may b a folder. I am trying to find a code example but nothing seems to work for me. I tried NIO in java but that seems to work only for writing to a particular file not folder. Below is code where I used NIO
// Checking If The File Exists At The Specified Location Or Not
Path filePathObj = Paths.get(filePath);
boolean fileExists = Files.exists(filePathObj);
if(fileExists) {
try {
urlObj = new URL(sampleUrl);
rbcObj = Channels.newChannel(urlObj.openStream());
fOutStream = new FileOutputStream(filePath);
fOutStream.getChannel().transferFrom(rbcObj, 0, Long.MAX_VALUE);
System.out.println("! File Successfully Downloaded From The Url !");
} catch (IOException ioExObj) {
System.out.println("Problem Occured While Downloading The File= " + ioExObj.getMessage());
} finally {
try {
if(fOutStream != null){
fOutStream.close();
}
if(rbcObj != null) {
rbcObj.close();
}
} catch (IOException ioExObj) {
System.out.println("Problem Occured While Closing The Object= " + ioExObj.getMessage());
}
}
} else {
System.out.println("File Not Present! Please Check!");
}```

public Class CopyAndWrite {
public static final String SOURCES = "C:\\Users\\Administrator\\Desktop\\resources";
public static final String TARGET = "C:\\Users\\Administrator\\Desktop\\111";
public static void main (String[]args) throws IOException {
Path startingDir = Paths.get(SOURCES);
Files.walkFileTree(startingDir, new FindJavaVisitor());
}
private static class FindJavaVisitor extends SimpleFileVisitor<Path> {
#Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
if (!StringUtils.equals(dir.toString(), SOURCES)) {
Path targetPath = Paths.get(TARGET + dir.toString().substring(SOURCES.length()));
if (!Files.exists(targetPath)) {
Files.createDirectory(targetPath);
}
}
return FileVisitResult.CONTINUE;
}
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Path targetPath = Paths.get(TARGET + file.toString().substring(SOURCES.length()));
copyFile(targetPath, Files.readAllBytes(file));
return FileVisitResult.CONTINUE;
}
}
private static void copyFile (Path path,byte[] bytes){
// write file
try {
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Using OKHttpClient to download the file and place in a folder.
Request request = new Request.Builder().url(downloadUrl).build();
Response response;
try {
response = client.newCall(request).execute();
if (response.isSuccessful()) {
fileName = abc.zip
Path targetPath = new File(inDir + File.separator + fileName).toPath();
try (FileOutputStream fos = new FileOutputStream(targetPath)) {
fos.write(response.body().bytes());
}
return 0;
}
} catch (IOException e) {
logger.error(e.getMessage());
}```

Related

how to backup file in java?

In reality its just making a copy of a text.txt file. I know how to use file chooser to choose the file but that is as far as my knowledge really goes.
I can do this:
public BasicFile()
{
JFileChooser choose = new JFileChooser(".");
int status = choose.showOpenDialog(null);
try
{
if (status != JFileChooser.APPROVE_OPTION) throw new IOException();
f = choose.getSelectedFile();
if (!f.exists()) throw new FileNotFoundException();
}
catch(FileNotFoundException e)
{
display(1, e.toString(), "File not found ....");
}
catch(IOException e)
{
display(1, e.toString(), "Approve option was not selected");
}
}
Path object is perfect for copying files,
Try this code to copy a file,
Path source = Paths.get("c:\\blabla.txt");
Path target = Paths.get("c:\\blabla2.txt");
try {
Files.copy(source, target);
} catch (IOException e1) {
e1.printStackTrace();
}
If you have to backup a whole folder, you can use this code
public class BackUpFolder {
public void copy(File sourceLocation, File targetLocation) throws IOException {
if (sourceLocation.isDirectory()) {
copyDirectory(sourceLocation, targetLocation);
} else {
copyFile(sourceLocation, targetLocation);
}
}
private void copyDirectory(File source, File target) throws IOException {
if (!target.exists()) {
target.mkdir();
}
for (String f : source.list()) {
copy(new File(source, f), new File(target, f));
}
}
private void copyFile(File source, File target) throws IOException {
try (
InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(target)) {
byte[] buf = new byte[1024];
int length;
while ((length = in.read(buf)) > 0) {
out.write(buf, 0, length);
}
}
}
public static void main(String[] args) {
try {
BackUpFolder backUpFolder = new BackUpFolder();
String location = "./src/edu/abc/locationFiles/daofile"; //File path you are getting from file chooser
String target = "./src"; //target place you want to patse
File locFile = new File(location);
File tarFile = new File(target);
backUpFolder.copyDirectory(locFile, tarFile);
} catch (IOException ex) {
Logger.getLogger(BackUpFolder.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Start by taking a look at Basic I/O, which explains the basics of Input/OutputStreams and Readers and Writers, which are used to read/write bytes of data from a source to a destination.
If you're using Java 7 or over, you should also take a look at Copying a File or Directory which is part of newer Files and Paths API, which you can find more information about at File I/O (Featuring NIO.2)

upload searched files on to a server

i code a program that searches for files in hard disk successfully. but now i want to add one more capability to it. i want that my program will upload these searched file on to a server through http. so can anyone explain what will be the strategy for this?
Here is my little program
public class Find {
public static class Finder extends SimpleFileVisitor<Path> {
private final PathMatcher matcher;
private int numMatches = 0;
Finder(String pattern)
{
matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
}
// Compares the glob pattern against
// the file or directory name.
void find(Path file)
{
Path name = file.getFileName();
if (name != null && matcher.matches(name))
{
numMatches++;
System.out.println(file);
}
}
// Prints the total number of
// matches to standard out.
void done()
{
System.out.println("Matched: "
+ numMatches);
}
// Invoke the pattern matching
// method on each file.
//#Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs)
{
find(file);
return CONTINUE;
}
// Invoke the pattern matching
// method on each directory.
//#Override
public FileVisitResult preVisitDirectory(Path dir,
BasicFileAttributes attrs)
{
find(dir);
return CONTINUE;
}
//#Override
public FileVisitResult visitFileFailed(Path file,IOException exc)
{
System.err.println(exc);
return CONTINUE;
}
}
static void usage()
{
System.err.println("java Find <path>" +" -name \"<glob_pattern>\"");
System.exit(-1);
}
public static void main(String[] args)throws IOException
{
if (args.length < 1 )
{
usage();
}
Iterable<Path> root;
root = FileSystems.getDefault().getRootDirectories();
for (Path startingDir : FileSystems.getDefault().getRootDirectories())
{
String pattern = args[0];
Finder finder = new Finder(pattern);
Files.walkFileTree(startingDir, finder);
//finder.done();
}
}
}
OK, so assuming you've got an absolute filename of the File.
Just a rough idea of what should be done (not tested):
FileInputStream fileInputStream = null;
try {
new FileInputStream("absoluteFilename");
byte[] buffer = new byte[MAX_SIZE];
int bufferIndex = 0;
while (fileInputStream.available() > 0) {
buffer[bufferIndex++] = (byte) fileInputStream.read();
}
byte[] fileContent = new byte[bufferIndex];
System.arraycopy(buffer,0,fileContent,0,bufferIndex);
URL serverUrl = new URL(url);
URLConnection connection = serverURL.openConnection();
connection.setConnectTimeout(60000);
connection.getOutputStream().write(fileContent);
} catch (Exception fatal) {
//proper handling??
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (Exception ignored) {}
}
}

How to copy file from one location to another location?

I want to copy a file from one location to another location in Java. What is the best way to do this?
Here is what I have so far:
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
public class TestArrayList {
public static void main(String[] args) {
File f = new File(
"D:\\CBSE_Demo\\Demo_original\\fscommand\\contentplayer\\config");
List<String>temp=new ArrayList<String>();
temp.add(0, "N33");
temp.add(1, "N1417");
temp.add(2, "N331");
File[] matchingFiles = null;
for(final String temp1: temp){
matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(temp1);
}
});
System.out.println("size>>--"+matchingFiles.length);
}
}
}
This does not copy the file, what is the best way to do this?
You can use this (or any variant):
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
Also, I'd recommend using File.separator or / instead of \\ to make it compliant across multiple OS, question/answer on this available here.
Since you're not sure how to temporarily store files, take a look at ArrayList:
List<File> files = new ArrayList();
files.add(foundFile);
To move a List of files into a single directory:
List<File> files = ...;
String path = "C:/destination/";
for(File file : files) {
Files.copy(file.toPath(),
(new File(path + file.getName())).toPath(),
StandardCopyOption.REPLACE_EXISTING);
}
Update:
see also
https://stackoverflow.com/a/67179064/1847899
Using Stream
private static void copyFileUsingStream(File source, File dest) throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} finally {
is.close();
os.close();
}
}
Using Channel
private static void copyFileUsingChannel(File source, File dest) throws IOException {
FileChannel sourceChannel = null;
FileChannel destChannel = null;
try {
sourceChannel = new FileInputStream(source).getChannel();
destChannel = new FileOutputStream(dest).getChannel();
destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
}finally{
sourceChannel.close();
destChannel.close();
}
}
Using Apache Commons IO lib:
private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
FileUtils.copyFile(source, dest);
}
Using Java SE 7 Files class:
private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
Or try Googles Guava :
https://github.com/google/guava
docs:
https://guava.dev/releases/snapshot-jre/api/docs/com/google/common/io/Files.html
Use the New Java File classes in Java >=7.
Create the below method and import the necessary libs.
public static void copyFile( File from, File to ) throws IOException {
Files.copy( from.toPath(), to.toPath() );
}
Use the created method as below within main:
File dirFrom = new File(fileFrom);
File dirTo = new File(fileTo);
try {
copyFile(dirFrom, dirTo);
} catch (IOException ex) {
Logger.getLogger(TestJava8.class.getName()).log(Level.SEVERE, null, ex);
}
NB:- fileFrom is the file that you want to copy to a new file fileTo in a different folder.
Credits - #Scott: Standard concise way to copy a file in Java?
public static void copyFile(File oldLocation, File newLocation) throws IOException {
if ( oldLocation.exists( )) {
BufferedInputStream reader = new BufferedInputStream( new FileInputStream(oldLocation) );
BufferedOutputStream writer = new BufferedOutputStream( new FileOutputStream(newLocation, false));
try {
byte[] buff = new byte[8192];
int numChars;
while ( (numChars = reader.read( buff, 0, buff.length ) ) != -1) {
writer.write( buff, 0, numChars );
}
} catch( IOException ex ) {
throw new IOException("IOException when transferring " + oldLocation.getPath() + " to " + newLocation.getPath());
} finally {
try {
if ( reader != null ){
writer.close();
reader.close();
}
} catch( IOException ex ){
Log.e(TAG, "Error closing files when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
}
}
} else {
throw new IOException("Old location does not exist when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
}
}
Copy a file from one location to another location means,need to copy the whole content to another location.Files.copy(Path source, Path target, CopyOption... options) throws IOException this method expects source location which is original file location and target location which is a new folder location with destination same type file(as original).
Either Target location needs to exist in our system otherwise we need to create a folder location and then in that folder location we need to create a file with the same name as original filename.Then using copy function we can easily copy a file from one location to other.
public static void main(String[] args) throws IOException {
String destFolderPath = "D:/TestFile/abc";
String fileName = "pqr.xlsx";
String sourceFilePath= "D:/TestFile/xyz.xlsx";
File f = new File(destFolderPath);
if(f.mkdir()){
System.out.println("Directory created!!!!");
}
else {
System.out.println("Directory Exists!!!!");
}
f= new File(destFolderPath,fileName);
if(f.createNewFile()) {
System.out.println("File Created!!!!");
} else {
System.out.println("File exists!!!!");
}
Files.copy(Paths.get(sourceFilePath), Paths.get(destFolderPath, fileName),REPLACE_EXISTING);
System.out.println("Copy done!!!!!!!!!!!!!!");
}
You can do it with the Java 8 Streaming API, PrintWriter and the Files API
try (PrintWriter pw = new PrintWriter(new File("destination-path"), StandardCharsets.UTF_8)) {
Files.readAllLines(Path.of("src/test/resources/source-file.something"), StandardCharsets.UTF_8)
.forEach(pw::println);
}
If you want to modify the content on-the-fly while copying, check out this link for the extended example https://overflowed.dev/blog/copy-file-and-modify-with-java-streams/
I modified one of the answers to make it a bit more efficient.
public void copy(){
InputStream in = null;
try {
in = new FileInputStream(Files);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
OutputStream out = new FileOutputStream();
try {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
while (true) {
int len = 0;
try {
if (!((len = in.read(buf)) > 0)) break;
} catch (IOException e) {
e.printStackTrace();
}
try {
out.write(buf, 0, len);
} catch (IOException e) {
e.printStackTrace();
}
}
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void moveFile() {
copy();
File dir = getFilesDir();
File file = new File(dir, "my_filename");
boolean deleted = file.delete();
}
Files.exists()
Files.createDirectory()
Files.copy()
Overwriting Existing Files:
Files.move()
Files.delete()
Files.walkFileTree()
enter link description here
You can use
FileUtils.copy(sourceFile, destinationFile);
https://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html

How to copy an entire content from a directory to another in Java?

File content[] = new File("C:/FilesToGo/").listFiles();
for (int i = 0; i < content.length; i++){
String destiny = "C:/Kingdoms/"+content[i].getName();
File desc = new File(destiny);
try {
Files.copy(content[i].toPath(), desc.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
This is what I have. It copies everything just fine.
But among the contents there are some folders. The folders are copied but the folder's contents are not.
Would recommend using FileUtils in Apache Commons IO:
FileUtils.copyDirectory(new File("C:/FilesToGo/"),
new File("C:/Kingdoms/"));
Copies directories & contents.
Recursion. Here is a method the uses rescursion to delete a system of folders:
public void move(File file, File targetFile) {
if(file.isDirectory() && file.listFiles() != null) {
for(File file2 : file.listFiles()) {
move(file2, new File(targetFile.getPath() + "\\" + file.getName());
}
}
try {
Files.copy(file, targetFile.getPath() + "\\" + file.getName(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
Didn't test the code, but it should work. Basically, it digs down into the folders, telling it to move the item, if its a folder, go through all its children, and move them, etc.
Just to clarify what needs to be changed in Alex Coleman's answer, for the code to work. Here is the modified version of Alex's code that I tested and that works fine for me:
private void copyDirectoryContents(File source, File destination){
try {
String destinationPathString = destination.getPath() + "\\" + source.getName();
Path destinationPath = Paths.get(destinationPathString);
Files.copy(source.toPath(), destinationPath, StandardCopyOption.REPLACE_EXISTING);
}
catch (UnsupportedOperationException e) {
//UnsupportedOperationException
}
catch (DirectoryNotEmptyException e) {
//DirectoryNotEmptyException
}
catch (IOException e) {
//IOException
}
catch (SecurityException e) {
//SecurityException
}
if(source.isDirectory() && source.listFiles() != null){
for(File file : source.listFiles()) {
copyDirectoryContents(file, new File(destination.getPath() + "\\" + source.getName()));
}
}
}
The question is old by now, but I wanted to share my copy methods using java.nio.file.
Copying source directory: src into a container directory: dst.
"Directory" is just a helper class. In this example you can think of it as "Path" container.
We separate the directory structure from the file content.
It's explicit, and easy to imagine. (Also, it avoids some potential Exceptions thrown by the Files.copy() method if you instead copied all files in "one go")
public static void copy(Directory src, Directory dst, boolean replace) throws IOException {
if (src == null || dst == null) throw new IllegalArgumentException("...");
Path sourcePath = src.path();
Path targetPath = dst.path().resolve(sourcePath.getFileName());
copyStructure(sourcePath,targetPath);
copyContent(sourcePath,targetPath,replace);
}
I.e. we want to copy the folder "top" into the "dst" folder "container".
sourcePath = ...some/location/top
targetPath = ...another/location/container/top
copyStructure: Iterates through the source files. If the source file is a directory and the a target file with equivalent name does not exist, we create
the target folder. (So "copy" is not accurate. We "assure" structure)
private static void copyStructure(final Path source, final Path target) throws IOException {
if (source == null || target == null) throw new IllegalArgumentException("...");
final String tarString = target.toString();
final String srcString = source.toString();
Files.walk(source).forEach(new Consumer<Path>() {
#Override
public void accept(Path srcPath) {
if (Files.isDirectory(srcPath)) {
String subString = srcPath.toString().substring(srcString.length());
Path newFolder = Path.of(tarString,subString);
if (!Files.exists(newFolder)) {
try { Files.createDirectory(newFolder);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
}
Now that we know that a target directory structure exists, we iterate the source files again. But now we only copy the "content" (regular files). Choosing whether to replace existing content. copyContent:
private static void copyContent(final Path source, final Path target, boolean replace) throws IOException {
if (source == null || target == null) throw new IllegalArgumentException("...");
final String tarString = target.toString();
final String srcString = source.toString();
Files.walk(source).forEach(new Consumer<Path>() {
#Override
public void accept(Path srcPath) {
if (Files.isRegularFile(srcPath)) {
String subString = srcPath.toString().substring(srcString.length());
Path newFile = Path.of(tarString,subString);
if (!Files.exists(newFile)) {
try { Files.copy(srcPath,newFile);
} catch (IOException e) {
e.printStackTrace();
}
} else {
if (replace) {
try { Files.copy(srcPath,newFile,
StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
});
}

Copy entire directory contents to another directory? [duplicate]

This question already has answers here:
Copying files from one directory to another in Java
(34 answers)
Closed 7 years ago.
Method to copy entire directory contents to another directory in java or groovy?
FileUtils.copyDirectory()
Copies a whole directory
to a new location preserving the file
dates. This method copies the
specified directory and all its child
directories and files to the specified
destination. The destination is the
new location and name of the
directory.
The destination directory is created
if it does not exist. If the
destination directory did exist, then
this method merges the source with the
destination, with the source taking
precedence.
To do so, here's the example code
String source = "C:/your/source";
File srcDir = new File(source);
String destination = "C:/your/destination";
File destDir = new File(destination);
try {
FileUtils.copyDirectory(srcDir, destDir);
} catch (IOException e) {
e.printStackTrace();
}
The following is an example of using JDK7.
public class CopyFileVisitor extends SimpleFileVisitor<Path> {
private final Path targetPath;
private Path sourcePath = null;
public CopyFileVisitor(Path targetPath) {
this.targetPath = targetPath;
}
#Override
public FileVisitResult preVisitDirectory(final Path dir,
final BasicFileAttributes attrs) throws IOException {
if (sourcePath == null) {
sourcePath = dir;
} else {
Files.createDirectories(targetPath.resolve(sourcePath
.relativize(dir)));
}
return FileVisitResult.CONTINUE;
}
#Override
public FileVisitResult visitFile(final Path file,
final BasicFileAttributes attrs) throws IOException {
Files.copy(file,
targetPath.resolve(sourcePath.relativize(file)));
return FileVisitResult.CONTINUE;
}
}
To use the visitor do the following
Files.walkFileTree(sourcePath, new CopyFileVisitor(targetPath));
If you'd rather just inline everything (not too efficient if you use it often, but good for quickies)
final Path targetPath = // target
final Path sourcePath = // source
Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult preVisitDirectory(final Path dir,
final BasicFileAttributes attrs) throws IOException {
Files.createDirectories(targetPath.resolve(sourcePath
.relativize(dir)));
return FileVisitResult.CONTINUE;
}
#Override
public FileVisitResult visitFile(final Path file,
final BasicFileAttributes attrs) throws IOException {
Files.copy(file,
targetPath.resolve(sourcePath.relativize(file)));
return FileVisitResult.CONTINUE;
}
});
With Groovy, you can leverage Ant to do:
new AntBuilder().copy( todir:'/path/to/destination/folder' ) {
fileset( dir:'/path/to/src/folder' )
}
AntBuilder is part of the distribution and the automatic imports list which means it is directly available for any groovy code.
public static void copyFolder(File source, File destination)
{
if (source.isDirectory())
{
if (!destination.exists())
{
destination.mkdirs();
}
String files[] = source.list();
for (String file : files)
{
File srcFile = new File(source, file);
File destFile = new File(destination, file);
copyFolder(srcFile, destFile);
}
}
else
{
InputStream in = null;
OutputStream out = null;
try
{
in = new FileInputStream(source);
out = new FileOutputStream(destination);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0)
{
out.write(buffer, 0, length);
}
}
catch (Exception e)
{
try
{
in.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
try
{
out.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
}
This is my piece of Groovy code for that. Tested.
private static void copyLargeDir(File dirFrom, File dirTo){
// creation the target dir
if (!dirTo.exists()){
dirTo.mkdir();
}
// copying the daughter files
dirFrom.eachFile(FILES){File source ->
File target = new File(dirTo,source.getName());
target.bytes = source.bytes;
}
// copying the daughter dirs - recursion
dirFrom.eachFile(DIRECTORIES){File source ->
File target = new File(dirTo,source.getName());
copyLargeDir(source, target)
}
}
Use Apache's
FileUtils.copyDirectory
Write
your own e.g. this guy provides
example code.
Java 7: take a look at java.nio.file.Files.
With coming in of Java NIO, below is a possible solution too
With Java 9:
private static void copyDir(String src, String dest, boolean overwrite) {
try {
Files.walk(Paths.get(src)).forEach(a -> {
Path b = Paths.get(dest, a.toString().substring(src.length()));
try {
if (!a.toString().equals(src))
Files.copy(a, b, overwrite ? new CopyOption[]{StandardCopyOption.REPLACE_EXISTING} : new CopyOption[]{});
} catch (IOException e) {
e.printStackTrace();
}
});
} catch (IOException e) {
//permission issue
e.printStackTrace();
}
}
With Java 7:
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.function.Consumer;
import java.util.stream.Stream;
public class Test {
public static void main(String[] args) {
Path sourceParentFolder = Paths.get("/sourceParent");
Path destinationParentFolder = Paths.get("/destination/");
try {
Stream<Path> allFilesPathStream = Files.walk(sourceParentFolder);
Consumer<? super Path> action = new Consumer<Path>(){
#Override
public void accept(Path t) {
try {
String destinationPath = t.toString().replaceAll(sourceParentFolder.toString(), destinationParentFolder.toString());
Files.copy(t, Paths.get(destinationPath));
}
catch(FileAlreadyExistsException e){
//TODO do acc to business needs
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
allFilesPathStream.forEach(action );
} catch(FileAlreadyExistsException e) {
//file already exists and unable to copy
} catch (IOException e) {
//permission issue
e.printStackTrace();
}
}
}
Neither FileUtils.copyDirectory() nor Archimedes's answer copy directory attributes (file owner, permissions, modification times, etc).
https://stackoverflow.com/a/18691793/14731 provides a complete JDK7 solution that does precisely that.
With regard to Java, there is no such method in the standard API. In Java 7, the java.nio.file.Files class will provide a copy convenience method.
References
The Java Tutorials
Copying files from one directory to another in Java
If you're open to using a 3rd party library, check out javaxt-core. The javaxt.io.Directory class can be used to copy directories like this:
javaxt.io.Directory input = new javaxt.io.Directory("/source");
javaxt.io.Directory output = new javaxt.io.Directory("/destination");
input.copyTo(output, true); //true to overwrite any existing files
You can also provide a file filter to specify which files you want to copy. There are more examples here:
http://javaxt.com/javaxt-core/io/Directory/Directory_Copy

Categories

Resources