I am currently trying to solve one problem for reading and writing files in Java.
So the task is, I am directly getting the InputStream object of file which I want to read (I don't have actual file just the InputStream object) and from this object I want to recreate the original file.
I was trying to read the data from file byte by byte and write the same in anather file.
But it is only working for .txt files not for doc, docx, PDF files. I haven't checked for rest of the non .txt format but I want it work for all the formats.
For Non txt formats the files are getting generated but content from it is not visible.
So my question is How can I recreate the file using just InputStream object for all types file format.
Below is the sample code that I have been using to write the file.
File file = new File("/home/sumit/Documents/newAbc.docx");
File fileAbc = new File("/home/sumit/Documents/abc.docx");
InputStream inputStream = new FileInputStream(fileAbc); // this is just for this sample code snippet but orginally I already have InputStream object.
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
int data = inputStream.read();
while(data != -1) {
//do something with data...
bw.write(data);
data = inputStream.read();
}
inputStream.close();
bw.close();
Above code is getting properly compiled and executed but the created file is not displaying content properly.
When searched I found I can not directly read Doc, PDf etc. from here: Reading .docx file in java
but from http://poi.apache.org/ POI library I did not find anything that will tell me how to write into file using InputStream.
Does anyone know how above problem can be solved?