devstory

Tutoriel sur les flux binaires Java IO

  1. Vue d'ensemble de flux binaire (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. Vue d'ensemble de flux binaire (Binary Stream)

Le flux binaire est dirigé par deux classes InputStream et OutputStream. Dans ces deux classesil y a de nombreuses sous-classes. Quant à la balance de la force, la relation entre le flux binaire (Binary Stream) est plus complexe avec leur flux de caractères (charecter stream). Avec JDK1.5 en flux binaire il y a 2 classes qui sont recommandés de ne pas utiliser le LineNumberInputStream et StringBufferInputStream parce qu'ils étaient obsolètes.

2. Class InputStream & OutputStream

La class InputStream est une classe abstraite, donc vous ne pouvez pas initialiser l'objet InputStream via la classe InputStream par elle-même. Cependant, cette classe se divise en multiples branches à travers les sous-classes qui en héritent. Selon chaque situation précise, vous pouvez créer l'objet InputStream à partir des constituants des sous-classes.
// 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;
La class OutputStream est une classe abstraite donc vous ne pouvez pas créer OutputStream via la classe OutputStream par elle-même. Cependant cette classe se sépare en nombreuses branches à travers la classe héritée et de l'importance. Selon la situation, vous pouvez créer l'objet InputStream à partir des constituants des sous-classes
// 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();
        }
    }

}
Résultat :
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();
       }
   }
}
Résultat :
Deux exemples ci-dessus sont simples, ils lisent ou écrivent chaque octet (byte), dans l'exemple suivant nous allons lire ou écrire plusieurs octets en série (byte), Cela accélère le processus.
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();
        }
    }
}
Ceci est une illustration des lectures simultanées de l'exemple au-dessus
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 enveloppe un tableau d'octets (byte[] buf) et et à travers ByteArrayInputStream pour accéder l'élément du tableau.
ByteArrayOutputStream est un flux d'octets, dans lequel il contient un tableau d'octets (byte[] buf) qui peut augmenter la taille lui même lorsque le nombre d'octets du flux augmente. Chaque fois que les octets sont écrit dans le flux, cela signifie que ces byte ont été assigné au tableau qui n'a pas encore assigné ...
  • Lorsque l'élément de tableau est complet, le programme crée un nouveau tableau avec la longeur plus grande et copie les anciens éléments du tableau... (C'est la façon de faire croître le tableau de caractères commementionné au-dessus)
Quelques méthode de 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);

    }

}
Résultat :
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);
    }
}
Résultat :

4. Class ObjectInputStream & ObjectOutputStream

ObjectInputStream et ObjectOutputStream vous permet de lire ou d'écrire un objet dans le flux. Ceci est le type d'objet Serializable (c'est-à-dire aligner).
Voici quelques exemples de classe :
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");
    }

}
Les résultats d'exécution de l'exemple :
Il s'agit de l'image qui illustre l'enregistrement de l'Objet sur le fichier. Cet enregistrement est traité à son tour. Dans le future, lorsque vous lisez, vous devez vous rappeler également l'ordre qui a été enregistré avant de lire correctement.
Et ceci est un exemple de ObjectInputStream lorsqu'il lit le fichier comme mentionné dans l'exemple au-dessus :
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();
    }
}
Résultat :

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();
    }

}
Exécutez la classe DataOutputStreamExample et recevez un fichier donné est enregistré.
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();
    }
}
Résultats :

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

Généralement, vous êtes familiarisé avec la lecture d'un fichier et l'obtention d'un flux d'entrée. Mais en réalité, vous devez parfois lire plusieurs fichiers et rassembler les données pour écrire un autre fichier, par exemple. C'es-à-dire vous rassemblez plusieurs flux d'entrée ensemble pour pour former un flux plus grand qui est composé de plusieurs flux petit en tandem. Nous parlons à la classe java.io.SequenceInputStream. Ce concept ne correspond pas au flux de sortie ...
// 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)
Exemple :
// 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)

Supposons que vous avez deux flux: d'un flux d'entrée et un flux de sortie ... Le flux d'entrée des données A lit un fichier et récupère les informations pour l'écriture sur le flux de données B dont la sortie est un autre fichier... Des deux flux A et B sont complètement différent dans ce cas ... Donc, dans l'application, vous devez effectuer 3 actions :
  • Créer le flux de lecture donnée A
  • Créer le flux d'écriture donnée B
  • Lecture des données de A à éciture sur B ...
Les deux premières actions sont obligatoires mais si vous voulez supprimer la troisième action ... Cela signifie que nous devons créer une connexion implicite entre le flux d’entrée et le flux de sortie, de sorte qu’une fois que les données apparaissent sur la tête de lecture A, elles puissent être reconnues et lues par le flux de sortie B ... C’est ce qu’on appelle une connexion canalisée entre le thread d'entrée et le thread de sortie.
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 {
		// Créer un 'pipedOutputStream',
		PipedOutputStream pipedOutputStream = new PipedOutputStream();

		// Des données sont écrites dans 'pipedOutputStream'
		// apparaîtra automatiquement sur 'pipedInputStream'.
		pipedInputStream = new PipedInputStream(pipedOutputStream);

		new ThreadRead().start();

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

		// Écrire des données dans 'pipedOutputStream'.
		for (char ch : chs) {
			pipedOutputStream.write(ch);
			Thread.sleep(1000);
		}
		pipedOutputStream.close();
	}

	// Un Thread lit les données qui apparaissent sur '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)
Vous savez déjà comment attraper des exceptions par le bloc 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();
}
C'est le 'Stack Trace' que vous voyez souvent quand quelque erreur se produisent.
L'exemple suivant récupère de "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);
      }
  }
}
Le code ci-dessous imprime des informations de débogage 'stack trace' sur à l'écran de la Console mais en utilisant la méthode printStackTrace (PrintStream ps) au lieu d'utiliser la méthode de printStackTrace()qui est utilisée par défaut pour à imprimer la 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();

Tutoriels Java IO

Show More