Java IO Notes (一)

原文链接:http://tutorials.jenkov.com/java-io/index.html

  • Java NIO  It contains classes that does much of the same as the Java IO and Java     Networking APIs, but Java NIO can work in non-blocking mode.
  • outputstream
  • inputstream
  • pipes

    1. different threads
    2. same JVM 
    3. different from the pipe concept in Unix / Linux, where two processes running in different address spaces can communicate via a pipe
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class PipeExample {

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

        final PipedOutputStream output = new PipedOutputStream();
        final PipedInputStream  input  = new PipedInputStream(output);


        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    output.write("Hello world, pipe!".getBytes());
                } catch (IOException e) {
                }
            }
        });


        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    int data = input.read();
                    while(data != -1){
                        System.out.print((char) data);
                        data = input.read();
                    }
                } catch (IOException e) {
                }
            }
        });

        thread1.start();
        thread2.start();

    }
}
  • Warnning!!!  The read() and write() calls on the streams are blocking, meaning if you try to use the same thread to both read and write, this may result in the thread deadlocking itself.
  • There are many other ways than pipes that threads can communicate within the same JVM. In fact, threads more often exchange complete objects rather than raw byte data. But - if you need to exchange raw byte data between threads, Java IO's pipes are a possibility.

  • Networking

  • Basically this means that if you have code that is capable of writing something to a file, that same something could easily be written to a network connection. All that is required is that your component doing the writing depends on an OutputStream instead of a FileOutputStream. Since FileOutputStream is a subclass of OutputStream this should be no problem.
  • Java IO: Byte & Char Arrays

  • Reading Arrays via InputStream or Reader

byte[] bytes = new byte[1024];

//write data into byte array...

InputStream input = new ByteArrayInputStream(bytes);

//read first byte
int data = input.read();
while(data != -1) {
    //do something with data

    //read next byte
    data = input.read();
}
  • Writing to Arrays via OutputStream or Writer

ByteArrayOutputStream output = new ByteArrayOutputStream();

output.write("This text is converted to bytes".getBytes("UTF-8"));

byte[] bytes = output.toByteArray();

  CharArrayWriter   toCharArray   ----- the same

  • System.in

  • connected to keyboard input of console programs
  • System.out  

  • outputs the data you write to it to the console.
  • System.out

  • works like System.out except it is normally only used to output error texts.
try {
  InputStream input = new FileInputStream("c:\data\...");
  System.out.println("File opened...");

} catch (IOException e){
  System.err.println("File opening failed:");
  e.printStackTrace();
}
  • Exchanging System Streams

OutputStream output = new FileOutputStream("c:\data\system.out.txt");
PrintStream printOut = new PrintStream(output);

System.setOut(printOut);

Now all data written to System.out should be redirected into the file "c:\data\system.out.txt".

  • Reader And Writer

  • They are intended for reading and writing text. The InputStream and OutputStream are byte based
  • Reader

 Reader reader = new FileReader("c:\data\myfile.txt");

    int data = reader.read();
    while(data != -1){
        char dataChar = (char) data;
        data = reader.read();
    }
  • Combining Readers With InputStreams

  • If you have an InputStream and want to read characters from it, you can wrap it in an InputStreamReader.
Reader reader = new InputStreamReader(inputStream);
  • Write

Writer writer = new FileWriter("c:\data\file-output.txt");

writer.write("Hello World Writer");
writer.close();
原文地址:https://www.cnblogs.com/L-a-u-r-a/p/7080918.html