Java类库中的I/O类分成输入和输出两个部分。通过继承,任何自InputStream或Reader派生而来的类都含有名为read()的基本方法,用于读取单个字节或者字节数组。同样,任何自OutputStream或Writer派生而来的类都含有名为write()的基本方法,用于写单个字节或字节数组。
下面介绍三种继承自InputStream的子类:
一、FileInputStream、FileOutputStream
FileInputStream,用于从文件中读取信息。FileOutputStream, 用于将信息写至文件。
具体代码实现如下:
public class InputStream1 { public static void main(String[] args) { String fileName = "D:"+File.separator+"file.txt"; File file = new File(fileName); if(!file.exists()){ try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } //FileOutputStream、FileInputStream文件操作流 try { OutputStream os = new FileOutputStream(file); String str = "大家好!"; byte[] a = str.getBytes(); os.write(a); os.close(); InputStream in = new FileInputStream(file); byte[] b = new byte[(int) file.length()]; in.read(b); in.close(); System.out.println(new String(b)); } catch (Exception e) { e.printStackTrace(); } } }
二、ByteArrayInputStream、ByteArrayOutputStream
ByteArrayInputStream允许将内存的缓存区当作InputStream使用。 ByteArrayInputStream在内存中创建缓冲区,所有送往"流"的数据都要放置在此缓冲区。
具体代码实现如下:
//ByteArrayInputStream、ByteArrayOutputStream try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); int a = 0; int b = 1; int c = 2; bos.write(a); bos.write(b); bos.write(c); //获取内存缓冲中的数据 byte[] buf = bos.toByteArray(); bos.close(); ByteArrayInputStream bin = new ByteArrayInputStream(buf); int data = 0; while((data=bin.read())!=-1){ System.out.println(data); } bin.close(); } catch (IOException e) { e.printStackTrace(); }
三、PipedInputStream、PipedOutputStream
PipedInputStream产生用于写入相关PipedOutputStream的数据,实现"管道化"概念。 PipedOutputStream任何写入其中的信息都会自动作为相关PipedInputStream的输出。实现"管道化"概念。
具体代码实现如下:
//PipedInputStream、PipedOutputStream Sender sender = new Sender(); Receiver receiver = new Receiver(); PipedOutputStream outStream = sender.getOutStream(); PipedInputStream inStream = receiver.getInStream(); try { //使用connection()方法将其相连。 outStream.connect(inStream); } catch (Exception e1) { e1.printStackTrace(); } sender.start(); receiver.start(); } } class Sender extends Thread{ private PipedOutputStream outStream = new PipedOutputStream(); public PipedOutputStream getOutStream() { return outStream; } public void run() { String info = "hello world!"; try { outStream.write(info.getBytes()); outStream.close(); } catch (Exception e) { e.printStackTrace(); } } } class Receiver extends Thread { private PipedInputStream inStream = new PipedInputStream(); public PipedInputStream getInStream() { return inStream; } public void run() { byte[] buf = new byte[1024]; try { inStream.read(buf); System.out.println("receive message from sender : " + new String(buf)); inStream.close(); } catch (Exception e) { e.printStackTrace(); } } }
时间: 2024-10-07 23:01:53