Java by API/java.io/InputStream

Материал из Java эксперт
Перейти к: навигация, поиск

extends InputStream

   <source lang="java">
 

import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; public class Main {

 public static void main(String[] argv) throws Exception {
   ByteBuffer buf = ByteBuffer.allocate(10);
   OutputStream os = new ByteBufferBackedOutputStream(buf);
   InputStream is = new  ByteBufferBackedInputStream(buf);
 }

} class ByteBufferBackedInputStream extends InputStream{

 ByteBuffer buf;
 ByteBufferBackedInputStream( ByteBuffer buf){
   this.buf = buf;
 }
 public synchronized int read() throws IOException {
   if (!buf.hasRemaining()) {
     return -1;
   }
   return buf.get();
 }
 public synchronized int read(byte[] bytes, int off, int len) throws IOException {
   len = Math.min(len, buf.remaining());
   buf.get(bytes, off, len);
   return len;
 }

} class ByteBufferBackedOutputStream extends OutputStream{

 ByteBuffer buf;
 ByteBufferBackedOutputStream( ByteBuffer buf){
   this.buf = buf;
 }
 public synchronized void write(int b) throws IOException {
   buf.put((byte) b);
 }
 public synchronized void write(byte[] bytes, int off, int len) throws IOException {
   buf.put(bytes, off, len);
 }
 

}


 </source>
   
  
 
  



InputStream: read(byte[] b)

   <source lang="java">
  

import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class Main {

 public static void main(String[] args) {
   try {
     copy(System.in, System.out);
   } catch (IOException ex) {
     System.err.println(ex);
   }
 }
 public static void copy(InputStream in, OutputStream out) throws IOException {
   byte[] buffer = new byte[1024];
   while (true) {
     int bytesRead = in.read(buffer);
     if (bytesRead == -1)
       break;
     out.write(buffer, 0, bytesRead);
   }
 }

}


 </source>
   
  
 
  



InputStream: read(byte[] b, int off, int len)

   <source lang="java">
 

import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; public class Main {

 public static void main(String[] argv) throws Exception {
   File file = new File("c:\\a.bat");
   InputStream is = new FileInputStream(file);
   long length = file.length();
   if (length > Integer.MAX_VALUE) {
     System.out.println("File is too large");
   }
   byte[] bytes = new byte[(int) length];
   int offset = 0;
   int numRead = 0;
   while (numRead >= 0) {
     numRead = is.read(bytes, offset, bytes.length - offset);
     offset += numRead;
   }
   if (offset < bytes.length) {
     throw new IOException("Could not completely read file " + file.getName());
   }
   is.close();
   System.out.println(new String(bytes));
 }

}


 </source>