I have a simple code that is supposed to make txt file zipped, though txt file has some content, it's empty in a zip folder ( it has 89 bytes ( like buffer ) but all are just spaces.
The interesting part is that if I write
byte[] buffer = Files.readAllBytes(path);
my code is working.
I am new to java and would appreciate your help a lot. Because I trully don't understand what I am doing wroing.
public class Test {
public static void main(String[] args) throws IOException {
try (FileInputStream fis = new FileInputStream("C:\\Users\\10\\Desktop\\ds.txt");
ZipInputStream zis = new ZipInputStream(fis);
ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(Paths.get("C:\\Users\\10\\Desktop\\ds.zip")))) {
byte[] buffer = new byte[fis.available()];
zos.putNextEntry(new ZipEntry("ds.txt"));
zis.read(buffer);
zos.write(buffer);
zos.closeEntry();
}
Since the text file is not zipped yet, don't use a ZipInputStream to read it. Just use the FileInputStream, or even better the NIO.2 File API (you're using it already to create the ZipOutputStream but not to create the InputStream).
There is even a file system provider for the NIO.2 File API to read/ write to Zip files using the same API: https://docs.oracle.com/javase/7/docs/technotes/guides/io/fsp/zipfilesystemprovider.html (For Java 11+ the following module is required: https://docs.oracle.com/en/java/javase/11/docs/api/jdk.zipfs/module-summary.html)
Also make sure to use try-with-resources for the OutputStream as well, not just the InputStream, to properly close the stream in the finally block.
Related
The steps I followed are.
get all objects from recursive objects
Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder()
.bucket(bucketName).recursive(true).build());
Then getting all streams of matching the prefix
InputStream stream = minioClient.getObject(GetObjectArgs.builder()
.bucket(bucketName).object(objectName).build());
the list of multiple stream got by the InputStream stream How do we convert it into zip file ?
tried the following code but it's (zipOut) coming as null.
downloading empty zip, How do we fix this ?
ByteArrayOutputStream fos = new ByteArrayOutputStream();
ZipOutputStream zipOut = new ZipOutputStream(fos);
ZipEntry zipEntry1 = new ZipEntry(objectName);
zipEntry1.setSize(resource.contentLength());
zipEntry1.setTime(System.currentTimeMillis());
zipOut.putNextEntry(zipEntry1);
StreamUtils.copy(stream.readAllBytes(), zipOut);
zipOut.closeEntry();
Thanks in advance.
byte[] test = getByteArry(excelfikepath)
I have one method where it returns the bytearray of the excel .xlsx file. To read this file i need to write these byte array using FileOutputStream on one server and from there i am calling another method which will read and process that excel from the server.
There is some limitation because of which i cant read excel file directly i have to put it onto another server and process.
Just wanted to know is there any way by which i can make use of this byte array and read excel file IN MEMORY instead of writing it on server.
This will help to get byte array out of an excel file.
public static byte[] getFileByteArr(String fileName) throws InvalidFormatException, IOException {
try (OPCPackage opcPackage = OPCPackage.open(new File(fileName))) {
try (XSSFWorkbook workbook = (XSSFWorkbook) WorkbookFactory.create(opcPackage)) {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
workbook.write(bos);
return bos.toByteArray();
}
}
}
}
I am trying to add a file to a zip archive. I want to do something like this
public void zipFile(Path fileToZip, Path zipFile) {
ZipOutputStream zipOut = new ZipOutputStream(Files.newOutputStream(zipFile, CREATE, APPEND));
FileChannel outputChannel = new FileOutputStream(zipOut).getChannel() //How to go from zipoutputstream to FileChannel...
FileChannel inputChannel = FileChannel.open(zipFile, READ)
ZipEntry zipEntry = new ZipEntry(fileToZip.toString());
zipOut.putNextEntry(zipEntry);
inputChannel.transferTo (0, inputChannel.size(), outputChannel);
outputChannel.close();
inputChannel.close();
}
but ZipOutputStream doesn't have a getChannel() like FileOutputStream does. How can I create a zip file using channels?
You can turn any OutputStream into a Channel using the Channels.newChannel method.
Turns out, this is very very easy to do. Don't use channels or anything. Just create a zipfilesystem and copy the files over.
http://docs.oracle.com/javase/7/docs/technotes/guides/io/fsp/zipfilesystemprovider.html
I have a chararray which holds coordinates in every index. I want to compress the array with zip algorithm and write the zipped version of the array to a file. My idea was that i run the chararray through a zip stream and write it afterwards directly to a file like test.txt. The problem is, that nothing is written to the file after the execution of the code. Can somebody please help me solve that problem?
Kind regards Lorenzo
Here my current code:
byte[] bytes = Charset.forName("UTF-8").encode(CharBuffer.wrap(sample)).array();
FileOutputStream out = new FileOutputStream(cscFile, true);
byte[] compressed = new byte[bytes.length];
ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
ZipInputStream zi = new ZipInputStream(bi);
ZipEntry entry = null;
while ((entry = zi.getNextEntry()) != null) {
zi.read(compressed);
for(int i = 0; i<bytes.length;i++){
out.write(compressed[i]);
}
out.flush();
out.close();
zi.closeEntry();
}
zi.close();
You will probably have to slightly modify your code with something like this:
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File("your zip file name")));
ZipEntry entry = new ZipEntry("zipped file name");
entry.setSize(bytes.length);
zos.putNextEntry(entry);
zos.write(bytes);
zos.closeEntry();
zos.close();
Explanation:
To compress writen data, use ZipOutputStream and give created FileOutputStream as constructor argument. After that, create ZipEntry, which represents file inside your zip file and write contents of byte array into it.
Hope it helps.
See similar question here: https://stackoverflow.com/a/357892/3115098
I'm using the Java API for reading and writing to the Google App Engine Blobstore.
I need to zip files directly into the Blobstore, meaning I have String objects which I want to be stored in the Blobstore when zipped.
My problem is that standard zipping methods are using OutputStream to write, while it seems that GAE doesn't provide one for writing to the Blobstore.
Is there a way to combine those APIs, or are there different APIs I can use (I haven't found such)?
If I am not wrong, you can try to use the Blobstore low level API. It offers a Java Channel (FileWriteChannel), so you could probably convert it to an OutputStream:
Channels.newOutputStream(channel)
And use that output stream with the java.util.zip.* classes you are currently using (here you have a related example that uses Java NIO to zip something to a Channel/OutputStream)
I have not tried it.
Here is one example to write content file and zip it and store it into blobstore:
AppEngineFile file = fileService.createNewBlobFile("application/zip","fileName.zip");
try {
FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);
//convert as outputstream
OutputStream blobOutputStream = Channels.newOutputStream(writeChannel);
ZipOutputStream zip = new ZipOutputStream(blobOutputStream);
zip.putNextEntry(new ZipEntry("fileNameTozip.txt"));
//read the content from your file or any context you want to get
final byte data[] = IOUtils.toByteArray(file1InputStream);
//write byte data[] to zip
zip.write(bytes);
zip.closeEntry();
zip.close();
// Now finalize
writeChannel.closeFinally();
} catch (IOException e) {
throw new RuntimeException(" Writing file into blobStore", e);
}
The other answer is using BlobStore api, but currently the recommended way is to use App Engine GCS client.
Here is what I use to zip multiple files in GCS :
public static void zipFiles(final GcsFilename targetZipFile,
Collection<GcsFilename> filesToZip) throws IOException {
final GcsFileOptions options = new GcsFileOptions.Builder()
.mimeType(MediaType.ZIP.toString()).build();
try (GcsOutputChannel outputChannel = gcsService.createOrReplace(targetZipFile, options);
OutputStream out = Channels.newOutputStream(outputChannel);
ZipOutputStream zip = new ZipOutputStream(out)) {
for (GcsFilename file : filesToZip) {
try (GcsInputChannel readChannel = gcsService.openPrefetchingReadChannel(file, 0, MB);
InputStream is = Channels.newInputStream(readChannel)) {
final GcsFileMetadata meta = gcsService.getMetadata(file);
if (meta == null) {
log.warn("{} NOT FOUND. Skipping.", file.toString());
continue;
}
final ZipEntry entry = new ZipEntry(file.getObjectName());
zip.putNextEntry(entry);
ByteStreams.copy(is, zip);
zip.closeEntry();
}
zip.flush();
}
}