I have a zip file and after decoding it I get a byte array now I want to create a FileInputStream object with that byte[] object. I dont want to create a file instead pass data content do FileInputStream.
Is there any way ?
following is the code:
byte[] decodedHeaderFileZip = decodeHeaderZipFile(headerExportFile);
FileInputStream fileInputStream = new FileInputStream(decodedHeaderZipFileString);
EDIT:
I wanted to build a ZipInputStream object with a FileInputStream.
I have a zip file and after decoding it I get a byte array now I want to create a FileInputStream object with that byte[] object.
But you don't have a file. You have some data in memory. So a FileInputStream is inappropriate - there's no file for it to read from.
If possible, use a ByteArrayInputStream instead:
InputStream input = new ByteArrayInputStream(decodedHeaderFileZip);
Where possible, express your API in terms of InputStream, Reader etc rather than any specific implementation - that allows you to be flexible in which implementation you use. (What I mean is that where possible, make method parameters and return types InputStream rather than FileInputStream - so that callers don't need to provide the specific types.)
If you absolutely have to create a FileInputStream, you'll need to write the data to a file first.
Related
I have a sample method which copies one file to another using InputStream and OutputStream. In this case, the source file is encoded in 'UTF-8'. Even if I don't specify the encoding while writing to the disk, the destination file has the correct encoding. But, if I have to write a java.lang.String to a file, I need to specify the encoding. Why is that ?
public static void copyFile() {
String sourceFilePath = "C://my_encoded.txt";
InputStream inStream = null;
OutputStream outStream = null;
try{
String targetFilePath = "C://my_target.txt";
File sourcefile =new File(sourceFilePath);
outStream = new FileOutputStream(targetFilePath);
inStream = new FileInputStream(sourcefile);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
System.out.println("File "+targetFilePath+" is copied successful!");
}catch(IOException e){
e.printStackTrace();
}
}
My guess is that since the source file has thee correct encoding and since we read and write one byte at a time, it works fine. And java.lang.String is 'UTF-16' by default and if we write it to the file, it reads one byte at a time instead of 2 bytes and hence garbage values. Is that correct or am I completely wrong in my understanding ?
You are copying the file byte per byte, so you don't need to care about character encoding.
As a rule of thumb:
Use the various InputStream and OutputStream implementations for byte-wise processing (like file copy).
There are some convenience methods to handle text directly like PrintStream.println(). Be careful because most of them use the default platform specific encoding.
Use the various Reader and Writer implemenations for reading and writing text.
If you need to convert between byte-wise and text processing use InputStreamReader and OutputStreamWriter with explicit file encoding.
Do not rely on the default encoding. The default character encoding is platform specific (e.g. Windows-ANSI aka Cp1252 for Windows, usually UTF-8 on Linux).
Example: If you need to read a UTF-8 text file:
BufferedReader reader =
new BufferedReader(new InputStreamReader(new FileInputStream(inFile), "UTF-8"));
Avoid using a FileReader because a FileReader uses always the default encoding.
A special case: If you need random access to a file you should use RandomAccessFile. With it you can read and write data blocks at arbitrary positions. You can read and write raw byte blocks or you can use convenience methods to read and write text. But you should read the documentation carefully. E.g. the methods readUTF() and writeUTF() use a modified UTF-8 encoding.
InputStream, OutputStream, Reader, Writer and RandomAccessFile form the basic IO functionality, enough for most use cases. For advanced IO (e.g. memory mapped files, ...) have a look at package java.nio.
Just read your code! (For the copy part at least ;-) )
When you copy the two files, you copy it byte by byte. There is no conversion to String, thus.
When you write a String into a file, you need to convert it (indirectly sometimes) in an array of byte (byte[]). There you need to specify your encoding.
When you read a file to get a String, you need to know its encoding in order to do it properly. Java doesn't 'skip' any byte but you need to make a conversion once again : from a byte[] to a String.
I'm planing to use SheetJS with rhino. And sheetjs takes a binary object(BLOB if i'm correct) as it's input. So i need to read a file from the system using stranded java I/O methods and store it into a blob before passing it to sheetjs. eg :-
var XLDataWorkBook = XLSX.read(blobInput, {type : "binary"});
So how can i create a BLOB(or appropriate type) from a binary file in java in order to pass it in.
i guess i cant pass streams because i guess XLSX needs a completely created object to process.
I found the answer to this by myself. i was able to get it done this way.
Read the file with InputStream and then write it to a ByteArrayOutputStream. like below.
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
...
buffer.write(bytes, 0, len);
Then create a byte array from it.
byte[] byteArray = buffer.toByteArray();
Finally i did convert it to a Base64 String (which is also applicable in my case) using the "Base64.encodeBase64String()" method in apache.commons.codec.binary package. So i can pass Base64 String as a method parameter.
If you further need there are lot of libraries(3rd-party and default) available for Base64 to Blob conversion as well.
I am using some algorithms which need data represented in array of bytes it is no problem when I am working on text files but I don't know how to put a sound file in a that kind of array. I don't have specified extension of that sound file, so it can be whatever is the easiest. So: How to put a sound file to a byte array in Java?
Thank you.
Alternatively, if you can use Apache common IO library, the FileUtils class contains a readFileToByteArray method for reading a file into a byte array in one line:
byte[] bytes = FileUitls.readFileToByteArray(file);
So: How to put a sound file to a byte array in Java?
File f = new File(soundFilePath, soundFileName);
byte[] soundFileByteArray = new byte[f.length()];
FileInputStream fis = new FileInputStream(f);
fis.read(soundFileByteArray);
I would like to send OutputStream object, which has pdf data, as file to the webbrowser.
The code is as follows.
#RequestMapping(value="/issue", method=RequestMethod.POST)
public void issue(HttpServletResponse response, TimeStampIssueParam param) throws JsonGenerationException, JsonMappingException, IOException {
OutputStream pdfOuput = issue(input);
response.setContentType("application/pdf");
ServletOutputStream respOutput = response.getOutputStream();
....
}
The problem is I already have the outputstream, and I do not want to convert it to byte array.
Any comment would be appreciated.
You can't: you can only copy an InputStream to an OutputStream. Then, you'll can use: org.springframework.util.FileCopyUtils.copy(InputStream, OutputStream)
First, I would say it is wrong to say that the OutputStream has any data. A stream just lets the data through to some destination. Sometimes (SocketOutputStream) this destination may be on a completely different computer, and sometimes (ByteArrayOutputStream) it will be closely related to the stream and even obtainable through it. But this is a detail of a specific stream, not something you can count on from an arbitrary one.
So, not knowing exactly where the result of the issue method comes from it is hard to provide a solution, but a generic OutputStream is not what it should return.
Guessing that the method generates some PDF data and writes it somewhere via an OutputStream, then returns the stream:
If it creates a File and the stream happens to be a FileOutputStream, it should return the file, file path or a FileInputStream for the same file instead.
If it creates eg. a ByteArrayOutputStream, then you already have a byte array, and additionally this stream type has a writeTo method that can be used directly to write the data to the ServletOutputStream; issue just has to return the stream as the proper type not hiding it behind the general interface.
For other OutputStream types, well, it depends on what exactly they are.
A user uploads a large file to my website and I want to gzip the file and store it in a blob. So I have an uncompressed InputStream and the blob wants an InputStream. I know how to compress an InputStream to an Outputstream using GZIPOutputStream, but how do I go from the gzip'ed OutputStream back to the InputStream needed by the blob.
The only way I could find involves using ByteArrayOutputStream and then creating a new InputStream using toByteArray. But that will mean I have an entire copy of the file in memory. And it wouldn't surprise me if the JDBC driver implementation converted the stream to a byte[] also so I'd have two copies in memory.
If you are on java 1.6 you can use java.util.zip.DeflaterInputStream. As far as I can tell, this does exactly what you want. If you can't use 1.6 you should be able to reimplement DeflaterInputStream using java.util.zip.Deflater. When reading the data back from the BLOB use a InflaterInputStream as a filter to get the original data back.