I am writing this method which will convert an InputStream into a file, but the method is working for some of the inputs but not for all (when i pass a zip file as an InputStream it works). It simply creates a file with 0 bytes.
I know that this question has been asked before, before anyone mark it as duplicate please go through what i have done so far..
This is what I have tried so far. Most of these solutions are found from StackOverFlow.
private void saveFile(String filename, InputStream input) throws IOException
{
if (filename == null) {
return;
}
File file = new File(filename);
//*************** 1st *****************
String stringFromInputStream = IOUtils.toString(input, "UTF-8");
System.out.println("This is inputStream:"+stringFromInputStream);
FileUtils.writeStringToFile(file, StringFromInputStream);
//********************2nd **********************
String stringFromInputStream = IOUtils.toString(input, "UTF-8");
byte[] aByte = StringFromInputStream.getBytes();
FileOutputStream fos=new FileOutputStream(file);
IOUtils.write(aByte, fos);
//*******************3rd**********************
String stringFromInputStream = IOUtils.toString(input, "UTF-8");
byte[] aByte = StringFromInputStream.getBytes();
FileOutputStream fos=new FileOutputStream(file);
fos.write(aByte);
//*********************4th*********************
String stringFromInputStream = IOUtils.toString(input, "UTF-8");
FileWriter fr=new FileWriter(file);
BufferedWriter br=new BufferedWriter(fr);
br.write(StringFromInputStream);
br.flush();
fr.flush();
br.close();
fr.close();
//*************5th**********************
String stringFromInputStream = IOUtils.toString(input, "UTF-8");
Files.write(Paths.get(filename), StringFromInputStream.getBytes());
//************************6th**************
String stringFromInputStream = IOUtils.toString(input, "UTF-8");
FileUtils.writeStringToFile(file, StringFromInputStream);
//******************7th*********************
String stringFromInputStream = IOUtils.toString(input, "UTF-8");
FileWriter fileWriter = new FileWriter(file);
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print(StringFromInputStream);
fileWriter.flush();
fileWriter.close();
//**********************8th*************************
final Path destination = Paths.get(filename);
try (
final InputStream in = input;
) {
Files.copy(in, destination,StandardCopyOption.REPLACE_EXISTING);
}
// ************* This one works but not for all(Sometimes creats a file with 0 bytes) ****************
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
BufferedInputStream bis = new BufferedInputStream(input);
int aByte;
while ((aByte = bis.read()) != -1) {
bos.write(aByte);
}
bos.flush();
fos.flush();
bos.close();
fos.close();
bis.close();
........
}