I/O基础

来源:互联网 发布:远程软件 编辑:程序博客网 时间:2024/05/11 22:38

1、java.io包中定义了多个流类型(类或抽象类)来实现输入、输出功能;可以从不同角度对其进行分类:
  (1)按数据流的方向不同可以分为输入流和输出流。
  (2)按处理数据单位不同可以分为字节流和字符流。
  (3)按照功能不同可以分为节点流和处理流。
2、J2SDK所提供的所有流类型位于包java.io内,都分别继承自以下四种抽象流类型:
    
                          字节流                            字符流
                    
输入流              InputStream                        Reader

输出流              OutputStream                       Writer


java中 字符是两字节,16位;中文就是占两个字节。

 

InputStream的基本方法

 

//读取一个字节并以整数的形式返回(0~255)
//如果返回-1已到输入流的末尾
int read()throws IOException

//读取一系列字节并存储到一个数组buffer
//返回实际读取的字节数,如果读取前已到输入流的末尾,返回-1
int read (byte[] buffer) throws IOException


//读取length个字节,并存储到一个字节数组buffer,从offset位置开始
//返回实际读取的字节数,如果读取前已到输入流的末尾,返回-1
int read(byte[] buffer,int offset,int length)throws Ecception


//关闭流释放内存资源
void close() throws IOException

//跳过n个字节不读,返回实际跳过的字节数
long skip(long n)throws IOException

 

 

OutputStream的基本方法
//向输出流中写入一个字节数据,该字节数据为参数b的低8位
void write (int b) throws IOException

//将一个字节类型的数组中的数据写入输出流
void write (byte [] b)throws IOException

//将一个字节类型的数组中的从指定位置(off)开始的len个字节写入到输出流
void write(byte[] b,int off,int len)throws IOException

//关闭流释放内存资源
void close() throws IOException

//将输出流中缓冲的数据全部写出到目的地
void flush()throws IOException

 

 

Read的基本方法

//读取一个字符并以整数的形式返回(0~255),如果返回-1已到输入流的末尾
int read()throws IOException

//读取一系列字符并存储到一个数组buffer,返回实际读取的字符数,如果读取前已到输入流的末尾返回-1
int read (char[] cbuf)throws IOException

int read(char[] cbuf,int offset,int length)throws IOException

void close()throws IOException

long skip(long n)throws IOException

 


Writer的基本方法
//向输出流中写入一个字符数据,该数据为参数b的低16位
void write(int c) throws IOException

//将一个字符类型的数组中的数据写入输出流
void write(char[] cbuf)throws IOException

//将一个字符类型的数组中的从指定位置(offset)开始的length个字符写入到输出流
void write(char[]cbuf,int offset,int length)throws IOException

//将一个字符串中的字符写入到输出流
void write(String str)throws IOException

//将一个字符串从offset开始的length个字符写入到输出流
void write(String str,int offset,int length)throws IOException

void close()

void flush();

 

 

 

3、节点流和处理流
  节点流可以从一个特定的数据源(节点)读写数据(如:文件,内存)。
  处理流是“连接”在已存在的流(节点流或处理流)之上,通过对数据的处理为程序提供更强大的读写功能。
 
  只能建文件不能建目录
 
4、  节点流分类:
 
     类型                              字符流                                字节流
 
  File(文件)                 FileReader                        FileInputStream
                                       FileWriter                           FileOutputStream
 
  Memory Array              CharArrayReader               ByteArrayInputStream
                                       CharArrayWriter                  ByteArrayOutputStream
                             
  Memory String               String Reader                           -
                                        String Writer                             -
                             
  Pipe(管道)                  PipedReader                        PipedInputStream
                                     PipedWriter                           PipedOutputStream
     
  字节流example:

package Test;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;public class TestFileInputStream {public static void main(String[] args) {FileInputStream in=null;try {in = new FileInputStream("D:\\Myeclipse\\workspace\\MyTest\\src\\Test\\TestFileInputStream.java");} catch (FileNotFoundException e) {// TODO Auto-generated catch blockSystem.out.println("找不到指定的文件!");System.exit(-1);e.printStackTrace();}int b=0;int num=0;try {while((b=in.read())!=-1){System.out.print((char)b);num++;}in.close();} catch (IOException e) {// TODO Auto-generated catch blockSystem.out.println("读取文件出错!");System.exit(-1);e.printStackTrace();}}}
package Test;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;public class TestFileOutputStream {public static void main(String[] args) {FileOutputStream out=null;FileInputStream in=null;try {in=new FileInputStream("D:\\Myeclipse\\workspace\\MyTest\\src\\Test\\TestFileOutputStream.java");out=new FileOutputStream("D:\\Myeclipse\\workspace\\MyTest\\src\\Test\\TFO.java");} catch (FileNotFoundException e) {// TODO Auto-generated catch blockSystem.out.println("找不到指定的文件!");System.exit(-1);e.printStackTrace();}int b=0;try {while((b=in.read())!=-1){out.write(b);}in.close();out.close();} catch (IOException e) {// TODO Auto-generated catch blockSystem.out.println("读取文件出错!");System.exit(-1);e.printStackTrace();}}}


字符流example:

package Test;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;public class TestReader {public static void main(String[] args) {FileReader fr=null;try {fr=new FileReader("D:\\Myeclipse\\workspace\\MyTest\\src\\Test\\TestReader.java");} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();System.out.println("找不到指定的文件!");System.exit(-1);}int b=0;try {while((b=fr.read())!=-1){System.out.print((char)b);}fr.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();System.out.println("读取文件出错!");System.exit(-1);}}}
package Test;import java.io.FileWriter;import java.io.IOException;public class TestWriter {public static void main(String[] args) {FileWriter fw=null;try {fw=new FileWriter("D:\\Myeclipse\\workspace\\MyTest\\src\\Test\\TW.java");} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}try {for(int c=0;c<50000;c++){fw.write(c);}fw.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}





 

5、处理流分类:
6、缓冲流
  (1)输入缓冲流支持其父类的mark和reset方法
  (2)
BufferedReader提供了readLine方法用于读取一行字符串(以\r或\n分割) 

public String readLine()                throws IOException


  (3)BufferedWriter提供了newLine用于写入一个行分割符
  (4)对于输出的缓冲流,写出的数据会现在内存中缓存,使用flush方法将会使内存中的数据立刻写出。

 

 

   BufferedReader(Reader in)
  BufferedReader(Reader in,int sz)  //sz为自定义缓存区的大小
  BufferedWriter(Writer out)
  BufferedReader(Reader in,int sz)
  BufferedInputStream(InputStream in )
  BufferedInputStream(InputStream in ,int sz)
  BUfferedOutputStream(OutputStream out)
  BUfferedOutputStream(OutputStream out,int sz)

 

缓冲流example

import java.io.*;

public class TestBufferStream{ public static void main(String[] args){  try{    FileInputStream in=new FileInputStream("F:\\JavaTest\\IO\\TestBufferStream.java");  BufferedInputStream bis=new BufferedInputStream(in);  int b=0;  System.out.println((char)bis.read());  System.out.println((char)bis.read());  bis.mark(100);  for(int i=0;i<10;i++){   System.out.print((char)bis.read());   }   System.out.println();      bis.reset();   for(int i=0;i<10;i++){   System.out.print((char)bis.read());   }    bis.close(); }catch(IOException e){  System.out.println("出错啦!");  System.exit(-1);  }   }}

 

 

 

注意:

mark就像书签一样,在这个BufferedReader对应的buffer里作个标记,以后再调用reset时就可以再回到这个mark过的地方。mark方法有个参数,通过这个整型参数,你告诉系统,希望在读出这么多个字符之前,这个mark保持有效。读过这么多字符之后,系统可以使mark不再有效,而你不能觉得奇怪或怪罪它。这跟buffer有关,如果你需要很长的距离,那么系统就必须分配很大的buffer来保持你的mark。          //eg.          //reader       is       a       BufferedReader                 reader.mark(50);//要求在50个字符之内,这个mark应该保持有效,系统会保证buffer至少可以存储50个字符          int       a       =       reader.read();//读了一个字符          int       b       =       reader.read();//又读了一个字符                 //做了某些处理,发现需要再读一次          reader.reset();          reader.read();//读到的字符和a相同          reader.read();//读到的字符和b相同

 

 

 

 
 
 
 
package Test;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;public class TestBufferStream2 {public static void main(String[] args) {BufferedWriter bw=null;BufferedReader br=null;FileWriter fw=null;try {fw=new FileWriter("D:\\Myeclipse\\workspace\\MyTest\\src\\Test\\TBF.java");br=new BufferedReader(new FileReader("D:\\Myeclipse\\workspace\\MyTest\\src\\Test\\TBF.java"));bw=new BufferedWriter(fw);String s=null;for(int i=0;i<100;i++){s=String.valueOf(Math.random());bw.write(s);bw.newLine();  //}bw.flush();   //while((s=br.readLine())!=null){                    //System.out.println(s);}bw.close();br.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

 

  转换流
  (1)InputStreamReader和OutputStreamWriter用于字节数据到字符数据的转换
  (2)InputStreamReader需要和InInputStream“套接”。
  (3)OutputStreamWriter需要和OutputStream“套接”。
  (4)转换流在构造时可以指定其编码集合,例如:InputStream isr=new InputStreamReader(System.in,"ISO8859_1")
  使用转换流后,对于写入,原本是一个字节一个字节地写入,现在可以直接写入一个字符串
  ISO8859_1是西欧语言编码,也称latin-1

 

转换流example

package Test;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStreamWriter;public class TestTransFormal1 {public static void main(String[] args) {OutputStreamWriter osw;try {osw = new OutputStreamWriter(new FileOutputStream("D:\\Myeclipse\\workspace\\MyTest\\src\\Test\\TTF1.java"));osw.write("asdfghjkl");System.out.println(osw.getEncoding());osw.close();osw = new OutputStreamWriter(new FileOutputStream("D:\\Myeclipse\\workspace\\MyTest\\src\\Test\\TTF1.java",true), "ISO8859-1");//   这里的true,使第二次写入接在原有的信息后面接着写,不加true,则擦除原有的内容重新写入新内容!osw.write("asdfghjkl");System.out.println(osw.getEncoding());osw.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}


 

package Test;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;public class TestTransForml2 {public static void main(String[] args) {try {InputStreamReader isr = new InputStreamReader(System.in);                      //BufferedReader br = new BufferedReader(isr);String s = null;s = br.readLine();while (s != null) {if (s.equalsIgnoreCase("exit"))break;System.out.println(s.toUpperCase());s = br.readLine();}br.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}


  数据流  DataOutputStream和ByteArrayOutputStream
  int占4个字节,long占8个字节
  float占4个字节,double占8个字节
  bool类型占1个字节

 

 

public class ByteArrayOutputStreamextends OutputStream
This class implements an output stream in which the data is written into a byte array. The buffer automatically grows as data is written to it. The data can be retrieved usingtoByteArray() and toString().

Closing a ByteArrayOutputStream has no effect. The methods in this class can be called after the stream has been closed without generating an IOException.

 

 

 

Constructor and DescriptionByteArrayOutputStream()
Creates a new byte array output stream.
ByteArrayOutputStream(int size)
Creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.

 

 

 

toByteArray

public byte[] toByteArray()
Creates a newly allocated byte array. Its size is the current size of this output stream and the valid contents of the buffer have been copied into it.
Returns:
the current contents of this output stream, as a byte array.
See Also:
size()

 

 

数据流example
 

package Test;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;public class TestDataStream {public static void main(String[] args) {try {ByteArrayOutputStream bos = new ByteArrayOutputStream();               //DataOutputStream dos = new DataOutputStream(bos);dos.writeDouble(Math.random());dos.writeBoolean(true);ByteArrayInputStream bais = new ByteArrayInputStream(bos.toByteArray());                                //System.out.println(bais.available());                              //DataInputStream dis = new DataInputStream(bais);System.out.println(dis.readDouble());System.out.println(dis.readBoolean());dos.close();dis.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}


 

  
  PrintWriter和PrintStream都属于输出流,分别针对字符和字节
  PrintWriter和PrintStream提供了重载的print
  PrintWriter和PrintStream的输出操作不会 抛出异常,用户通过检测错误状态获取错误信息
  PrintWriter和PrintStream有自动flush功能

 

 

import java.io.*;public class TestPrintStream1{public static void main(String[] args){try{FileOutputStream fis=new FileOutputStream("F:\\JavaTest\\IO\\TestPrintStream1Log.txt");PrintStream ps=new PrintStream(fis);System.setOut(ps);int ln=0;for(char i=0;i<50000;i++){System.out.print(i);if(ln++==100){System.out.println();ln=0;}}}catch(IOException e){System.out.println("出错啦!");System.exit(-1);}}}


 

 

import java.io.*;public class TestPrintStream2{public static void main(String[] args ){try{InputStreamReader  isr=new InputStreamReader(System.in);BufferedReader br=new BufferedReader(isr);FileWriter fos=new FileWriter("F:\\JavaTest\\IO\\TestPrintStream2Log.txt",true);PrintWriter ps=new PrintWriter(fos);String s=null;while((s=br.readLine())!=null){if(s.equals("exit"))break;System.out.println(s.toUpperCase());ps.println(s.toUpperCase());ps.flush();}br.close();ps.close();}catch(IOException e){System.out.println("出错啦!");System.exit(-1);}}}


 

 

import java.io.*;public class TestPrintStream3{public static void main(String []args){String fileName=args[0];if(fileName!=null)list(fileName,System.out);}public static void list(String f,PrintStream fs){try{BufferedReader br=new BufferedReader(new FileReader(f));String s=null;while((s=br.readLine())!=null){fs.println(s);}br.close();}catch(IOException e){System.out.println("出错啦!");System.exit(-1);}}}
 
 
javac TestPrintStream3.java
java TestPrintStream3  TestPrintStream3.java
 
 
 


 

 

原创粉丝点击