I have a zip file with the structure like:
xml.zip
Root Folder: package
Folder: Subfolder.zip
Inside Subfolder.zip :
Root Folder: _
Folder: var
Folder: run
Folder: xmls
Xml1.xml
Xml2.xml
Xml3.xml
Is there a way to read in these three files recursively with the above structure? I've tried using ZipInputStream and ZipArchiveInputStream, but zip.getNextEntry() keeps returning null.. due to the nested zip. Anyway to recursively use it?
private void readZipFileStream(final InputStream zipFileStream) {
final ZipInputStream zipInputStream = new ZipInputStream(zipFileStream);
ZipEntry zipEntry;
try {
zipEntry = zipInputStream.getNextEntry();
while(zipEntry.getName() != null) {
System.out.println("name of zip entry: " + zipEntry.getName());
if (!zipEntry.isDirectory()) {
System.out.println("1."+zipInputStream.available());
System.out.println("2."+zipEntry.getName());
System.out.println("3."+zipEntry.isDirectory());
System.out.println("4."+zipEntry.getSize());
} else {
readZipFileStream(zipInputStream);
}
zipEntry = zipInputStream.getNextEntry();
}
// }
} catch (IOException e) {
e.printStackTrace();
}
}
Can someone please help?
recursive call should be done when the zip entry is identified as zip file. Use zipEntry.getName().endsWith(".zip") to identify and then call the same function.
public static void readZip(InputStream fileStream) throws IOException
{
ZipInputStream zipStream = new ZipInputStream(fileStream);
ZipEntry zipEntry = zipStream.getNextEntry();
try {
while(zipEntry !=null) {
String fileName = zipEntry.getName();
if (fileName.endsWith(".zip")) {
//recur if the entry is a zip file
readZip(zipStream);
}
else {
System.out.println(zipEntry.getName());
}
zipEntry = zipStream.getNextEntry();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Started working after calling the same function again if getName().contains(".zip").
Related
I use this code to list files into directory and move it based on a found value.
#Override
public void execute(JobExecutionContext context) {
File directoryPath = new File("C:\\csv\\nov");
// Create a new subfolder called "processed" into source directory
try {
Path processedFolderPath = Path.of(directoryPath.getAbsolutePath() + "/processed");
if (!Files.exists(processedFolderPath) || !Files.isDirectory(processedFolderPath)) {
Files.createDirectory(processedFolderPath);
}
Path invalidFilesFolderPath = Path.of(directoryPath.getAbsolutePath() + "/invalid_files");
if (!Files.exists(invalidFilesFolderPath) || !Files.isDirectory(invalidFilesFolderPath)) {
Files.createDirectory(invalidFilesFolderPath);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
FilenameFilter textFileFilter = (dir, name) -> {
String lowercaseName = name.toLowerCase();
if (lowercaseName.endsWith(".csv")) {
return true;
} else {
return false;
}
};
// List of all the csv files
File filesList[] = directoryPath.listFiles(textFileFilter);
System.out.println("List of the text files in the specified directory:");
for(File file : filesList) {
try {
try (var br = new FileReader(file.getAbsolutePath(), StandardCharsets.UTF_16)){
List<CsvLine> beans = new CsvToBeanBuilder(br)
.withType(CsvLine.class)
.withSeparator('\t')
.withSkipLines(3)
.build()
.parse();
for (CsvLine item : beans)
{
Path originalPath = file.toPath();
if(item.getValue().equals(2)
|| item.getValue().equals(43)
|| item.getValue().equals(32))
{
// Move here file into new subdirectory when file is invalid
Path copied = Paths.get(file.getParent() + "/invalid_files");
try {
// Use resolve method to keep the "processed" as folder
br.close();
Files.move(originalPath, copied.resolve(originalPath.getFileName()), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new RuntimeException(e);
}
}}
} catch (Exception e){
e.printStackTrace();
}
Path originalPath = file.toPath();
System.out.println(String.format("\nProcessed file : %s, moving the file to subfolder /processed\n",
originalPath));
}
// Move here file into new subdirectory when file processing is finished
Path copied = Paths.get(file.getParent() + "/processed");
try {
// Use resolve method to keep the "processed" as folder
br.close();
Files.move(originalPath, copied.resolve(originalPath.getFileName()), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
The problem is that I try to move a file. I get error:
java.lang.RuntimeException: java.nio.file.NoSuchFileException: C:\csv\nov\12_21_39.csv
at com.wordscore.engine.processor.DataValidationCheckJob.execute(DataValidationCheckJob.java:94)
at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573)
Caused by: java.nio.file.NoSuchFileException: C:\csv\nov\12_21_39.csv
How I can edit the code in way that it can be moved properly?
It looks like you have omitted break; after both Files.move(originalPath, ...); calls.
Without a break to exit the for (CsvLine item : beans) loop, processing continues over the next iteration. The second iteration will attempt to perform Files.move(originalPath, ...) again - and fails because the file has already been moved.
Therefore you get the NoSuchFileException which you have re-thrown as RuntimeException in your try.. Files.move .. catch block.
The handling would be cleaner if you dealt with move in one place and such that it avoids the untidy br.close(), leaving file handling to the auto-close try() block. Something like this:
Path invalidDir = Paths.get(file.getParent() + "/invalid_files");
Path processedDir = Paths.get(file.getParent() + "/processed");
for(File file : filesList) {
Path originalPath = file.toPath();
Path moveTo = processedDir.resolve(originalPath.getFileName());
try (var br = new FileReader(file.getAbsolutePath(), StandardCharsets.UTF_16)){
List<CsvLine> beans = new CsvToBeanBuilder(br)
.withType(CsvLine.class)
.withSeparator('\t')
.withSkipLines(3)
.build()
.parse();
for (CsvLine item : beans) {
if(item.getValue().equals(2)
|| item.getValue().equals(43)
|| item.getValue().equals(32)) {
// file is invalid, skip it
moveTo = invalidDir.resolve(originalPath.getFileName());
// LOG MSG HERE
break;
}
}
}
Files.move(originalPath, moveTo, StandardCopyOption.REPLACE_EXISTING);
System.out.format("%nProcessed file : %s, moving the file to subfolder %s%n", originalPath, moveTo);
}
I need to copy the directory "src" that is located in my java project, as a common resource. This "src" folder contains other subfolders and files, so I need them to be copied as well. How can I achieve something like this??
The main problem I'm facing is that I can't retrieve the absolute path of my "src" folder.
A solution would be to copy file by file but their are too much and I would like to find a better solution
Thank you
EDIT:
When the user click on "Generate" button, my app ask to the user a target location where to generate some files. This target location is where I want to copy my "src" folder with all its children. The "src" folder, as sad above, is located in my java project main folder.
If you want to extract the sources from a jar file you could start with this short example
public class UnZip {
public static void main(String argv[]) {
String destDir = "/tmp/";
String sourceJar = "your_src.jar";
try (ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(sourceJar)))) {
ZipEntry zipEntry;
while ((zipEntry = zis.getNextEntry()) != null) {
File newDestination = new File(destDir + zipEntry.getName());
if (zipEntry.isDirectory()) {
unzipDir(newDestination);
} else {
unzipFile(newDestination, zis);
}
}
} catch (IOException ex) {
System.err.println("input file coud not be read " + ex.getMessage());
}
}
private static void unzipFile(File file, final ZipInputStream zis) {
System.out.printf("extract to: %s - ", file.getAbsoluteFile());
if (file.exists()) {
System.out.println("already exist");
return;
}
int count;
try (BufferedOutputStream dest = new BufferedOutputStream(new FileOutputStream(file), BUFFER_SIZE)) {
while ((count = zis.read(BUFFER, 0, BUFFER_SIZE)) != -1) {
dest.write(BUFFER, 0, count);
}
dest.flush();
System.out.println("");
} catch (IOException ex) {
System.err.println("file could not be created " + ex.getMessage());
}
}
private static void unzipDir(File dir) {
System.out.printf("create directory: %s - ", dir);
if (dir.exists()) {
System.out.println("already exist");
} else if (dir.mkdirs()) {
System.out.println("successful");
} else {
System.out.println("failed");
}
}
static final int BUFFER_SIZE = 2048;
static byte[] BUFFER = new byte[BUFFER_SIZE];
}
I resolved the problem creating a zip archive of the app I need to generate. Then from my project I unzip this archive taken from resource folder and after that I open the stream of the java file I need to modify and I edit it.
This is the code, similar to SubOptimal's solution
UnzipUtility unzipper = new UnzipUtility();
InputStream inputStream = getClass()
.getResource("/template/template.zip").openConnection()
.getInputStream();
unzipper.unzip(inputStream, parentFolder.getCanonicalPath());
The UnzipUtility class is from this example: http://www.codejava.net/java-se/file-io/programmatically-extract-a-zip-file-using-java
I wish to create a zip program in Java, which zip files and folders let say structure like this -
folder-one/
folder-one/one.txt
folder-one/two.mp3
folder-one/three.jpg
folder-two/
folder-two/four.doc
folder-two/five.rtf
folder-two/folder-three/
folder-two/folder-three/six.txt
I used zip4j open source, I have collected all the files (with absolute path) in one list then given it to zip but it is zipping files only as in my.zip -
one.txt
two.mp3
three.jpg
four.doc
five.rtf
six.txt
How can I preserve same structure on zipping and unzipping as it was on local earlier. Please suggest if any other open source can help me to zip/unzip in same structure files and folders like other windows zip programs.
Code is below --
public class CreateZipWithOutputStreams {
ArrayList filesToAdd = new ArrayList();
public void CreateZipWithOutputStreams(String sAbsolutePath) {
ZipOutputStream outputStream = null;
InputStream inputStream = null;
try {
ArrayList arrLocal = exploredFolder(sAbsolutePath);
outputStream = new ZipOutputStream(new FileOutputStream(new File("c:\\ZipTest\\CreateZipFileWithOutputStreams.zip")));
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
parameters.setEncryptFiles(true);
parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
parameters.setPassword("neelam");
for (int i = 0; i < arrLocal.size(); i++) {
File file = (File) arrLocal.get(i);
outputStream.putNextEntry(file, parameters);
if (file.isDirectory()) {
outputStream.closeEntry();
continue;
}
inputStream = new FileInputStream(file);
byte[] readBuff = new byte[4096];
int readLen = -1;
while ((readLen = inputStream.read(readBuff)) != -1) {
outputStream.write(readBuff, 0, readLen);
}
outputStream.closeEntry();
inputStream.close();
}
outputStream.finish();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public ArrayList exploredFolder(String sAbsolutePath) {
File[] sfiles;
File fsSelectedPath = new File(sAbsolutePath);
sfiles = fsSelectedPath.listFiles();
if (sfiles == null) {
return null;
}
for (int j = 0; j < sfiles.length; j++) {
File f = sfiles[j];
if (f.isDirectory() == true) {
exploredFolder(f.getAbsolutePath());
} else {
filesToAdd.add(f);
}
}
return filesToAdd;
}
public static void main(String[] args) {
new CreateZipWithOutputStreams().CreateZipWithOutputStreams("c:\\ZipTest");
}
}
Thanks!
Okay so first the code that is attached is supposed to work the way it is because the exploredFolder(String absolutePath) method is returning the "files to add" which in turn is being used by the CreateZipWithOutputStreams() method to create a single layered(flat) zip file.
What needs to be done is looping over the individual folders and keep adding them to the ZipOutputStream.
Please go through the link below and you will find the code snippet and detailed explaination.
Let me know if that helps!
http://www.java-forums.org/blogs/java-io/973-how-work-zip-files-java.html
I was wondering whether there is a way to take a given .jar file, selected with a JFileChooser, extract it and put it into a new directory. Then, take all the files from another directory, add it to the directory with the extracted .jar file, and then take all that and package it back up again.
I'm doing this because I want a really easy way to install mods for that game, minecraft, where you can just select your minecraft.jar, and make sure the files for the mod are in a folder, and wait a bit, as indicated by a JProgressBar.
This is all I have so far
import java.io.*;
import java.util.jar.*;
import javax.swing.*;
public class Main extends JFrame {
public Main() {
super("Auto-mod installer");
setSize(300, 60);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JProgressBar bar = new JProgressBar(0, 100);
add(bar);
setVisible(true);
}
public static void main(String[] args) {
Main m = new Main();
}
private void extract(File f) {
//Hrm...
}
private void addModFiles() {
//Uh...
}
private void repackage(File f) {
//What?
}
}
As you can see, I have no idea what I'm doing. I do know what the imports needed are, but that's about it. Help would be appreciated, ranting about anything I did wrong would get me mad. Thanks!
EDIT: If you know a way to get the same results, and it's not the way that I was looking for, please let me know how to do so. As long as I get the results I was looking for, it would be great. Thanks again!
The idea is relatively simple. You have a few gotchas (like what to do if files already exist and that kind of thing), but otherwise...
I'd start by having a look at JarFile
(I'm in the middle of another example, but when I get time, I'll post some stuff)
UPDATE with Example
public class JarTest {
protected static final String OUTPUT_PATH = "..."; // The place you want to extact the jar to
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
new JarTest();
}
public JarTest() {
try {
unjar();
// Copy new contents in...
jar();
} catch (IOException exp) {
exp.printStackTrace();
}
}
// This just recursivly lists through all the files to be included in the new jar
// We don't care about the directories, as we will create them from the file
// references in the Jar ourselves
protected List<File> getFiles(File path) {
List<File> lstFiles = new ArrayList<File>(25);
// If you want the directories, add the "path" to the list now...
File[] files = path.listFiles();
if (files != null && files.length > 0) {
for (File file : files) {
if (file.isDirectory()) {
lstFiles.addAll(getFiles(file));
} else {
lstFiles.add(file);
}
}
}
return lstFiles;
}
// Re-Jar the contents
// You should always attempt to jar back to a new file, as you may not want to effect the original ;)
public void jar() throws IOException {
JarOutputStream jos = null;
try {
String outputPath = OUTPUT_PATH;
// Create a new JarOutputStream to the file you want to create
jos = new JarOutputStream(new FileOutputStream("...")); // Add your file reference
List<File> fileList = getFiles(new File(OUTPUT_PATH));
System.out.println("Jaring " + fileList.size() + " files");
// Okay, I cheat. I make a list of all the paths already added to the Jar only create
// them when I need to. You could use "file.isDirectory", but that would mean you would need
// to ensure that the files were sorted to allow all the directories to be first
// or make sure that the directory reference is added to the start of each recursion list
List<String> lstPaths = new ArrayList<String>(25);
for (File file : fileList) {
// Replace the Windows file seperator
// We only want the path to this element
String path = file.getParent().replace("\\", "/");
// Get the name of the file
String name = file.getName();
// Remove the output path from the start of the path
path = path.substring(outputPath.length());
// Remove the leading slash if it exists
if (path.startsWith("/")) {
path = path.substring(1);
}
// Add the path path reference to the Jar
// A JarEntry is considered to be a directory if it ends with "/"
if (path.length() > 0) {
// At the trailing path seperator
path += "/";
// Check to see if we've already added it out not
if (!lstPaths.contains(path)) {
// At the path entry...we need need this to make it easier to
// extract the files at a later state. There is a way to cheat,
// but I'll let you figure it out
JarEntry entry = new JarEntry(path);
jos.putNextEntry(entry);
jos.closeEntry();
// Make sure we don't try to add the same path entry again
lstPaths.add(path);
}
}
System.out.println("Adding " + path + name);
// Create the actual entry for this file
JarEntry entry = new JarEntry(path + name);
jos.putNextEntry(entry);
// Write the entry to the file
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
byte[] byteBuffer = new byte[1024];
int bytesRead = -1;
while ((bytesRead = fis.read(byteBuffer)) != -1) {
jos.write(byteBuffer, 0, bytesRead);
}
jos.flush();
} finally {
try {
fis.close();
} catch (Exception e) {
}
}
jos.closeEntry();
}
jos.flush();
} finally {
try {
jos.close();
} catch (Exception e) {
}
}
}
public void unjar() throws IOException {
JarFile jarFile = null;
try {
String outputPath = OUTPUT_PATH;
File outputPathFile = new File(outputPath);
// Make the output directories.
// I'll leave it up to you to decide how best to deal with existing content ;)
outputPathFile.mkdirs();
// Create a new JarFile reference
jarFile = new JarFile(new File("C:/hold/Java_Harmony.jar"));
// Get a list of all the entries
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
// Get the next entry
JarEntry entry = entries.nextElement();
// Make a file reference
File path = new File(outputPath + File.separator + entry.getName());
if (entry.isDirectory()) {
// Make the directory structure if we can
if (!path.exists() && !path.mkdirs()) {
throw new IOException("Failed to create output path " + path);
}
} else {
System.out.println("Extracting " + path);
// Extract the file from the Jar and write it to disk
InputStream is = null;
OutputStream os = null;
try {
is = jarFile.getInputStream(entry);
os = new FileOutputStream(path);
byte[] byteBuffer = new byte[1024];
int bytesRead = -1;
while ((bytesRead = is.read(byteBuffer)) != -1) {
os.write(byteBuffer, 0, bytesRead);
}
os.flush();
} finally {
try {
os.close();
} catch (Exception e) {
}
try {
is.close();
} catch (Exception e) {
}
}
}
}
} finally {
try {
jarFile.close();
} catch (Exception e) {
}
}
}
}
You can use this very simple library to pack/unpack jar file
JarManager
Very simple
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import fr.stevecohen.jarmanager.JarPacker;
import fr.stevecohen.jarmanager.JarUnpacker;
public class MyClass {
public void addFileToJar(String jarPath, String otherFilePath) {
try {
JarUnpacker jarUnpacker = new JarUnpacker();
File myJar = new File("./myfile.jar");
File otherFile = new File(otherFilePath);
Path unpackDir = Files.createTempDirectory(myJar.getName()); //create a temp directory to extract your jar
System.out.println("Unpacking in " + unpackDir.toString());
jarUnpacker.unpack(jarPath, unpackDir.toString()); //extraxt all files contained in the jar in temp directory
Files.copy(otherFile.toPath(), new File(unpackDir.toFile(), otherFile.getName()).toPath()); //copy your file
JarPacker jarRepacker = new JarPacker();
File newJar = new File("./maNewFile.jar");
System.out.println("Packing jar in " + newJar.getAbsolutePath());
jarRepacker.pack(unpackDir.toString(), newJar.getAbsolutePath()); //repack the jar with the new files inside
} catch (IOException e) {
e.printStackTrace();
}
}
}
You can also use maven dependency
<dependency>
<groupId>fr.stevecohen.jarmanager</groupId>
<artifactId>JarManager</artifactId>
<version>0.5.0</version>
</dependency>
You also need my repository
<repository>
<id>repo-reapersoon</id>
<name>ReaperSoon's repo</name>
<url>http://repo-maven.stevecohen.fr</url>
</repository>
Check the last version with the link bellow to use the last dependency
Please use my public issue tracker if you find some bugs
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();
}
}
}
}
}
});
}