How to copy a zip file in Java - java

I have a zip file that gets created at runtime that I need to copy to another directory however whenever I run my code I get a DirectoryNotEmptyException. Is there some extra parameter I need to specify to copy into a non-empty directory?
Here's the layout
Path sourceZip = new File(path).toPath();
String destinDir = new File(System.getProperty("user.dir")).getParent();
Path target = Paths.get(destinDir);
try {
Files.copy(sourceZip, target, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) //DirectoryNotEmptyException occurs here
{}

the destination needs to contain the full path of the file that will eventually be there.
so you say if you needed to copy /home/dauser/faq.txt to /home/faq.txt
File file = new File(path);
Path sourceZip = file.toPath();
StringBuilder sb = new StringBuilder();
sb.append(new File(System.getProperty("user.dir")).getParent());
sb.append("/");
sb.append(file.getName());
Path target = Paths.get(sb.toString());
try {
Files.copy(sourceZip, target, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) //DirectoryNotEmptyException occurs here
{}

Related

how to create dynamic paths in java and write the file data in java

I will get dynamic paths from database. Example: 1.xyz/abc/file1.txt
2.pqr/file2.txt
Now I need to append these paths to existing file (eg:/users/rama/) and save that file
my final directory should like /users/rama/xyz/abc/file1.txt
I am able to create directories such as xyz/abc if they don't exist, but the problem is file1.txt is also created as directory instead of file.
I am able to create directories such as xyz/abc if they don't exist,
but the problem is file1.txt is also created as directory instead of
file.
Because you are creating the directories until *.txt. Below an example of code to acheive what you want:
String prefix = "/users/rama/";
String filePath = "xyz/abc/file1.txt";
// concatenation => /users/rama/xyz/abc/file1.txt
String fullPath = prefix.concat(filePath);
PrintWriter writer;
try {
// Getting the directory path : /users/rama/xyz/abc/
int lastIndexOfSlash = fullPath.lastIndexOf("/");
String path = filePath.substring(0, lastIndexOfSlash);
File file = new File(path);
// If /users/rama/xyz/abc/ don't exist then creating it.
if(!file.exists()) {
file.mkdirs();
}
// Creating the file.
writer = new PrintWriter(fullPath, "UTF-8");
writer.println("content");
writer.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Unable to located generated file

I am generating a file using the following syntax
File file = new File("input.txt");
The problem is that it is saying that it is writing to the file but I am not able to locate where the file is created, I searched my entire workspace. The expectation was that it would be created in the same folder as my code which is executing.
Any ideas?
Rest of the code :
File file = new File("input.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
You could do a sop on the absolute path and you would get the path:
File file = new File("input.txt");
System.out.println("" + file.getAbsolutePath());
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
When you create file through relative paths, Java uses System.getProperty("user.dir"). So, in your case the full path to file will be System.out.println(System.getProperty("user.dir") + "/input.txt");.

i want to overwrite the existing zipfile

i want to overwrite the existing zip file(which mean i add new file in existing zip file) but here show this error (java.util.zip.ZipError: zip END header not found)
private void updateZip(String fileName, String scenarioDirectory){
System.out.println("File Name : " +fileName);
System.out.println("Scenario Directory : " +scenarioDirectory);
String scenarioName ="12345";
Path myFilePath = Paths.get(fileName);
Path zipFilePath = Paths.get(scenarioDirectory);
FileSystem fs;
try {
fs = FileSystems.newFileSystem(zipFilePath,null);
Path fileInsideZipPath = fs.getPath(scenarioName);
Files.copy(myFilePath, fileInsideZipPath);
fs.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Try this :
if your file exist then delete it ant after save the new.
Or Added a file directly in the zip code since this example https://stackoverflow.com/a/17500924/4017037

Error while copying files from source to destination java

//original file
Path original = Paths.get("C:\\Users\\Laksahan\Desktop\\bg.jpg");
File f = new File("C:\\Users\\Laksahan\\Desktop\\bg.jpg");
// new file
Path destination = Paths.get("C:\\Program Files\\Tour v0.1\\image\\"+f.getName());
try {
Files.copy(original, destination, LinkOption.NOFOLLOW_LINKS);
} catch (IOException x) {
x.printStackTrace();
}
i tried above method to copy files, it wont work and it prints this error
java.nio.file.NoSuchFileException: C:\Users\Laksahan\Desktop\bg.jpg -> C:\Program Files\Tour v0.1\image\bg.jpg
please help
Java 7's NIO will not create a folder if it doesn't exist when using Files.copy().
The best you can do is check for the folder and create it if it doesn't exist before you call copy.
Try
Path original = Paths.get("C:\\Users\\Laksahan\\Desktop\\bg.jpg");
instead of
Path original = Paths.get("C:\\Users\\Laksahan\Desktop\\bg.jpg");
Create a folder programmatically for example -
Path from = Paths.get("C:\\Users\\Laksahan\\Desktop\\bg.jpg");
Path to = Paths.get("C:\\Program Files\\Tour v0.1\\image\\");
Path destination;
File f = new File("C:\\Users\\Laksahan\\Desktop\\bg.jpg");
if (!Files.exists(to)) {
try {
Files.createDirectories(to);
} catch (IOException ioe) {
ioe.printStackTrace();
}
destination = Paths.get(to.toString() + "\\" + f.getName());
try {
Files.copy(from, destination, LinkOption.NOFOLLOW_LINKS);
} catch (FileAlreadyExistsException faee) {
faee.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}

Problem in Zipping a File

When I run my code and use the files that are in the resource folder of my project itself, I face no problems. It zips the file successfully and I can extract it using WINZIP. The problem comes when I try to zip a file that is not in the project folder.
When I do the same, I am passing the Absolute Path of both the src and the dest files. My program doesn't give any exceptions, but when I try to open that zip file, I get an error saying, File is Invalid.
Can anyone tell me why this may be happening.
public static void compress(String srcPath, String destPath) {
srcFile = new File(srcPath);
destFile = new File(destPath);
try {
fileInputStream = new FileInputStream(srcFile);
fileOutputStream = new FileOutputStream(destFile);
zipEntry = new ZipEntry(srcPath);
zipOutputStream = new ZipOutputStream(fileOutputStream);
zipOutputStream.putNextEntry(zipEntry);
byte[] data = new byte[12];
while ((fileInputStream.read(data)) != -1) {
zipOutputStream.write(data);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try{
fileInputStream.close();
zipOutputStream.close();}catch (Exception e) {
e.printStackTrace();
}
}
}
You should not store paths with drive letters in your zip file because when you try to extract your zip, it will try to create a directory with the name of the drive and fail.
You will need to change your code so that it removes the drive letter from the path before creating the ZipEntry.

Categories

Resources