I have a query that is in the below code i have a file name as shown below
String filename = "C:\\abcd\\Ttre.xls";
which later on i am passing to FileInputStream object as shown below
FileInputStream fileStream = new FileInputStream(filename);
workbook = new HSSFWorkbook(fileStream);
the happy case above was that filename was hardcoded which was pass to the FileInputStream object but lets say if some one is giving me file in form of byte array then how to deal with that case for example
as shown below
public void abcd( byte[] excelByteStream) {
//how to pass the the byte array file to the FileInputStream object
}
so in that case how we would pass the bytestream file to the FileInputStream object please advise
You can't. FileInputStream is a type of InputStream that expects a file as input.
To use a byte array, you would use java.io.ByteArrayInputStream, which is also another type of InputStream.
Just make sure that whatever is expecting an input stream is defined to accept the more generic InputStream. (e.g.: public HSSFWorkbook(InputStream inputStream) { // HSSFWorkbook constructor definition)
Documentation: ByteArrayInputStream.
EDIT: A more complete example
If your HSSFWorkbook class has the constructor currently defined as:
public HSSFWorkbook(FileInputStream inputStream) {
// ...
}
... you would want to change it to accept the more generic InputStream class, which would now allow you to pass it either a FileInputStream or a ByteArrayInputStream instance depending on where you call it from. Like this:
public HSSFWorkbook(InputStream inputStream) {
// ...
}
Then you can instantiate your HSSFWorkbook using either option:
FileInputStream fileStream = new FileInputStream(filename);
workbook = new HSSFWorkbook(fileStream); // still works
... or ...
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(excelByteStream);
workbook = new HSSFWorkbook(byteArrayInputStream ); // now also works.
Use ByteArrayInputStream instead of FileInputStream:
workbook = new HSSFWorkbook(excelByteStream);
Related
I am writing a csv file in a very old java application so i can not use all the new Java 8 streams.
Writer writer = new OutputStreamWriter(new FileOutputStream("file.csv"));
writer.append("data,");
writer.append("data,");
...
Then I need to transform the writer object into a ByteArrayInputStream.
How can i do it ?
Thanks in advance.
Best regards.
This depends on what you are trying to do.
If you are writing a bunch of data to the file and THEN reading the file you will want to use a FileInputStream in place of your ByteArrayInputStream.
If you want to write a bunch of data to a byte array then you should take a look at using a ByteArrayOutputStream. If you then need to read the byte array as a ByteArrayInputStream you can pass the ByteArrayOutputStream into the input stream like what is shown below. Keep in mind this only works for writing and THEN reading. You can not use this like a buffer.
//Create output stream
ByteArrayOutputStream out = new ByteArrayOutputStream();
//Create Writer
Writer writer = new OutputStreamWriter(out);
//Write stuff
...
//Close writer
writer.close();
//Create input stream using the byte array from out as input.
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Short answer: you can't.
A ByteArrayInputStream is just not assignable from a OutputStreamWriter.
Since you're probably after write, you can just read the file back to a byte[] and then construct a ByteArrayInputStream with it:
File file = new File("S:\\Test.java");
FileInputStream fis = new FileInputStream(file);
byte[] content = new byte[(int) file.length()];
fis.read(content,0,content.length);
ByteArrayInputStream bais = new ByteArrayInputStream(content);
I have 2 java classes. Let them be class A and class B.
Class A gets String input from user and stores the input as byte into the FILE, then Class B should read the file and display the Byte as String.
CLASS A:
File file = new File("C:\\FILE.txt");
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
String fwrite = user_input_1+"\n"+user_input_2;
fos.write(fwrite.getBytes());
fos.flush();
fos.close();
In CLASS B, I wrote the code to read the file, but I don't know how to read the file content as bytes.
CLASS B:
fr = new FileReader(file);
br = new BufferedReader(fr);
arr = new ArrayList<String>();
int i = 0;
while((getF = br.readLine()) != null){
arr.add(getF);
}
String[] sarr = (String[]) arr.toArray(new String[0]);
The FILE.txt has the following lines
[B#3ce76a1
[B#36245605
I want both these lines to be converted into their respective string values and then display it. How to do it?
Are you forced to save using a String byte[] representation to save data? Take a look at object serialization (Object Serialization Tutorial), you don't have to worry about any low level line by line read or write methods.
Since you are writing a byte array through the FileOutputStream, the opposite operation would be to read the file using the FileInputStream, and construct the String from the byte array:
File file = new File("C:\\FILE.txt");
Long fileLength = file.length();
byte[] bytes = new byte[fileLength.intValue()]
try (FileInputStream fis = new FileInputStream(file)) {
fis.read(bytes);
}
String result = new String(bytes);
However, there are better ways of writing the String to a file.
You could write it using the FileWriter, and read using FileReader (possibly wrapping them by the corresponding BufferedReader/Writer), this will avoid creating intermediate byte array. Or better yet, use Apache Commons' IOUtils or Google's Guava libraries.
I have the following situation, into a method I have:
ByteArrayInputStream fis = new ByteArrayInputStream(Bean.getValoreString("PDFmulti", "PDF").getBytes());
As you can see fis varialbe is a ByteArrayInputStream and Bean.getValoreString("PDFmulti", "PDF").getBytes() returns a byte[]
So now I need to put the content of the fis object into a PDF using iText.
What can I do to do it? I think that I have to read this input stream and put its content into a ByteArrayOutputStream, something like this:
public static byte[] readFully(InputStream stream) throws IOException
{
byte[] buffer = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = stream.read(buffer)) != -1)
{
baos.write(buffer, 0, bytesRead);
}
return baos.toByteArray();
}
But then?
In a comment to your previous question https://stackoverflow.com/questions/28342714/how-to-convert-a-string-object-representing-a-pdf-into-a-bytearrayinputstream-th, you say I have to concatenate all the PDF to create a single PDF.
This is crucial information that you are omitting in your new question. If I read your new question, it's as if you want to persist a PDF that exists in a byte[] in some other form. For instance: you want to store it as a file.
If that is the case, then you don't need iText! Just write the bytes to a FileOutputStream!
However, now that I know that you need to concatenate files, I know that you need several PdfReader instances and then use these PdfReader instances in combination with PdfCopy (or PdfSmartCopy) to create a single PDF out of a series of different PDFs.
That's a completely different question! In that case, why would you create a ByteArrayOutputStream? There is a PdfReader contructor that accepts an InputStream as a parameter. Why not pass fis to that constructor?
I have a file that can be any thing like ZIP, RAR, txt, CSV, doc etc. I would like to create a ByteArrayInputStream from it.
I'm using it to upload a file to FTP through FTPClient from Apache Commons Net.
Does anybody know how to do it?
For example:
String data = "hdfhdfhdfhd";
ByteArrayInputStream in = new ByteArrayInputStream(data.getBytes());
My code:
public static ByteArrayInputStream retrieveByteArrayInputStream(File file) {
ByteArrayInputStream in;
return in;
}
Use the FileUtils#readFileToByteArray(File) from Apache Commons IO, and then create the ByteArrayInputStream using the ByteArrayInputStream(byte[]) constructor.
public static ByteArrayInputStream retrieveByteArrayInputStream(File file) {
return new ByteArrayInputStream(FileUtils.readFileToByteArray(file));
}
The general idea is that a File would yield a FileInputStream and a byte[] a ByteArrayInputStream. Both implement InputStream so they should be compatible with any method that uses InputStream as a parameter.
Putting all of the file contents in a ByteArrayInputStream can be done of course:
read in the full file into a byte[]; Java version >= 7 contains a convenience method called readAllBytes to read all data from a file;
create a ByteArrayInputStream around the file content, which is now in memory.
Note that this may not be optimal solution for very large files - all the file will stored in memory at the same point in time. Using the right stream for the job is important.
A ByteArrayInputStream is an InputStream wrapper around a byte array. This means you'll have to fully read the file into a byte[], and then use one of the ByteArrayInputStream constructors.
Can you give any more details of what you are doing with the ByteArrayInputStream? Its likely there are better ways around what you are trying to achieve.
Edit:
If you are using Apache FTPClient to upload, you just need an InputStream. You can do this;
String remote = "whatever";
InputStream is = new FileInputStream(new File("your file"));
ftpClient.storeFile(remote, is);
You should of course remember to close the input stream once you have finished with it.
This isn't exactly what you are asking, but is a fast way of reading files in bytes.
File file = new File(yourFileName);
RandomAccessFile ra = new RandomAccessFile(yourFileName, "rw"):
byte[] b = new byte[(int)file.length()];
try {
ra.read(b);
} catch(Exception e) {
e.printStackTrace();
}
//Then iterate through b
This piece of code comes handy:
private static byte[] readContentIntoByteArray(File file)
{
FileInputStream fileInputStream = null;
byte[] bFile = new byte[(int) file.length()];
try
{
//convert file into array of bytes
fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
fileInputStream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return bFile;
}
Reference: http://howtodoinjava.com/2014/11/04/how-to-read-file-content-into-byte-array-in-java/
I am about to write junit tests for a XML parsing Java class that outputs directly to an OutputStream. For example xmlWriter.writeString("foo"); would produce something like <aTag>foo</aTag> to be written to the outputstream held inside the XmlWriter instance. The question is how to test this behaviour. One solution would of course be to let the OutputStream be a FileOutputStream and then read the results by opening the written file, but it isn't very elegant.
Use a ByteArrayOutputStream and then get the data out of that using toByteArray(). This won't test how it writes to the stream (one byte at a time or as a big buffer) but usually you shouldn't care about that anyway.
If you can pass a Writer to XmlWriter, I would pass it a StringWriter. You can query the StringWriter's contents using toString() on it.
If you have to pass an OutputStream, you can pass a ByteArrayOutputStream and you can also call toString() on it to get its contents as a String.
Then you can code something like:
public void testSomething()
{
Writer sw = new StringWriter();
XmlWriter xw = new XmlWriter(sw);
...
xw.writeString("foo");
...
assertEquals("...<aTag>foo</aTag>...", sw.toString());
}
It's simple. As #JonSkeet said:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// pass the baos to be writed with "value", for this example
byte[] byteArray = baos.toByteArray();
Assert.assertEquals("value", new String(byteArray));