Java学习总结7-----Java IO

Java库的IO类分为输入与输出两个部分, 在1.0版本中提供了两个抽象基类, 所有输入的类都从InputStream继承, 所有输出的类都从OutputStream继承, 1.1提供了两个新的基类, 负责输入的Reader与输出的Writer, 但它们并不是用来替换原来老的InputStream与OutputStream, 它们主要是让Java能更好的支持国际化的需求。 原来老的IO流层只支持8位字节流, 不能很好地控制16位Unicode字符。 Java内含的char是16位的Unicode, 所以添加了Reader和Writer层次以提供对所有IO操作中的Unicode的支持。 除此之外新库也对速度进行了优化, 可比旧库更快地运行。

1.InputStream
java.lang.Object

extended by java.io.InputStream
                Direct Known Subclasses:
      AudioInputStream, ByteArrayInputStream, FileInputStream, FilterInputStream, InputStream, ObjectInputStream, PipedInputStream, SequenceInputStream, StringBufferInputStream
2.OutputStream
java.lang.Object
extended by
java.io.OutputStream
   Direct Known Subclasses:
ByteArrayOutputStream, FileOutputStream, FilterOutputStream, ObjectOutputStream, OutputStream, PipedOutputStream
3. Reader
java.lang.Object
extended by
java.io.Reader
  Direct Known Subclasses:
BufferedReader, CharArrayReader, FilterReader, InputStreamReader, PipedReader, StringReader
4.Writer
  java.lang.Object
  extended by java.io.Writer
  Direct Known Subclasses:
BufferedWriter, CharArrayWriter, FilterWriter, OutputStreamWriter, PipedWriter, PrintWriter, StringWriter
一、从控制台读取输入
//从控制台读取输入---按字符读取
public class BRRead {
public static void main(String[] args) throws IOException {
//throwOne();
BufferedReader BR = new BufferedReader(new InputStreamReader(System.in));
System.out.println(
"Input character:'q' to quit:");
char c;
do{
c
= (char)BR.read();
System.out.println(c);
}
while(c!='q');
}
}
//从控制台读取输入---按行读取
public class BRReadLine {
public static void main(String[] args) throws IOException {
//throwOne();
BufferedReader BR = new BufferedReader(new InputStreamReader(System.in));
String line
= new String();
System.out.println(
"Input lines: "+ " stop to quit:");
// char c;
do{
line
= BR.readLine();
System.out.println(line);
}
while(!line.equals("stop"));
}
}

二、文件的读写FileInputStream、FileOutputStream

public class FileStreamDemo {

	public static void main(String[] args) throws IOException {
	
		//创建两个文件,aa.txt是已经存在文件,aa2.txt是新创建的文件
		
		File inFile = new File("d:\\aa.txt");
		
		File outFile = new File("d:\\aa2.txt");
		
		//创建流文件读入与写出类
		
		FileInputStream inStream = new FileInputStream(inFile);
		
		FileOutputStream outStream = new FileOutputStream(outFile);
		
		//通过available方法取得流的最大字符数
		
		byte[] inOutb = new byte[inStream.available()];
		
		inStream.read(inOutb);  //读入流,保存在byte数组
		
		outStream.write(inOutb);  //写出流,保存在文件newFace.gif中
		
		inStream.close();
		
		outStream.close();
	
	}

} 


posted @ 2011-06-24 13:47  lxmanutd  阅读(428)  评论(0编辑  收藏  举报