Easy way to write contents of a Java InputStream to an OutputStream
Easy way to write contents of a Java InputStream to an OutputStream
I was surprised to find today that I couldn't track down any simple way to write the contents of an InputStream
to an OutputStream
in Java. Obviously, the byte buffer code isn't difficult to write, but I suspect I'm just missing something which would make my life easier (and the code clearer).
So, given an InputStream
in
and an OutputStream
out
, is there a simpler way to write the following?
byte[] buffer = new byte[1024]; int len = in.read(buffer); while (len != -1) { out.write(buffer, 0, len); len = in.read(buffer); }
Answer by Mike Stone for Easy way to write contents of a Java InputStream to an OutputStream
I think this will work, but make sure to test it... minor "improvement", but it might be a bit of a cost at readability.
byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); }
Answer by Arktronic for Easy way to write contents of a Java InputStream to an OutputStream
PipedInputStream and PipedOutputStream may be of some use, as you can connect one to the other.
Answer by WMR for Easy way to write contents of a Java InputStream to an OutputStream
There's no way to do this a lot easier with JDK methods, but as Apocalisp has already noted, you're not the only one with this idea: You could use IOUtils from Jakarta Commons IO, it also has a lot of other useful things, that IMO should actually be part of the JDK...
Answer by Mikezx6r for Easy way to write contents of a Java InputStream to an OutputStream
As WMR mentioned, org.apache.commons.io.IOUtils
from Apache has a method called copy(InputStream,OutputStream)
which does exactly what you're looking for.
So, you have:
InputStream in; OutputStream out; IOUtils.copy(in,out); in.close(); out.close();
...in your code.
Is there a reason you're avoiding IOUtils
?
Answer by Dilum Ranatunga for Easy way to write contents of a Java InputStream to an OutputStream
PipedInputStream
and PipedOutputStream
should only be used when you have multiple threads, as noted by the Javadoc.
Also, note that input streams and output streams do not wrap any thread interruptions with IOException
s... So, you should consider incorporating an interruption policy to your code:
byte[] buffer = new byte[1024]; int len = in.read(buffer); while (len != -1) { out.write(buffer, 0, len); len = in.read(buffer); if (Thread.interrupted()) { throw new InterruptedException(); } }
This would be an useful addition if you expect to use this API for copying large volumes of data, or data from streams that get stuck for an intolerably long time.
Answer by Andrew Mao for Easy way to write contents of a Java InputStream to an OutputStream
Another possible candidate are the Guava I/O utilities:
http://code.google.com/p/guava-libraries/wiki/IOExplained
I thought I'd use these since Guava is already immensely useful in my project, rather than adding yet another library for one function.
Answer by Alexander Volkov for Easy way to write contents of a Java InputStream to an OutputStream
I think it's better to use a large buffer, because most of the files are greater than 1024 bytes. Also it's a good practice to check the number of read bytes to be positive.
byte[] buffer = new byte[4096]; int n; while ((n = in.read(buffer)) > 0) { out.write(buffer, 0, n); } out.close();
Answer by Jordan LaPrise for Easy way to write contents of a Java InputStream to an OutputStream
Simple Function
If you only need this for writing an InputStream
to a File
then you can use this simple function:
private void copyInputStreamToFile( InputStream in, File file ) { try { OutputStream out = new FileOutputStream(file); byte[] buf = new byte[1024]; int len; while((len=in.read(buf))>0){ out.write(buf,0,len); } out.close(); in.close(); } catch (Exception e) { e.printStackTrace(); } }
Answer by user1079877 for Easy way to write contents of a Java InputStream to an OutputStream
If you are using Java 7, Files (in the standard library) is the best approach:
/* You can get Path from file also: file.toPath() */ Files.copy(InputStream in, Path target) Files.copy(Path source, OutputStream out)
Edit: Of course it's just useful when you create one of InputStream or OutputStream from file. Use file.toPath()
to get path from file.
To write into an existing file (e.g. one created with File.createTempFile()
), you'll need to pass the REPLACE_EXISTING
copy option (otherwise FileAlreadyExistsException
is thrown):
Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING)
Answer by DejanLekic for Easy way to write contents of a Java InputStream to an OutputStream
Use Commons Net's Util class:
import org.apache.commons.net.io.Util; ... Util.copyStream(in, out);
Answer by Pranav for Easy way to write contents of a Java InputStream to an OutputStream
you can use this method
public static void copyStream(InputStream is, OutputStream os) { final int buffer_size=1024; try { byte[] bytes=new byte[buffer_size]; for(;;) { int count=is.read(bytes, 0, buffer_size); if(count==-1) break; os.write(bytes, 0, count); } } catch(Exception ex){} }
Answer by Andrejs for Easy way to write contents of a Java InputStream to an OutputStream
Using Guava's ByteStreams.copy()
:
ByteStreams.copy(inputStream, outputStream);
Answer by Nour Rteil for Easy way to write contents of a Java InputStream to an OutputStream
public static boolean copyFile(InputStream inputStream, OutputStream out) { byte buf[] = new byte[1024]; int len; long startTime=System.currentTimeMillis(); try { while ((len = inputStream.read(buf)) != -1) { out.write(buf, 0, len); } long endTime=System.currentTimeMillis()-startTime; Log.v("","Time taken to transfer all bytes is : "+endTime); out.close(); inputStream.close(); } catch (IOException e) { return false; } return true; }
Answer by Sivakumar for Easy way to write contents of a Java InputStream to an OutputStream
Using Java7 and try-with-resources, comes with a simplified and readable version.
try(InputStream inputStream = new FileInputStream("C:\\mov.mp4"); OutputStream outputStream = new FileOutputStream("D:\\mov.mp4")){ byte[] buffer = new byte[10*1024]; for (int length; (length = inputStream.read(buffer)) != -1; ){ outputStream.write(buffer, 0, length); outputStream.flush(); } }catch (FileNotFoundException exception){ exception.printStackTrace(); }catch (IOException ioException){ ioException.printStackTrace(); }
Answer by Bohemian for Easy way to write contents of a Java InputStream to an OutputStream
A IMHO more minimal snippet (that also more narrowly scopes the length variable):
byte[] buffer = new byte[2048]; for (int n = in.read(buffer); n >= 0; n = in.read(buffer)) out.write(buffer, 0, n);
As a side note, I don't understand why more people don't use a for
loop, instead opting for a while
with an assign-and-test expression that is regarded by some as "poor" style.
Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72
0 comments:
Post a Comment