2015-02-24 13:19

[Java] InputStream to OutputStream

Stream Read / Write
  1. import java.io.FileInputStream; 
  2. import java.io.FileOutputStream; 
  3. import java.io.InputStream; 
  4. import java.io.OutputStream; 
  5.  
  6. public class StreamCopy1 { 
  7.  
  8.    public static void main(String[] args) throws Exception { 
  9.  
  10.        InputStream input = new FileInputStream("input.txt"); 
  11.        OutputStream output = new FileOutputStream("output.txt"); 
  12.  
  13.        int byteValue; 
  14.        while ((byteValue = input.read()) != -1) { 
  15.            output.write(byteValue); 
  16.        } 
  17.  
  18.        input.close(); 
  19.        output.close(); 
  20.    } 
  21. } 


Apache IOUtils.copy
  1. import java.io.FileInputStream; 
  2. import java.io.FileOutputStream; 
  3. import java.io.InputStream; 
  4. import java.io.OutputStream; 
  5.  
  6. import org.apache.commons.io.IOUtils; 
  7.  
  8. public class StreamCopy2 { 
  9.  
  10.    public static void main(String[] args) throws Exception { 
  11.  
  12.        InputStream input = new FileInputStream("input.txt"); 
  13.        OutputStream output = new FileOutputStream("output.txt"); 
  14.  
  15.        IOUtils.copy(input, output); 
  16.  
  17.        input.close(); 
  18.        output.close(); 
  19.    } 
  20. } 

0 回應: