HI
so my code works like this, I get a docx and a folder to put the unzip files,
String templateLocation = "//path"; //this is where the document is located
String AUX = "//path"; //this is a aux folder that's get the unzip files
unzip(new File(templateLocation), new File(AUX));
and the method unzip is
private static void unzip(File zipfile, File directory) throws IOException {
ZipFile zfile = new ZipFile(zipfile);
Enumeration<? extends ZipEntry> entries = zfile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
File file = new File(directory, entry.getName());
if (entry.isDirectory()) {
file.mkdirs();
}
else {
file.getParentFile().mkdirs();
InputStream in = zfile.getInputStream(entry);
try {
copy(in, file);
}
finally {
in.close();
}
}
}
}
the thing is that i need to use a external docx that's in Base64
but how?
attempt with this
String wordx = "DocxInBase64";
byte[] dataFileWord = java.util.Base64.getDecoder().decode(wordx);
String dataw = new String(dataFileWord,StandardCharsets.UTF_8);
But im getting something that looks like corrupted
PK����Xs���g����l}'_B�R;�q�u#��.�����~�Hwx�=��4��������pv�{3o�'M,���b���wi�O���0��E]}`�x��?...
any ideas to start with?
Thanks in advance
You can use Apache POI to parse word files.
http://poi.apache.org/document/index.html
Related
I have a Jar file which has many excel sheets inside it. I want to access the excels sheets while running the Jar file and copy somewhere. How can I do that ?
You can access the Excel sheets as resources in the classpath:
Class.getResourceAsStream("/excelfiles/myfile.xlsx");
For reading Excel sheets in java you can use Apache POI library
If you only want to copy the files to an output folder (without understanding Excel, you can just read the resource as an InputStream and write it to a a FileOutputStream.
The issue is resolved. I used below code to access the excels inside jar and copy excels outside my Jar
public static void main(String[] args) throws IOException {
final String classPath = "Path_Of_Jar/abc.jar";
JarFile jarFile = new JarFile (classPath);
String copyFolderExcel="Path to copy excels";
File excelFolderFile = new File (copyFolderExcel);
excelFolderFile.mkdir();
Enumeration<JarEntry> e = jarFile.entries ();
while (e.hasMoreElements ()) {
JarEntry entry = (JarEntry) e.nextElement ();
if (entry.getName ().contains ("excelFiles/")) {
String name = entry.getName ();
if(name.contains (".xlsx")) {
copyExcel(jarFile,name,copyFolderExcel);
}
}
}
jarFile.close ();
}
private static void copyExcel(JarFile jarFile, String file,String updatedFolder) throws IOException {
String[] outputFileName = file.split ("/");
String finalName = outputFileName[outputFileName.length-1];
JarEntry entry = (JarEntry) jarFile.getEntry(file);
InputStream input = jarFile.getInputStream(entry);
OutputStream output = new FileOutputStream (updatedFolder+"/"+finalName);
try {
byte[] buffer = new byte[input.available ()];
for (int i = 0; i != -1; i = input.read (buffer)) {
output.write (buffer, 0, i);
}
} finally {
input.close();
output.close();
}
}
}
Unzipping multipart file with and without subdirectories since I am not giving any instruction to user to how to zip the file therefore I need to find/search all files from Zip file which might have directories and subdirectories and keeping all files in a seperate different folder.
So basically it is some kind of smart unzipping where it detects the directory using ZipEntry then skip and find file to write in the folder.
I have written a code but I am not even near it since I am getting only one file that too which has no directories in it.
String outputPath="C:\\Users\\Plootus\\exceldocs\\";
FileSystem fileSystem = FileSystems.getDefault();
try
{
ZipInputStream zis=new ZipInputStream(serverFile.getInputStream());
BufferedInputStream bis=null;
InputStream is=null;
//Get file entries
ZipEntry entry=null;
//We will unzip files in this folder
while ( (entry = zis.getNextEntry()) != null ) {
System.out.println(entry.getName());
if(!entry.isDirectory()) {
System.out.println(entry.getName());
is = zis;
bis = new BufferedInputStream(is);
String uncompressedFileName = outputPath+toolName+entry.getName();
Path uncompressedFilePath = fileSystem.getPath(uncompressedFileName);
Files.createFile(uncompressedFilePath);
FileOutputStream fileOutput = new FileOutputStream(uncompressedFileName);
while (bis.available() > 0)
{
fileOutput.write(bis.read());
}
fileOutput.close();
System.out.println("Written :" + entry.getName());
bis.close();
is.close();
}
}
zis.close();
return true;
}
catch(IOException e)
{
return false;
}
return false;
Objective: Zip file contains possible entries
1.) abc.zip(Multipart File)
-folder1-arkan.csv,dan.csv,kud.csv
abc.zip(Mutlipart File)
-folder1--bio.csv(file)-folder-2(inside folder1)-arkan.csv,dan.csv,kud.csv
abc.zip(Mutlipart File)
-arkan.csv,dan.csv,kud.csv
Instead of extracting from MultipartFile and handling entries as ZipEntry(as told by #Jokkeri) is not possible therefore I found other way to do it.
I will save that file and when the operation is done then delete it.
After receiving multipart file I saved the file using File object(saveZip)
try(ZipFile file = new ZipFile(saveZip.getCanonicalPath()))
{
FileSystem fileSystem = FileSystems.getDefault();
//Get file entries
Path inputpath=fileSystem.getPath(file.getName());
Enumeration<? extends ZipEntry> entries = file.entries();
//We will unzip files in this folder
File directory=new File(zipFilePath.concat(username+"-"+toolName));
if(!directory.exists()) {
directory.mkdir();
}
//Iterate over entries
while (entries.hasMoreElements())
{
ZipEntry entry = entries.nextElement();
String abc[]=entry.getName().split("/");
//Else create the file
if(!entry.isDirectory())
{
InputStream is = file.getInputStream(entry);
BufferedInputStream bis = new BufferedInputStream(is);
String uncompressedFileName = zipFilePath +username+"-"+toolName+"/"+ abc[abc.length-1];
Path uncompressedFilePath = fileSystem.getPath(uncompressedFileName);
if(Files.notExists(uncompressedFilePath))
Files.createFile(uncompressedFilePath);
FileOutputStream fileOutput = new FileOutputStream(uncompressedFileName);
while (bis.available() > 0)
{
fileOutput.write(bis.read());
}
fileOutput.close();
System.out.println("Written :" + entry.getName());
is.close();
bis.close();
}
}
file.close();
Files.deleteIfExists(inputpath);
return true;
}catch(IOException e)
{
e.printStackTrace();
return false;
}
I want to extract a zip file which contains a jar file. This file has complex folder structure and in one of the folders there is a jar file. When I am trying to use the following code to extract the jar file the program goes in infinite loop in reading the jar file and never recovers. It keeps on writing the contents of the jar till we reach the limit of the disc space even though the jar is of only a few Mbs.
Please find the code snippet below
`
// using a ZipInputStream to get the zipIn by passing the zipFile as FileInputStream
ZipEntry entry = zipIn.getNextEntry();
String fileName= entry.getName()
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileName));
byte[] bytesIn = new byte[(int)bufferSize];
while (zipIn.read(bytesIn) > 0) // This is the part where the loop does not end
{
bos.write(bytesIn);
}
..
// flushing an closing the bos
Please let me know if there is any way we can avoid this and get the jar file out at required location.
Does this suit your needs?
public static void main(String[] args) {
try {
copyJarFromZip("G:\\Dateien\\Desktop\\Desktop.zip",
"G:\\Dateien\\Desktop\\someJar.jar");
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void copyJarFromZip(final String zipPath, final String targetPath) throws IOException {
try (ZipFile zipFile = new ZipFile(zipPath)) {
for (final Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements();) {
ZipEntry zipEntry = e.nextElement();
if (zipEntry.getName().endsWith(".jar")) {
Files.copy(zipFile.getInputStream(zipEntry), Paths.get(targetPath),
StandardCopyOption.REPLACE_EXISTING);
}
}
}
}
I am facing an unusal issue.I am building a tool which is scheduled to run every 5 mins.
It will pick up the zip files from a particular directory and extract files (depending on the file name) to a destination. I am using zipentry to get each filename in zip file and then extracting as required then I back them (zip files, once I finish all the files in a zip) to a particular directory and then delete the zip file. But sometimes (not always) the zip files do not get deleted. Since I am using fileutils.forcedelete(). I am getting an exception: unable to delete file. So I changed to the code to using fileutils.forcedeleteonexit() still some files remain in the source.
Here is a sample of my code:
sourceFile=new file(zipfile);
zipFile = new ZipFile(sourceFile);
zEnum = (Enumeration<ZipEntry>) zipFile.entries();
for (int a = 0; a < zipFile.size(); a++)
{
ZipEntry zE = zEnum.nextElement();
//Function uses zip4j for extracting. No streams used.
extract(String sourceZipFile, String fileNameToExtract, String outputFolder);
}
//I tried it with finally either
zipFile.close();
//Using fileutils to copy. No streams used.
copyFile(sourceFile, backup);
FileUtils.forceDeleteOnExit(sourceFile);
There are no streams used but I am getting a lock on files sometimes (not always).
What seems to be the bug here? Is it the zip4j extraction that is causing the problem or anything else? I am using zip4j 1.3.1.
I think your problem related with OS file buffers, that sometimes are not flushed when you are trying to delete file.
Did you try to use sourceFile.deleteOnExit() instead FileUtils.forceDeleteOnExit(sourceFile)?
Also you can try to check sourceFile.canWrite before deleting (may be it may helps)
You can also try to use FileInputStream() before deleting:
FileInputStream fi = new FileInputStream(sourceFile);
fi.getFD().sync();
Use apache-commons IO's FileDeleteStrategy. Something like:
FileDeleteStrategy.FORCE.delete(file);
Update:
It should be the way IO is being handled in your application. I have written simple code which copies a zip file to a temporary zip, deflates the temporary zip and after few seconds deletes it. Here you go:
public class ZipTest {
private static String dirPath = "/home/ubuntuuser/Desktop/";
public static void main(String[] args) throws Exception {
File myzip = new File(dirPath + "content.zip");
String tempFileStr = dirPath + "content_temp.zip";
File tempFile = new File(tempFileStr);
String unzipFolderStr = dirPath + "unzip";
copyUsingChannels(myzip, tempFile);
// copyUsingStreams(myzip, tempFile);
unZip(tempFileStr, unzipFolderStr);
Thread.sleep(3000);
tempFile.delete();
}
private static void copyUsingStreams(File myzip, File tempFile)
throws IOException, FileNotFoundException {
byte[] barray = new byte[1024];
if (!tempFile.exists())
{
tempFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(tempFile);
FileInputStream fis = new FileInputStream(myzip);
int length = 0;
while ((length = fis.read(barray)) != -1)
{
fos.write(barray, 0, length);
}
fis.close();
fos.close();
}
public static void copyUsingChannels(final File srcFile, final File destFile) throws Exception
{
if (!destFile.exists())
{
destFile.createNewFile();
}
FileChannel source = new FileInputStream(srcFile).getChannel();
FileChannel destination = new FileOutputStream(destFile).getChannel();
source.transferTo(0, source.size(), destination);
source.close();
destination.close();
}
private static void unZip(String zipFile, String outputFolder) throws Exception {
byte[] buffer = new byte[1024];
File folder = new File(outputFolder);
if (!folder.exists()) {
folder.mkdir();
}
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String fileName = ze.getName();
File newFile = new File(outputFolder + File.separator + fileName);
System.out.println("file unzip : " + newFile.getAbsoluteFile());
new File(newFile.getParent()).mkdirs();
if (ze.isDirectory())
{
newFile.mkdir();
ze = zis.getNextEntry();
continue;
}
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
}
}
here i'm trying to zip only .txt file in a folder using java.
My code here was found with google and works perfectly but only for a specified .txt file.
Thank you.
import java.util.*;
import java.util.zip.*;
import java.io.*;
public class ZipFile
{
public static void main(String[] args) {
ZipOutputStream out = null;
InputStream in = null;
try {
File inputFile1 = new File("c:\\Target\\target.txt");// here i want to say only the directroy where .txt files are stored
File outputFile = new File("c:\\Target\\Archive_target.zip");//here i want to put zipped file in a different directory
OutputStream rawOut = new BufferedOutputStream(new FileOutputStream(outputFile));
out = new ZipOutputStream(rawOut);
InputStream rawIn = new FileInputStream(inputFile1);
in = new BufferedInputStream(rawIn);
ZipEntry entry = new ZipEntry("c:\\Target\\target.txt");
out.putNextEntry(entry);
byte[] buf = new byte[2048];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
catch(IOException e) {
e.printStackTrace();
}
finally {
try {
if(in != null) {
in.close();
}
if(out != null) {
out.close();
}
}
catch(IOException ignored)
{ }
}
}
}
You need to use File.list(...) to get a list of all the text files in the folder. Then you create a loop to write each file to the zip file.
I just add these lines just after
"File outputFile = new File("c:\Target\Archive_target.zip");
from my previous code.
code added:
File Dir = new File("c:/Target");
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return !name.startsWith(".txt");
}
};
String[] children = Dir.list(filter);
You can get a list of all text files in your directory by using the following method of the File class:
String[] list(FilenameFilter filter)
Create a File object that points to your DIRECTORY (I know it sounds illogical, but that's the way it is- you can test if it is a directory using isDirectory()) and then use the FilenameFilter to say, for example, accept this file if its name contain ".txt"
Create a FilenameFilter that accepts only *.txt file , and then just use
list = File.list(yourNameFilter);
and then just add all the files in the list to the zip file