How To : Write a File with FileOutputStream? - java

What I'm doing is that the file and each line of data I'm reading for BufferOutputStream will be saved in a FileOutputStream and I want to specify the output data.

If i have understood correct, you want to download the file from S3 and write to your local directory using BufferedOutputStream .
S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
InputStream is = object.getObjectContent();
// Creating file
File file= new File(localFilePath);
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos= new BufferedOutputStream(fos);
int read = -1;
while ((read = is.read()) != -1) {
bos.write(read);
}
bos.flush();
bos.close();
is.close();

Related

Download zip file when call api

FileOutputStream fos = new FileOutputStream(FILE_NAME);
ZipOutputStream zipOut = new ZipOutputStream(fos);
for (File file : files) {
FileInputStream fis = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(file.getName());
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
fis.close();
}
zipOut.close();
fos.close();
I have a zip file, I want to download it when I call the api.With the zip file, I don't know how to download. Hope to get help from you.
If you are using Spring/Spring Boot. You can follow this stackoverflow thread Download File in Spring

How to convert the Video file to byte array?

I need to convert a video file to byte array and then send the byte array to a server, but when I upload the byte array the server did not receive it in the correct format. I convert the file like below:-
buffer=new byte[1024];
os=new ByteArrayOutputStream();
FileInputStream fis=new FileInputStream(file);
int read;
while ((read=fis.read(buffer))!=-1){
os.write(buffer,0,read);
}
fis.close();
os.close();
Following are the ways to convert the file into byte[]
First
File file = new File(path);
int size = (int) file.length();
byte[] bytes = new byte[size];
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
buf.read(bytes, 0, bytes.length);
buf.close();
Second
byte bytes[] = new byte[(int) file.length()];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
DataInputStream dis = new DataInputStream(bis);
dis.readFully(bytes);
Third
byte bytes[] = FileUtils.readFileToByteArray(photoFile)
The only drawback is to add this dependency in your build.gradle app :
implementation 'commons-io:commons-io:2.5'
File file = new File("filepath");
//init array with file length
byte[] bytesArray = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(bytesArray); //read file into bytes[]
fis.close();
return bytesArray;
Try this! hopefully it will work.

Saving a spreadsheet to disk using java

I have a requirement to store the uploaded spreadsheet to the disk. I am using the below code to do the same and receiving the file is corrupted error from the excel.
byte[] bytes = null;
File uploadedFile = new File("D://xlsxTest//BNG Issue.xlsx");
File file = new File("D://xlsxTest//sample1.xlsx");
FileOutputStream outStream = null;
InputStream inputStream = null;
try{
if(!file.exists()){
file.createNewFile();
}
outStream = new FileOutputStream(file);
if (uploadedFile != null) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
inputStream = new FileInputStream(uploadedFile);;
int c = 0;
while (c != -1) {
c = inputStream.read();
byteArrayOutputStream.write((char) c);
}
bytes = byteArrayOutputStream.toByteArray();
}
outStream.write(bytes);
}catch(Exception e){
e.printStackTrace();
}finally{
try{
outStream.close();
}catch(Exception e){
e.printStackTrace();
}
}
I tried using a file of 83KB size and the resultant file is 82.5KB.
Any help would be appreciated.
Thanks.
Try using Apace POI, Convert .xls or .xlsx file to byte array using OPCPackage and XSSFWorkbook with below code.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OPCPackage pkg = OPCPackage.open(new File(fullFileName));
XSSFWorkbook wb = new XSSFWorkbook(pkg);
wb.write(baos);
byte[] fileContent = baos.toByteArray();
Apache POI takes care to extract all information of the excel file while converting to byte array.

How to compress and download a xlsx file using zip in java

I'm creating a xlsx using poi and saving it on fileSystem. I need to download the file on a servlet call and due to memory constraints I did not create a xssf workbook object and used the following code instead :
byte[] buf = new byte[1024];
ServletOutputStream sOut = response.getOutputStream();
FileInputStream input = null;
try {
long length = fileToRead.length();
input = new FileInputStream(fileToRead);
while ((input != null) && ((length = input.read(buf)) != -1)) {
sOut.write(buf, 0, (int) length);
}
Where fileToRead is the file present at the file system.
How can I integrate this with How to create a zip file in Java
You could use
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
....
ze = new ZipEntry("xlsData");
zos.putEntry (ze);
// loop
zos.write(buf, 0, (int) length);
// finally
zos.close();

Unzipping the content of a file

I have an application where Service A will provide a zipped data to Service B. And service B needs to unzip it.
Service A has an exposes method getStream and it gives ByteArrayInputStream as output and the data init is zipped data.
However passing that to GzipInputStream gives Not in Gzip format exception.
InputStream ins = method.getInputStream();
GZIPInputStream gis = new GZIPInputStream(ins);
This gives an exception. When the file is dumped in Service A the data is zipped. So getInputStream gives the zipped data.
How to process it ans pass it to the GzipInputStream?
Regards
Dheeraj Joshi
If it zipped, then you must use ZipInputstream.
It does depend on the "zip" format. There are multiple formats that have the zip name (zip, gzip, bzip2, lzip) and different formats call for different parsers.
http://en.wikipedia.org/wiki/List_of_archive_formats
http://www.codeguru.com/java/tij/tij0115.shtml
http://docstore.mik.ua/orelly/java-ent/jnut/ch25_01.htm
If you are using zip then try this code:
public void doUnzip(InputStream is, String destinationDirectory) throws IOException {
int BUFFER = 2048;
// make destination folder
File unzipDestinationDirectory = new File(destinationDirectory);
unzipDestinationDirectory.mkdir();
ZipInputStream zis = new ZipInputStream(is);
// Process each entry
for (ZipEntry entry = zis.getNextEntry(); entry != null; entry = zis
.getNextEntry()) {
File destFile = new File(unzipDestinationDirectory, entry.getName());
// create the parent directory structure if needed
destFile.getParentFile().mkdirs();
try {
// extract file if not a directory
if (!entry.isDirectory()) {
// establish buffer for writing file
byte data[] = new byte[BUFFER];
// write the current file to disk
FileOutputStream fos = new FileOutputStream(destFile);
BufferedOutputStream dest = new BufferedOutputStream(fos,
BUFFER);
// read and write until last byte is encountered
for (int bytesRead; (bytesRead = zis.read(data, 0, BUFFER)) != -1;) {
dest.write(data, 0, bytesRead);
}
dest.flush();
dest.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
is.close();
}
public static void main(String[] args) {
UnzipInputStream unzip = new UnzipInputStream();
try {
InputStream fis = new FileInputStream(new File("test.zip"));
unzip.doUnzip(fis, "output");
} catch (IOException e) {
e.printStackTrace();
}
}

Categories

Resources