Java学习之输入输出流

3 篇文章 0 订阅
1 篇文章 0 订阅

“持志如心痛,一心在痛上,岂有功夫说闲话,管闲事  --摘自阳明先生语录”

Java中通过流来完成输入/输出,所有的输入/输出以流的形式处理,流可以理解为一个数据的序列。输入流表示从一个源读取数据,输出流表示向一个目标写数据。

Java 为 I/O 提供了强大的而灵活的支持,使其更广泛地应用到文件传输和网络编程中,操作I/O的类都被放在java.io包中。

根据流中的数据单位分为字节流和字符流。
        字节流:流中的数据是以8位字节为单位进行读写,以InputStream和OutputStream为基础类。
        字符流:流中的数据是以16为字符为单位进行读写,以Reader和Writer为基础类。

先看看字节流,InputStream和OutputStream是字节流的两个顶层父类,提供了输入流类和输出流类的通用API,这是我在网上找的关于字节流的层次结构图:

InputStream抽象类 

InputStream 为字节输入流,本身为一个抽象类,是所有字节输入流的父类,以字节为单位从数据源中读取数据,遇到错误时都会引发 IOException 异常,常用的子类有:

    FileInputStream把一个文件作为InputStream,实现对文件的读取操作     
  ByteArrayInputStream:把内存中的一个缓冲区作为InputStream使用 
    StringBufferInputStream:把一个String对象作为InputStream 
    PipedInputStream:实现了pipe的概念,主要在线程中使用 
    SequenceInputStream:把多个InputStream合并为一个InputStream

如果需要从一个文件读取数据,可以这样:

public static void main(String[] args) {
	try {
	    InputStream in = new FileInputStream("E:\\test.txt");
	    int  n=0; 
            StringBuffer sBuffer=new StringBuffer();
            //当n不等于-1,则代表未到末尾
            while (n!=-1){
               try {
            	   n=in.read();//读取文件的一个字节(8个二进制位),并将其由二进制转成十进制的整数返回
               } catch (IOException e) {
            	   e.printStackTrace();
               }
               char by=(char) n; //转成字符
               sBuffer.append(by);
            }
            System.out.println(sBuffer.toString());
	} catch (FileNotFoundException e) {
	    e.printStackTrace();
	}
}

使用FileInputStream读取文件时,若File类对象的所代表的文件不存在或者其他原因不能打开的话,则会抛出FileNotFoundException,下面为InputStream部分方法:

   (1)读取一个byte的数据,返回值是高位补0的int类型值。若返回值=-1说明没有读取到任何字节读取工作结束: int read()

   (2)读取b.length个字节的数据放到b数组中。返回值是读取的字节数。该方法实际上是调用下一个方法实现的 : read(byte b[ ])

   (3)从输入流中最多读取len个字节的数据,存放到偏移量为off的b数组中:read(byte b[ ], int off, int len)
   (4)在使用完后必须对打开的流进行关闭:void close()
   (5) 返回输入流中还有多少可读字节 int available()
   (6)跳过指定字节  long skip(long n)

OutputStream抽象类 

OutputStream为字节输出流,本身为一个抽象类,是所有字节输出流的父类,它以字节为单位将数据写入数据源,遇到错误时都会引发 IOException 异常,常用的子类有:

    FileOutputStream:实现对文件的写取操作 
    BufferedOutputStream:缓冲输出流
    PrintStream:打印输出流

还有其他的子类不一一列举了,如果要将数据写入到文件中,可以这样:

public static void main(String[] args) {
	try {
		OutputStream out = new FileOutputStream("E:\\test.txt");
		out.write( new String("This is test.txt").getBytes() );
	} catch (FileNotFoundException e) {
			e.printStackTrace();
	}catch (IOException e) {
		e.printStackTrace();
	}
}

这段代码执行后当文件不存在时,会自动创建一个文件,然后将内容写入文件中,如果文件润在将会覆盖文件的原内容。

注意:一定要在最后关闭流,如:

public static void main(String[] args) {
	OutputStream out = null;
	try {
		out = new FileOutputStream("E:\\test.txt");
		out.write( new String("This is test.txt").getBytes() );
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	}catch (IOException e) {
		e.printStackTrace();
	}finally{
		if(null != out){
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

将关闭流的操作放在finally块中可以保证不管是否出现异常都能执行关闭流的操作,OutputStream常用方法:

write(int b):一次写一个字节    b- 要写入的字节
write(byte[] b):一次写一个字节数组
write(byte[] b, int off,int len):一次写一部分字节数组
close():关闭此文件输出流并释放与此流有关的所有系统资源。此文件输出流不能再用于写入字节

再看看字符流,Reader和Writer是字符流的两个顶层父类,这是我在网上找的关于字符流的层次结构图:

Reader抽象类:

Reader抽象类是所有字符输入流的超类,它以字符为单位从数据源中读取数据,遇到错误时会引发 IOException 异常,常用的子类:

BufferedReader:字符缓冲输入流

InputStreamReader:字节流到字符流的桥接器

使用BufferedReader读取文件内容:

public static void main(String[] args) {
	try {
	    Reader reader = new BufferedReader(new FileReader("E:\\test.txt"));
	    int  n=0; 
	    StringBuffer sBuffer=new StringBuffer();
	    while (n!=-1){
           	n = reader.read();
                char by=(char) n;
                sBuffer.append(by);
            }
            System.out.println(sBuffer.toString());
	} catch (FileNotFoundException e) {
	    e.printStackTrace();
	}catch (IOException e) {
	    e.printStackTrace();
	}
}

当然你也可以直接使用BufferedReader的readLine来读取内容,该方法每次读取一行内容,如果读到返回null就表示文件结束了。

使用InputStreamReader读取:

public static void main(String[] args) {
	try {
	    InputStreamReader isr =new InputStreamReader(new FileInputStream("E:\\test.txt"), "GBK");
	    BufferedReader br = new BufferedReader(isr);
	    StringBuilder strb = new StringBuilder();
	    while (true) {
	        String line = br.readLine();
	        if (line == null) {
	             break;
	        }
	        strb.append(line);
	    }
	    System.out.println(strb);
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	}catch (IOException e) {
		e.printStackTrace();
	}
}

Writer抽象类:

Writer抽象类是所有字符输出流超类,它以字符为单位从数据写入数据源中,遇到错误时会引发 IOException 异常,常用的子类:

BufferedWriter:字符缓冲输出流

OutputStreamWriter:字符转换输出流

使用BufferedWriter输出:

public static void main(String[] args) throws Exception {
	   //创建一个字符缓冲输出流对象
	   BufferedWriter bw = new BufferedWriter(new FileWriter("E:\\test.txt")) ;
	   //写数据
	   bw.write("hello");
	   bw.write("world");
	   //刷新流
	   bw.flush();
	   //关闭资源
	   bw.close();
}

使用OutputStreamWriter输出:

public static void main(String[] args) throws Exception {
	//创建一个字符缓冲输出流对象
	OutputStreamWriter bw = new OutputStreamWriter(new FileOutputStream("E:\\test.txt")) ;
       //写数据
       bw.write("hello");
       bw.write("world");
       //刷新流
       bw.flush();
       //关闭资源
       bw.close();        
}

如果你觉得不错就分享出去

你也可以关注公众号,随时获取最新文章

PS:预计下月将在公众号做一波活动,可关注公众号回复暗号:“Java” 查看礼品~~

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值