betacode

Руководство Java IO Binary Streams

  1. Обзор бинарного потока (Binary Stream)
  2. Class InputStream & OutputStream
  3. Class ByteArrayInputStream & ByteArrayOutputStream
  4. Class ObjectInputStream & ObjectOutputStream
  5. Class DataInputStream & DataOutputStream
  6. Dẫy luồng đầu vào nhị phân - SequenceInputStream
  7. Luồng dữ liệu đường ngầm nhị phân (PipedInputStream,PipedOutputStream)
  8. Class PrintStream

1. Обзор бинарного потока (Binary Stream)

Бинарная система лидируется с помощью 2 class-а InputStream и OutputStream под этими 2 class-ми имеется большое количество подклассов, если сравнить по силе, то реляционная связь бинарной системы(Binary Stream) разнообразней и сложнее чем поток сиволов (Charactor Stream). С JDK1.5 в бинарной системе имеется 2 class-а которые рекомендуются не использовать это LineNumberInputStream и StringBufferInputStream так как они устарели.

2. Class InputStream & OutputStream

Class InputStream это астрактный класс, поэтому вы не можете создать объект InputStream через сам класс InputStream. Но это класс будет разделен на многие ветви через потомков подклассов. Смотря на случай вы можете создать объект InputStream из составляющих подклассов.
// Java.io.InputStream is an abstract class
// Could not initialize InputStream object directly, through class InputStream.
// Initialize InputStream object should be through its subclasses ..

InputStream fileStream =new FileInputStream("C:/test.txt");

// Input stream from the keyboard ..
InputStream is = System.in;
Class OutputStream это абстрактный класс, поэтому вы не можете создать объект OutputStream через сам класс OutputStream . Но этот класс разделяется на разные ветви через подклассы, которые играют важную роль. Смотря по ситуации вы можете создать объект InputStream из составляющих подклассов.
// Java.io.OutputStream is an abstract class
// Could not initialize OutputStream object directly, through class OutputStream.
// Initialize OutputStream object should be through its subclasses ..

// Stream write to file.
OutputStream os=new FileOutputStream("D:/outData.txt");

// Stream write to console.
OutputStream w=System.out;
HelloInputStream.java
package org.o7planning.tutorial.javaio.stream;

import java.io.FileInputStream;
import java.io.InputStream;

public class HelloInputStream {

    public static void main(String[] args) {
        try {
       
            // Create InputStream object from subclass.
            // This is Stream read file.
            InputStream is = new FileInputStream("data.txt");

            int i = -1;
           
            // Read the turn of bytes in the stream.
            // Each time the 8-bit read, convert it to int.
            // Read the value of -1 means the end of the stream.
            while ((i = is.read()) != -1) {
                System.out.println(i + "  " + (char) i);
            }
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
Результат:
HelloOutputStream.java
package org.o7planning.tutorial.javaio.stream;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class HelloOutputStream {

   public static void main(String[] args) {
       try {
           File dir = new File("C:/Test");

           // Create directories if not exists
           dir.mkdirs();

           // Create output Stream write data to file.
           OutputStream w = new FileOutputStream(
                   "C:/Test/test_outputStream.txt");
           
           // Create array of bytes, write it to stream.
           byte[] by = new byte[] { 'H', 'e', 'l', 'l', 'o' };

           // write turn the bytes into the stream
           for (int i = 0; i < by.length; i++) {
               byte b = by[i];

               // Write 1 byte.
               w.write(b);
           }
           // Close the output stream, finish write file.
           w.close();
       } catch (Exception e) {
           e.printStackTrace();
       }
   }
}
Результат:
2 Примера выше являются простыми, они читают или записывают каждый byte, в следующем примере мы прочитаем или запишем одновременно много byte, это ускоряет обработку.
InputStreamExample2.java
package org.o7planning.tutorial.javaio.stream;

import java.io.FileInputStream;
import java.io.InputStream;

public class InputStreamExample2 {

    public static void main(String[] args) {
        try {

            // Create input stream, read a file.
            InputStream in = new FileInputStream("data.txt");

            // A temporary array to store data each reading
            byte[] temp = new byte[10];
            int i = -1;

           
            // Reads some number of bytes from the input stream
            // and stores them into the buffer array 'temp'.
            // Return the number of bytes actually read.
            // return -1 if end of stream.
            while ((i = in.read(temp)) != -1) {

                // Create String from bytes
                String s = new String(temp, 0, i);
                System.out.println(s);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Это иллюстрации одновременного чтения примера выше:
OutputStreamExample2.java
package org.o7planning.tutorial.javaio.stream;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class OutputStreamExample2 {

    public static void main(String[] args) {
        try {
            File dir = new File("C:/Test");

            // Create directories if not exists.
            dir.mkdirs();            
            
            // Create output Stream to write file.
            OutputStream os = new FileOutputStream("C:/Test/test_writerOutputStream.txt");
            
            // Create array of bytes, write bytes into the file above.
            byte[] by = new byte[] { 'H', 'e', 'l', 'l', 'o', ' ', 31, 34, 92 };
            byte[] by2 = new byte[] { 'H', 'e', 'l', 'l', 'o', ' ', 'b', 'o',
                    'y' };
            
            // Write all of bytes in array into Stream.
            os.write(by);
            
            // Flush data in memory to file.
            os.flush();
            
            // Continue write the 2nd byte array to the stream
            os.write(by2);
            
            // Close the output stream, finish write file.
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3. Class ByteArrayInputStream & ByteArrayOutputStream

ByteArrayInputStream покрывает массив byte (byte[] buf) и через ByteArrayInputStream имеет доступ к элементам массива.
ByteArrayOutputStream это поток byte, внутри этого объекта содержится массив byte (byte[] buf) имеющие способность самоувеличиваться в размере когда количество byte потока увеличивается. Каждый раз, при записи потока в byte этот byte прикрепляется в позицию массива..
  • Когда массив заполняется элементами, то программа создает новый массив, имеющий большую длину и копирует элементы старого массива ...(Это способ самоувеличения массива как было упомянуто выше)
Некоторые методы ByteArrayOutputStream:
// return the current contents of this output stream, as a byte array.
  - byte[] toByteArray();

// String decoded from the buffer's contents.
  - String toString() ;

// return the number of valid bytes in this output stream.
  - int size();
ByteArrayInputStreamExample.java
package org.o7planning.tutorial.javaio.bytestream;

import java.io.ByteArrayInputStream;
import java.io.IOException;

public class ByteArrayInputStreamExample {

    public static void main(String args[]) throws IOException {

        // Byte Array.
        byte[] bytes = new byte[] { 'H', 'e', 'l', 'l', 'o', ' ', 'I', 'O' };

        // Using ByteArrayInputStream to read bytes array.
        ByteArrayInputStream bInput = new ByteArrayInputStream(bytes);

        System.out.println("Converting characters to Upper case ");
        int c = 0;

        // Read the turn of bytes in the stream.
        // Cursor will move from the beginning to the end of the array array.
        // Every time you read a byte pointer will move one step to the end.        
        while ((c = bInput.read()) != -1) {
            char ch = (char) c;
            ch = Character.toUpperCase(ch);
            System.out.println(ch);
        }

        // Check whether this stream supports mark or not
        boolean markSupport = bInput.markSupported();

        System.out.println("Mark Support? " + markSupport);
       
        // Move the cursor to the default location
        // In this example, it will move to position 0 ..        
        bInput.reset();

        char ch = (char) bInput.read();
        System.out.println(ch);

         // Read next byte
        ch = (char) bInput.read();
        System.out.println(ch);

        System.out.println("Skip 4");
 
        // Skip 4 bytes
        bInput.skip(4);
        ch = (char) bInput.read();
        System.out.println(ch);

    }

}
Результат:
ByteArrayOutputStreamExample.java
package org.o7planning.tutorial.javaio.bytestream;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ByteArrayOutputStreamExample {

    public static void main(String args[]) throws IOException {


        // Create ByteArrayOutputStream object.
        // Object contains within it an array of bytes.
        // Array with size 12 elements.
        // If the number of elements to write to stream more than 12, the array will be replaced by
        // new array has more elements, and copy the elements of old array into.        
        ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12);

        String s = "Hello ByteArrayOutputStream";

        for (int i = 0; i < s.length(); i++) {

            char ch = s.charAt(i);

            if (ch != 'a' && ch != 'e') {
                bOutput.write(ch);
            }
        }

        // Returns the current size of the buffer.
        int size = bOutput.size();
        System.out.println("Size = " + size);

        byte[] bytes = bOutput.toByteArray();

        String ss = new String(bytes);

        System.out.println("New String = " + ss);
    }
}
Результат:

4. Class ObjectInputStream & ObjectOutputStream

ObjectInputStream, ObjectOutputStream позволяет вам читать или записывать Object в поток. Эти Object должны быть вида Serializable (То есть могут быть расставлены в очереди).
Далее, некоторые примеры class-ов:
Student.java
package org.o7planning.tutorial.javaio.objstream;

import java.io.Serializable;

public class Student implements Serializable {

   private static final long serialVersionUID = -5074534753977873204L;

   private String firstName;

   private String lastName;

   public Student(String firstName, String lastName) {
       this.firstName = firstName;
       this.lastName = lastName;
   }

   public String getFirstName() {
       return firstName;
   }

   public void setFirstName(String firstName) {
       this.firstName = firstName;
   }

   public String getLastName() {
       return lastName;
   }

   public void setLastName(String lastName) {
       this.lastName = lastName;
   }

}
Pupil.java
package org.o7planning.tutorial.javaio.objstream;

import java.io.Serializable;

public class Pupil implements Serializable {
 
   private static final long serialVersionUID = -8501383434011302991L;
   
   private String fullName;

   public Pupil(String fullName)  {
       this.fullName= fullName;
   }
   
   public String getFullName() {
       return fullName;
   }

   public void setFullName(String fullName) {
       this.fullName = fullName;
   }

}
ObjectOutputStreamExample.java
package org.o7planning.tutorial.javaio.objstream;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;

public class ObjectOutputStreamExample {

    public static void main(String[] args) throws IOException {
        File dir = new File("C:/Test");

        // Create directories if not exists.
        dir.mkdirs();


        // Create stream write to file.
        FileOutputStream fos = new FileOutputStream(
                "C:/Test/testObjectStream.txt");

       
        // Create ObjectOutputStream object wrap 'fos'.
        // Data written to this stream will be pushed to 'fos'.
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        
        
        // Write String to Stream.
        oos.writeUTF("This is student, pupil profiles");
    
  
        // Note: Write Serializable object only.
        // Write an Object to stream.
        oos.writeObject(new Date());

        Student student1 = new Student("Thanh", "Phan");
        Student student2 = new Student("Ngan", "Tran");
        Pupil pupil1 = new Pupil("Nguyen Van Ba");

        oos.writeObject(student1);
        oos.writeObject(pupil1);
        oos.writeObject(student2);

        oos.close();
        System.out.println("Write successful");
    }

}
Результаты запуска:
Это иллюстрацию записи Object в файл, запись делается по очереди. После, при чтении, вы должны вспомнить очередности записи, чтобы вы могли ее прочитать правильно.
И пример сi ObjectInputStream читает файл только что записанный в примере выше:
ObjectInputStreamExample.java
package org.o7planning.tutorial.javaio.objstream;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Date;

public class ObjectInputStreamExample {

    public static void main(String[] args) throws IOException,
            ClassNotFoundException {

        // Create stream to read file.
        FileInputStream fis = new FileInputStream(
                "C:/Test/testObjectStream.txt");

        // Create ObjectInputStream object wrap 'fis'.
        ObjectInputStream ois = new ObjectInputStream(fis);

        // Read String.
        String s = ois.readUTF();

        System.out.println(s);

        // Read Object.
        Date date = (Date) ois.readObject();
        System.out.println("Date = " + date);

        Student student1 = (Student) ois.readObject();

        System.out.println("Student " + student1.getFirstName());

        Pupil pupil = (Pupil) ois.readObject();

        System.out.println("Pupil " + pupil.getFullName());

        Student student2 = (Student) ois.readObject();

        System.out.println("Student " + student2.getFirstName());

        ois.close();
    }
}
Результат:

5. Class DataInputStream & DataOutputStream

DataOutputStream **
// Constructor
public DataOutputStream(OutputStream out)

// Write a character 16 bit (2-byte)
public void writeChar(int val)
// Write double 64 bit (8-byte)
public void writeDouble(double val)
// Write float 32 bit (4-byte)
public void writeFloat(float val)
// Write integer 32 bit (4-byte)
public void writeInt(int val)
// Write String UTF-8.
public void writeUTF(String obj)
....
DataInputStream **
// Constructor
public DataInputStream(InputStream in)

// Read a character 16 bit (2 byte)
public char readChar()
// Read double 64 bit (8 byte)
public double readDouble()
// Read float 32 bit (4 byte)
public float readFloat()
// Read int 16 bit (4 byte)
public int readInt()
// Read UTF-8 String.
public String readUTF()
....
DataOutputStreamExample.java
package org.o7planning.tutorial.javaio.datastream;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class DataOutputStreamExample {

    public static void main(String[] args) throws IOException {
        int cityIdA = 1;
        String cityNameA = "Green Lake City";
        int cityPopulationA = 500000;
        float cityTempA = 15.50f;

        int cityIdB = 2;
        String cityNameB = "Salt Lake City";
        int cityPopulationB = 250000;
        float cityTempB = 10.45f;

        File dir = new File("C:/Test");
        dir.mkdirs();

        //
        // Create FileOutputStream write to file.
        //
        FileOutputStream fos = new FileOutputStream("C:/Test/cities.txt");

        // Create DataOutputStream object wrap 'fos'.
        // The data write to 'dos' will be pushed to 'fos'.
        DataOutputStream dos = new DataOutputStream(fos);

        //
        // Write data.
        //
        dos.writeInt(cityIdA);
        dos.writeUTF(cityNameA);
        dos.writeInt(cityPopulationA);
        dos.writeFloat(cityTempA);

        dos.writeInt(cityIdB);
        dos.writeUTF(cityNameB);
        dos.writeInt(cityPopulationB);
        dos.writeFloat(cityTempB);

        dos.flush();
        dos.close();
    }

}
Запустить class DataOutputStreamExample и получить записанный файл данных.
DataInputStreamExample.java
package org.o7planning.tutorial.javaio.datastream;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class DataInputStreamExample {
    
    
    
    public static void main(String[] args) throws IOException {
        
         // Stream to read file.
         FileInputStream fis = new FileInputStream("C:/Test/cities.txt");

         // Create DataInputStream object wrap 'fis'.
         DataInputStream dis = new DataInputStream(fis);

         //
         // Read data.
         //
         int cityId1 = dis.readInt();
         System.out.println("Id: " + cityId1);
         String cityName1 = dis.readUTF();
         System.out.println("Name: " + cityName1);
         int cityPopulation1 = dis.readInt();
         System.out.println("Population: " + cityPopulation1);
         float cityTemperature1 = dis.readFloat();
         System.out.println("Temperature: " + cityTemperature1);

         //
         // Read data.
         //
         int cityId2 = dis.readInt();
         System.out.println("Id: " + cityId2);
         String cityName2 = dis.readUTF();
         System.out.println("Name: " + cityName2);
         int cityPopulation2 = dis.readInt();
         System.out.println("Population: " + cityPopulation2);
         float cityTemperature2 = dis.readFloat();
         System.out.println("Temperature: " + cityTemperature2);
         
         dis.close();
    }
}
Результаты:

6. Dẫy luồng đầu vào nhị phân - SequenceInputStream

Сейчас вы знакомы с чтением определенного файла и получением входного потока. Но на самом деле, иногда вам нужно прочитать много файлов и соединить полученные данные друг с другом, чтобы записать в другой файл например. То есть соединить разные входные потоки друг с другом для создания большого потока в тандеме. Мы говорим про class java.io.SequenceInputStream. Это понятие не соответствует с выходным потоком...
// Constructor

 // Create new Stream from Pairing two streams together
// which will be read in order
public SequenceInputStream(InputStream s1,InputStream s2)  
 
// Create new Stream from Multi input stream.
// which will be read in order
  public SequenceInputStream(Enumeration<? extends InputStream> e)
Пример:
// Input stream read a file - File1.txt .
InputStream is1=new FileInputStream("File1.txt");
// Input stram read a file - File2.txt  
InputStream is2=new FileInputStream("File2.txt");

// Create new Stream from two stream
SequenceInputStream sis=new SequenceInputStream(is1,is2);

7. Luồng dữ liệu đường ngầm nhị phân (PipedInputStream,PipedOutputStream)

Представим, что у вас есть 2 потока: входной и выходной ...Например входной поток данных А читает файл, берет информацию из данного потока и записывает в В, выходной поток данных которого является другой файл ...Два потока А и В в данном случае отличаются... Поэтому в приложении у вас должно быть 3 действия:
  • Создать поток чтения файла A
  • Создать поток записи файла B
  • Читать из A записывать в B ...
Первые два действи обязательны, но если вы хотите избавиться от 3-го действия ...значит нужно создать неявное соединение между 2-мя потоками (входной - выходной), чтобы появившиеся byte при чтении A сразу были записаны в B.... Это называется неявное соединения между входным и выходным потоком..
PipeStreamExample1.java
package org.o7planning.tutorial.javaio.pipestream;

import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class PipeStreamExample1 {

	private InputStream pipedInputStream;

	public static void main(String[] args) throws IOException, InterruptedException {
		new PipeStreamExample1().test();
	}

	private void test() throws IOException, InterruptedException {
		// Создать 'pipedOutputStream',
		PipedOutputStream pipedOutputStream = new PipedOutputStream();

		// Данные записанные в 'pipedOutputStream'
		// автоматически появятся в 'pipedInputStream'.
		pipedInputStream = new PipedInputStream(pipedOutputStream);

		new ThreadRead().start();

		char[] chs = new char[] { 'a', 'a', 'b', 'c' , 'e' };

		// Данные записанные в 'pipedOutputStream'.
		for (char ch : chs) {
			pipedOutputStream.write(ch);
			Thread.sleep(1000);
		}
		pipedOutputStream.close();
	}

	// Thread для чтения данных появился на 'pipedInputStream'.
	class ThreadRead extends Thread {

		@Override
		public void run() {
			try {
				int data = 0;
				while ((data = pipedInputStream.read()) != -1) {
					System.out.println((char) data);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				closeQuietly(pipedInputStream);
			}
		}
	}

	private void closeQuietly(InputStream is) {
		if (is != null) {
			try {
				is.close();
			} catch (IOException e) {
			}
		}
	}

}

8. Class PrintStream


// PrintStream is the subclass of FilterOutputStream.
// It can wrap a binary output stream (OutputStream) , ..
// Constructor :

   // Wrap a OutputStream
   public PrintStream(OutputStream out)

   public PrintStream(OutputStream out,boolean autoFlush)

   // Write to file ..
   public PrintStream(String fileName)
 

// Some methods
   public void println(String s)
   public void print(char ch)

   // Write an Object
   public void print(Object obj)

   // Write long value (64bit)
   public void print(long n)

   public PrintStream append(java.lang.CharSequence csq) .
   // ... (more see javadoc)
Вы уже знакомы с уловкой исключений Exception через try, catch.
try {    
 // Do something here
 // Error divided by 0
 int i=10/0;
}
// The catch block is executed
catch(Exception e) {  
 // Print out message
 System.out.println("Error on try..."+e.getMessage());
 // Print 'stack trace' to Console.
 // How to get the text "stack trace"?
 e.printStackTrace();
}
Это 'Stack Trace' который вы часто видите при определенной ошибке.
Следующий пример получает "Stack Trace"
GetStackTraceString.java
package org.o7planning.tutorial.javaio.printstream;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

public class GetStackTraceString {

  private static String getStackTraceString(Exception e) {
 
      // Create ByteArrayOutputStream
      ByteArrayOutputStream baos = new ByteArrayOutputStream();


      // Data written to this stream will be pushed to 'baos'.
      PrintStream printStream = new PrintStream(baos);


      // Prints this throwable and its backtrace to 'printStream'
      e.printStackTrace(printStream);

      printStream.close();
     
      byte[] bytes = baos.toByteArray();

      String s = new String(bytes);
      return s;
  }

  public static void main(String[] args) {

      try {
          // Do something here
          // Error divided by 0
          int i = 10 / 0;
      }
      // The catch block is executed
      catch (Exception e) {
          // Print out message
          System.out.println("Error on try..." + e.getMessage());

          // Get the text "stack trace"
          String s = getStackTraceString(e);

          System.out.println("Stack Trace String " + s);
      }
  }
}
Код ниже записывает информацию поиска ошибки в экран Console, но использует метод printStackTrace(PrintStream ps) в Exception вместо метода printStackTrace(), который используется по умолчанию для записи поиска ошибки в Console.
// PrintStream to write to the Console
PrintStream os = System.out;
// Exception e ..
// Write 'stack trace' to 'os'. This means print to the Console.
e.printStackTrace(os);

// In essence it is equivalent to calling:
e.printStackTrace();

Руководства Java IO

Show More