Java输入输出流

Java输入输入流有的时候很难理解,特别是read,write,到底是数据从什么地方到什么地方呢。下面有个图标示了数据的方向: 下面的代码是以Java字符流中的CharArrayReader和CharArrayWriter为例的代码:
package com.javaBooks.sixth;
import java.io.CharArrayReader;
import java.io.IOException;

public class CharArrayReaderTest {
	public static void main(String[] args) throws IOException {
		String s = "BUAASEM108CHENDANGYANG";
		int length = s.length();
		char charArray[] = new char[length];
		s.getChars(0, length, charArray, 0);
		CharArrayReader inputChar1 = new CharArrayReader(charArray);
		CharArrayReader inputChar2 = new CharArrayReader(charArray, 0, 5);
		int i;
		System.out.println("inputChar1 is: ");
		while ((i = inputChar1.read()) != -1) {
			System.out.print((char) i);
		}
		System.out.println();
		System.out.println("inputChar2 is: ");
		while ((i = inputChar2.read()) != -1) {
			System.out.print((char) i);
		}
		System.out.println();
	}
}

package com.javaBooks.sixth;

import java.io.CharArrayWriter;
import java.io.IOException;

public class CharArrayWriterTest {
	public static void main(String[] args) throws IOException {
		CharArrayWriter charArrayWriter = new CharArrayWriter();
		String s = "BUAASEM108CHENDANGYANG";
		char buffer[] = new char[s.length()];
		s.getChars(0, s.length(), buffer, 0);
		charArrayWriter.write(buffer);
		System.out.println("String buffer ");
		System.out.println(charArrayWriter.toString());
		System.out.println("write to an array");
		char chars[] = charArrayWriter.toCharArray();
		for (int i = 0; i < chars.length; i++) {
			System.out.print(chars[i]);
		}
		System.out.println();
	}
}
posted @ 2011-03-29 16:49  坤坤同学  阅读(187)  评论(0编辑  收藏  举报