Zip4j: How to overwrite if created zip file is exist - java

I want to overwrite existing zip file when I create zip file by using Zip4j. When I create zip file by using Zip4j, my file will split according to splitSize. So I can't check it. Here my Code sample ...
File file = new File("C:\\temp\\5.pdf");
ZipParameters parameters = new ZipParameters();
// set compression method to store compression
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
// Set the compression level. This value has to be in between 0 to 9
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
zipFile.createZipFile(file, parameters, true, splitSize);

Whether the file already exists or not, the following code will work:
File file = new File("<your zip file">);
boolean delete = file.delete();
The boolean will be true if the file was deleted, and false if the file did not exist or could not be deleted. Of course if the file could not be deleted for any reason other than "file does not exist", you will not know. If you care about it, you should use the code suggested by Arno_Geismar.

Hope this helps, regards
//step 1
Path p1 = ...; //path to your potentially existing file
Path p2 = ...; //path of your new file;
if (Files.isSameFile(p1, p2)) {
try {
delete(p1) // delete the directory where your duplicate is located
//step 2: insert your saving logic with zip4j ( make sure you create a new subdirectory for each file you zip
//step 3: eat some strawberry ice-cream
} catch (NoSuchFileException x) {
System.err.format("%s: no such" + " file or directory%n", path);
} catch (DirectoryNotEmptyException x) {
System.err.format("%s not empty%n", path);
} catch (IOException x) {
// File permission problems are caught here.
System.err.println(x);
}
}
//use this method to delete the files in the directory before deleting it.
void delete(File f) throws IOException {
if (f.isDirectory()) {
for (File c : f.listFiles())
delete(c);
}
if (!f.delete())
throw new FileNotFoundException("Failed to delete file: " + f);
}

Related

Compare the String array elements with the file names in a folder if matches move them to another folder

I have this requirement where I have some files.
Say - file1.txt file2.txt in a folder --> Files ->> C:/Files
Inside this folder I have two other folders
Completed ->> C:/Files/Completed and Error C:/Files/Error
Now I have this String array : String arr[]={file1, file2};
I need to compare the string arry elements with the file names in the folder Files.
If any of the name matches then those original files will be moved to the Completed folder otherwise to the Error folder.
Here's what I was trying to do but couldn't get through it
String arr[]={file1, file2};
List<String> textFiles = new ArrayList<File>();
List<String> directories = new ArrayList<File>();
File[] files = new File("C:/Files").listFiles();
for (File file : files) {
if(file.isFile()){
textFiles.add(file.getName());
}else
directories.add(file.getName());
}
for(int i = 0; i < textFiles.size(); i++){
if(textFiles.equals(sampleids)){
logger.info(textFiles.get(i));
//FileOutputStream fStream = new FileOutputStream();
}
}
Based on the title of your post, the code below will do the task required however do keep in mind that the file names you have supplied within your String Array do not have file name extensions. I'm not sure if this is a requirement or just an over-site. In any case the code takes this into account and will distinguish between names with or without extensions.
If the 'Completed' folder and or the 'Error' folder do not exist within the 'Files' folder then they are automatically created.
Access Permissions within the local file system will be your responsibility to establish and ensure they exist.
Read the comments in code:
String completedArray[] = {"file1", "file2"};
List<String> completedFiles = new ArrayList<>(); // Files moved to the 'Completed' folder.
List<String> notCompletedFiles = new ArrayList<>(); // Files moved to the 'Error' folder.
File[] files = new File("C:/Files").listFiles();
// Does the 'Completed' folder exist? If not, create it.
File checkPath = new File("C:/Files/Completed");
if (!checkPath.exists()) {
checkPath.mkdirs();
}
// Does the 'Error' folder exist? If not, create it.
checkPath = new File("C:/Files/Error");
if (!checkPath.exists()) {
checkPath.mkdirs();
}
/* Check Files within the 'Files' folder against
the file names within the 'completed' array...
Note that the file names contained within the
completedArray string array DO NOT contain file
name extensions. This is how the OP portrays this
within his/her code.
*/
// Iterate through the files within the 'Files' folder...
for (File file : files) {
// Is this an actual file?
if (file.isFile()) {
// Yes...
// Get file name WITH file name extension
String fileName = file.getName();
// Get the file name WITHOUT the file name extension (ie: no .txt)
String fileName_NoExtension = file.getName().substring(0, file.getName().lastIndexOf("."));
boolean fileMoved = false; // Flag to indicate file was successfully moved.
// Check to see if the file name is contained within our list
// (array) of completed files?
for (String completed : completedArray) {
String name;
// Add extensions as you see fit.
if (completed.matches("([^\\s]+(\\.(?i)(txt|csv|doc|pdf))$)")) {
name = fileName;
}
else {
name = fileName_NoExtension;
}
// Is there a match?
if (completed.equalsIgnoreCase(name)) {
// Yes...
//Move the file to 'Completed' folder
try {
java.nio.file.Path temp = Files.move(Paths.get(file.getAbsolutePath()),
Paths.get("C:/Files/Completed/" + file.getName()));
if (temp != null) {
// Add the completed, moved file to the 'completedFiles' collection.
completedFiles.add(file.getAbsolutePath());
fileMoved = true; // Indicated move was successfull.
}
else {
// Indicate there was a problem. Moving the file failed.
System.err.println("Failed to move the file");
}
}
catch (IOException ex) {
// Display the exception if one occurres.
System.err.println("FAILED TO MOVE FILE...");
System.err.println(ex.getMessage());
}
}
}
/* If the fileMoved flag is still false then there was
either an error in moving the file OR the file was
not indicated within our 'completedFiles' array, so,
move the file to the 'Error' folder. */
if (!fileMoved) {
try {
java.nio.file.Path temp = Files.move(Paths.get(file.getAbsolutePath()),
Paths.get("C:/Files/Error/" + file.getName()));
if (temp != null) {
// Add the moved file to the 'notCompletedFiles' collection.
notCompletedFiles.add(file.getAbsolutePath());
fileMoved = true;
}
else {
// Indicate there was a problem. Moving the file failed.
System.err.println("Failed to move the file");
}
}
catch (IOException ex) {
// Display the exception if one occurres.
System.err.println("FAILED TO MOVE FILE...");
System.err.println(ex.getMessage());
}
}
}
}
// Display Completed files moved to the 'Completed' folder...
System.out.println();
System.out.println("Files moved to the 'Completed' folder (C:\\Files\\Completed):");
System.out.println("===========================================================");
for (String comp : completedFiles) {
System.out.println(comp);
}
// Display Non-Completed files moved to the 'Error' folder...
System.out.println();
System.out.println("Files moved to the 'Error' folder (C:\\Files\\Error):");
System.out.println("===================================================");
for (String nonComp : notCompletedFiles) {
System.out.println(nonComp);
}

Delete zip folder in android

Map<String, String> zip_properties = new HashMap<>();
zip_properties.put("create", "false");
URI zip_disk = URI.create(name);
/* Create ZIP file System */
try (FileSystem zipfs = FileSystems.newFileSystem(zip_disk, zip_properties))
{
Path pathInZipfile = zipfs.getPath(name);
// System.out.println("About to delete an entry from ZIP File" +
pathInZipfile.toUri() );
Files.delete(pathInZipfile);
//System.out.println("File successfully deleted");
} catch (IOException e) {
e.printStackTrace();
}
I have create zip folder for multiple images in internal storage.Now i want to delete Zip files from the location and recreate same name zip folder in android.
Perform above code for delete zip folder but its not working
Please help me if anyone have solution
Thanks in advance..
after using delete() method in your File.
filePath is a String containing the path to your zip file.
File file = new File(filePath);
//must check if deleted is true. It is true if the file was successfully deleted
boolean deleted = file.delete();
Use below method
/**
* Clear/Delete all the contents in file/Directory
*
* #param file file/folder
* #return true on successfull deletion of all content
* <b>Make sure file it is not null</b>
*/
public boolean clearDirectory(#NonNull File file) {
boolean success = false;
if (file.isDirectory())
for (File child : file.listFiles())
clearDirectory(child);
success = file.delete();
return success;
}
Give this a try!
public static final String ZIP_FILES_DIR = "Download/FolderNAME";
File directoryPath = new File(Environment.getExternalStorageDirectory()+ File.separator + ZIP_FILES_DIR);
if (directoryPath.delete()) {
//do whatever you want
}
File file = new File(deleteFilePath);
boolean deleted = = file.deleted();
deleteFilePath is a String containing the path to your zip file.
if deleted is true. It is true if the file was successfully deleted.

Java nio move folder with content throws exception [duplicate]

How do you move a file from one location to another? When I run my program any file created in that location automatically moves to the specified location. How do I know which file is moved?
myFile.renameTo(new File("/the/new/place/newName.file"));
File#renameTo does that (it can not only rename, but also move between directories, at least on the same file system).
Renames the file denoted by this abstract pathname.
Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.
If you need a more comprehensive solution (such as wanting to move the file between disks), look at Apache Commons FileUtils#moveFile
With Java 7 or newer you can use Files.move(from, to, CopyOption... options).
E.g.
Files.move(Paths.get("/foo.txt"), Paths.get("bar.txt"), StandardCopyOption.REPLACE_EXISTING);
See the Files documentation for more details
Java 6
public boolean moveFile(String sourcePath, String targetPath) {
File fileToMove = new File(sourcePath);
return fileToMove.renameTo(new File(targetPath));
}
Java 7 (Using NIO)
public boolean moveFile(String sourcePath, String targetPath) {
boolean fileMoved = true;
try {
Files.move(Paths.get(sourcePath), Paths.get(targetPath), StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
fileMoved = false;
e.printStackTrace();
}
return fileMoved;
}
File.renameTo from Java IO can be used to move a file in Java. Also see this SO question.
To move a file you could also use Jakarta Commons IOs FileUtils.moveFile
On error it throws an IOException, so when no exception is thrown you know that that the file was moved.
Just add the source and destination folder paths.
It will move all the files and folder from source folder to
destination folder.
File destinationFolder = new File("");
File sourceFolder = new File("");
if (!destinationFolder.exists())
{
destinationFolder.mkdirs();
}
// Check weather source exists and it is folder.
if (sourceFolder.exists() && sourceFolder.isDirectory())
{
// Get list of the files and iterate over them
File[] listOfFiles = sourceFolder.listFiles();
if (listOfFiles != null)
{
for (File child : listOfFiles )
{
// Move files to destination folder
child.renameTo(new File(destinationFolder + "\\" + child.getName()));
}
// Add if you want to delete the source folder
sourceFolder.delete();
}
}
else
{
System.out.println(sourceFolder + " Folder does not exists");
}
Files.move(source, target, REPLACE_EXISTING);
You can use the Files object
Read more about Files
You could execute an external tool for that task (like copy in windows environments) but, to keep the code portable, the general approach is to:
read the source file into memory
write the content to a file at the new location
delete the source file
File#renameTo will work as long as source and target location are on the same volume. Personally I'd avoid using it to move files to different folders.
Try this :-
boolean success = file.renameTo(new File(Destdir, file.getName()));
Wrote this method to do this very thing on my own project only with the replace file if existing logic in it.
// we use the older file i/o operations for this rather than the newer jdk7+ Files.move() operation
private boolean moveFileToDirectory(File sourceFile, String targetPath) {
File tDir = new File(targetPath);
if (tDir.exists()) {
String newFilePath = targetPath+File.separator+sourceFile.getName();
File movedFile = new File(newFilePath);
if (movedFile.exists())
movedFile.delete();
return sourceFile.renameTo(new File(newFilePath));
} else {
LOG.warn("unable to move file "+sourceFile.getName()+" to directory "+targetPath+" -> target directory does not exist");
return false;
}
}
Please try this.
private boolean filemovetoanotherfolder(String sourcefolder, String destinationfolder, String filename) {
boolean ismove = false;
InputStream inStream = null;
OutputStream outStream = null;
try {
File afile = new File(sourcefolder + filename);
File bfile = new File(destinationfolder + filename);
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024 * 4];
int length;
// copy the file content in bytes
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
// delete the original file
afile.delete();
ismove = true;
System.out.println("File is copied successful!");
} catch (IOException e) {
e.printStackTrace();
}finally{
inStream.close();
outStream.close();
}
return ismove;
}

Moving/Copying a file to another directory creates empty file and empties source

My goal is to move a file from one directory to another. The source is on a local drive and the destination is on a network drive. It doesn't matter whether I move or I copy then delete source. The file is approx 6GB.
What I've tried:
// C:\path\to\dir\file.bak
File source = new File(localRoot + backup);
// \\192.168.1.100\path\to\dir\file.bak
File dest = new File(storageRoot + "/" + storagePath + "/" + backup);
try {
log("Copying");
// I've tried copyFile as well.
FileUtils.copyFileToDirectory(source, dest);
log("copied");
} catch (Exception e) {
e.printStackTrace();
}
File source = new File(localRoot + backup);
File dest = new File(storageRoot + "/" + storagePath + "/" + backup);
try {
log("Copying");
// I've tried move and creating Paths instead of Files as well.
Files.copy(source.toPath(), dest.toPath());
log("copied")
} catch (Exception e) {
e.printStackTrace();
}
I've tried as well a manual method using Input, OutputStreams and reading bytes.
The results is that a file is created in the destination with the correct filename with 0 bytes, and the source file is rewritten from 6GB to 0 bytes. This happens for all methods I've tried, the only exception is that when I tried move, the source file was deleted rather than rewritten.
All code is in early development, please refrain from commenting on best practices.
Thank you, and what am I missing or what else can I try?

Moving file from one directory to another and delete from source directory using java

I am trying to move files from one directory to another delete that file from source directory after moving.
for (File file : files) {
if (file != null) {
boolean status = moveFile(file, filePath, name, docGroupId);
if (status) {
//some operations....
}
}
}
public static boolean moveFile(final File file, final String filePath, final String groupName, Integer docGroupId) {
// TODO Auto-generated method stub
String selectedDirectory = filePath + File.separator + groupName;
InputStream in = null;
OutputStream out = null;
try {
if (!file.isDirectory()) {
File dir = new File(selectedDirectory);
if (!dir.exists()) {
dir.mkdirs();
}
String newFilString = dir.getAbsolutePath() +
File.separator + file.getName();
File newFile = new File(newFilString);
in = new FileInputStream(file);
out = new FileOutputStream(newFile);
byte[] moveBuff = new byte[1024];
int butesRead;
while ((butesRead = in.read(moveBuff)) > 0) {
out.write(moveBuff, 0, butesRead);
}
}
in.close();
out.close();
if(file.delete())
return true;
} catch (Exception e) {
return false;
}
}
The program works on Linux-Ubuntu and all files are moved to another directory and deleted from source directory, but in Windows system all files are moved but failed to delete one or two files from source directory. Please note that while debugging the program is working fine.
Consider using Files.delete instead of File.delete. The javadoc says:
Note that the Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.
This should provide the information necessary to diagnose the problem.
So, if problem comes with delete, possible explanations:
you do file.delete() on every files and directories. How do you know the directory is empty ? If not, it will fail, then what happen to next instructions ?
file deletion is OS-dependant. On Windows, you can have many security issues, depending on which user, which rights, which location. You should check with a file-delete-alone program;
last: files can be locked by other programs (even explorer), it is also OS-dependant.
You don't need any of this if the source and target are in the same file system. Just use File.renameTo().

Categories

Resources