从头认识java-16.3 IO的典型用法

来源:互联网 发布:sybase执行sql文件 编辑:程序博客网 时间:2024/06/06 16:40

解释:由于IO里面的InputStream,OutputStream这些api的用法比较简单,因此,暂时没有略过。

这一章节主要介绍一下IO的典型用法。

1.使用IO的时候推荐在外面包一层Buffer

package com.ray.ch16;import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io.FileInputStream;import java.io.FileReader;import java.io.IOException;public class Test {public static void main(String[] args) throws IOException {FileReader fileReader = new FileReader("d:\\fg.ini");//这里需要自己定义你想读取的文件BufferedReader bufferedReader = new BufferedReader(fileReader);String text = "";while ((text = bufferedReader.readLine()) != null) {System.out.println(text);}System.out.println("-------------------------------------");FileInputStream fis = new FileInputStream("d:\\fg.ini");BufferedInputStream bis = new BufferedInputStream(fis);byte b[] = new byte[1024];int len = 0;int temp = 0; // 所有读取的内容都使用temp接收while ((temp = bis.read()) != -1) { // 当没有读取完时,继续读取b[len] = (byte) temp;len++;}System.out.println(new String(b, 0, len));}}

上面的代码是两种读取某个文件内容的方法,分别通过FileInputStream和FileReader实现。

还有一点需要注意的是,在使用完这些InputStream的资源后,必须关闭,不然很容易引起内存溢出,我上面的代码就没有做好这一点。


2.使用DataInputStream格式化输入输出

package com.ray.ch16;import java.io.DataInputStream;import java.io.FileInputStream;import java.io.IOException;public class Test {public static void main(String[] args) throws IOException {DataInputStream dataInputStream = new DataInputStream(new FileInputStream("d:\\fg.ini"));while (dataInputStream.available() != 0) {System.out.println(dataInputStream.read());//System.out.println(dataInputStream.readDouble());//System.out.println(dataInputStream.readInt());}}}

总结:这一章节主要介绍IO的典型用法的两个典型用法。


这一章节就到这里,谢谢。

-----------------------------------

目录



0 0
原创粉丝点击