1. 抽象类InputStream\OutputStream
方法read(), write(), close()
流结束的判断方法 read()的返回值为-1, readLine()返回值为null
2. 文件读写类FileInputStrea\FileOutputStream
方法: read()方法将文件读入一个byte类型的数组,其数组长度可以由in.avalialbe()方法获得
read(byte[], int off, int len) off指从流中读入的字节所放入数组中的开始数字, len指读入长度
write(byte[], int off, int len) off指定数组的起始位置,从该位置起的字节写入流中,len指写入长度
byte数组的最大长度为60M,如超出则需要将文件分段
package example; import java.io.*; public class IOTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub File inFile = new File("C:\\test\\1.jpg"); File outFile = new File("C:\\test\\2.jpg"); if(!outFile.exists()){ try{ outFile.createNewFile(); } catch(IOException ex){ ex.printStackTrace(); } } try{ FileInputStream in = new FileInputStream(inFile); byte[] array = new byte[in.available()]; in.read(array); FileOutputStream out = new FileOutputStream(outFile); out.write(array); in.close(); out.close(); } catch(FileNotFoundException ex){ ex.printStackTrace(); } catch(IOException ex){ ex.printStackTrace(); } } }3. 管道流PipedInputStream/PiledOutputStream
管道的建立有两种构造方式:
1) PipedInputStream pInput = new PipedInputStream();
PipedOutputStream pOutput = new PipedOutputStream();
2) PipedInputStream pInput = new PipedInputStream();
PipedOutputStream pOutput = new PipedOutputStream();
pInput.connect(pOutput);
package example; import java.io.*; public class PipeTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub PipedInputStream pipeIn = new PipedInputStream(); PipedOutputStream pipeOut = new PipedOutputStream(); try{ File f1 = new File("C:\\test\\1.txt"); File f2 = new File("C:\\test\\2.txt"); FileInputStream fileIn = new FileInputStream(f1); pipeOut.connect(pipeIn); Write writer = new Write(fileIn,pipeOut); writer.start(); //byte temp[] = new byte[pipeIn.available()]; InputStreamReader inReader = new InputStreamReader(pipeIn,"GBK"); BufferedReader reader = new BufferedReader(inReader); char temp[] = new char[10]; /* Read test 1 char temp[] = new char[20]; reader.read(temp); String s = new String(temp); System.out.println(temp); */ int c= reader.read(temp); while(c!=-1){ System.out.println(temp); c= reader.read(temp); } } catch(IOException ex){ ex.printStackTrace(); } } package example; import java.io.*; public class Write extends Thread{ FileInputStream fileIn; PipedOutputStream pipedOut; int c =0; public Write(FileInputStream fileIn,PipedOutputStream pipeOut){ this.fileIn = fileIn; this.pipedOut = pipeOut; } public void run(){ try{ for (int i = 0; i<25; i++){ c = fileIn.read(); pipedOut.write(c); } sleep(5000); for (int i = 0; i<10; i++){ c = fileIn.read(); pipedOut.write(c); } } catch(IOException ex){ ex.printStackTrace(); } catch(InterruptedException ex){ ex.printStackTrace(); } } } }在上面的代码中,遇到的问题是,写进程sleep一段时间之后再次写入的值无法被读进程读取