Java IO流 续

编程技术  /  houtizong 发布于 3年前   78

1.基于字节文件读写

  • FileInputStream和FileOutputStream分别继承自InputStream和OutputStream用于向文件中输入和输出字节。
  • FileInputStream和FileOutputStream的常用构造方法:
    FileInputStream(String name) throws FileNotFoundException
    FileInputStream(File file)   throws FileNotFoundException
    FileOutputStream(String name)throws FileNotFoundException
    FileOutputStream(File file)  throws FileNotFoundException
    FileOutputStream(File file, boolean append)throws FileNotFoundException
  • 注意:
    在实例化FileInputStream和FileOutputSteam流时要用try-catch语句以处理其可能抛出的FileNotFoundException。
    在读写数据时也要用try-catch语句以处理可能抛出的 IOException。
    FileNotFoundException是IOException的子类
package javaio.inputstream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;/** * 将TestFileInputStream.java中的内容读出来 * @author Administrator * */public class TestFileInputStream {public static void main(String[] args) {FileInputStream in = null;try {in = new FileInputStream("D:\\TestFileInputStream.java");} catch (FileNotFoundException e) {System.out.println("没有找到TestFileInputStream.java文件");e.printStackTrace();return;}//如果流不为空循环流if(in!=null){StringBuffer buffer = new StringBuffer();byte b[] = new byte[1024];try {while (in.read(b)!=-1) {buffer.append(new String(b));b = new byte[1024];}System.out.println(buffer.toString());} catch (IOException e) {System.out.println("读取错误");e.printStackTrace();return;//关闭流}finally{if(in!=null){try {in.close();in = null;} catch (IOException e) {e.printStackTrace();}}}}}}
  •  写
package javaio.outputstream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;/** * 将TestFileInputStream.java中的内容读出来然后写入到TestFileInputStream2.java *  * @author Administrator *  */public class TestFileOutputStream {public static void main(String[] args) {FileInputStream in = null;FileOutputStream out = null;try {in = new FileInputStream("D:\\TestFileInputStream.java");out = new FileOutputStream("D:\\TestFileInputStream2.java");if(in!=null){StringBuffer buffer = new StringBuffer();byte b[] = new byte[1];while (in.read(b)!=-1) {buffer.append(new String(b));out.write(b);b = new byte[1];}}} catch (FileNotFoundException e) {System.out.println("没有找到TestFileInputStream.java文件");e.printStackTrace();return;} catch (IOException e) {System.out.println("读取或写入发生错误");e.printStackTrace();}finally {  try {  if(in != null) {  in.close();   in = null;  }    } catch(IOException e) {    e.printStackTrace();    }  try {  if(out != null) {  out.flush();    out.close();    out = null;    }     } catch(IOException e) {    e.printStackTrace();    }  }}}

 2.基于字符文件读写

  • FileReader 和 FileWriter 分别继承自Reader和Writer,FileInputSteam与FileOutputStream类似,所不同的是FileReader和FileWriter向文件输入和输出的数据单位为字符。
  • FileReader和FileWriter的常用构造方法:
    public FileWriter(File file) throws IOException
    public FileWriter(File file, boolean append)throws IOException
    public FileWriter(String fileName)throws IOException
    public FileWriter(String fileName,boolean append)throws IOException
    public FileReader(String fileName)throws FileNotFoundException
    public FileReader(File file) throws FileNotFoundException
package javaio.reader;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;/** * 读取指定文件内容 *  * @author Administrator *  */public class TestFileReader {public static void main(String[] args) {FileReader reader = null;try {reader = new FileReader("D:\\TestFileReader.java");if(reader!=null){StringBuffer buffer = new StringBuffer();char b[] = new char[1024];while (reader.read(b)!=-1) {buffer.append(new String(b));b = new char[1024];}System.out.println(buffer.toString());}} catch (FileNotFoundException e) {System.out.println("没有找到TestFileReader.java文件");e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally {if(reader != null) {try{reader.close();}catch (IOException e){e.printStackTrace();}reader = null;}}}}

 

package javaio.writer;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;/** * 将TestFileReader.java内容写入到TestFileReader2.java中 * @author Administrator * */public class TestFileWriter {public static void main(String[] args) {FileReader reader = null;FileWriter writer = null;try {reader = new FileReader("D:\\TestFileReader.java");writer = new FileWriter("D:\\TestFileReader2.java");if(reader!=null){char b[] = new char[1];while (reader.read(b)!=-1) {writer.write(b);}}} catch (FileNotFoundException e) {System.out.println("没有找到TestFileReader.java文件");e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally {if(reader != null) {try{reader.close();}catch (IOException e){e.printStackTrace();}reader = null;}if(writer != null) {try{writer.flush();writer.close();}catch (IOException e){e.printStackTrace();}writer = null;}}}}

 

3.什么时候使用字节流?什么时候使用字符流?

  • 任何数据存在硬盘上时,都是以二进制的形式存储的。
  • 通过使用字节流,可以读取任意文件。字节流一次读取一个字节,而字符流使用了字节流读到一个或者多个字节时,去查找指定的编码表,返回对应的编码。所以字符流只能处理纯文本字符数据,而字节流可以处理更多类型的数据,比如图片,视频,音频文件等。
  • 只要是纯文本数据处理,优先考虑使用字符流。其他情况就使用字节流。

4.缓冲流

  • 缓冲流-Buffered:缓冲流要“套接”在相应的节点流之上,对读写的数据提供了缓冲的功能,提高了读写的效率
  • 读写
    BufferedReader提供了readLine方法用于读取一行字符串(以\r或\n分隔)。
    BufferedWriter提供了newLine用于写入一个行分隔符。
    对于输出的缓冲流,写出的数据会先在内存中缓存,使用flush方法将会使内存中的数据立刻写出。
  • 常用的构造方法
    BufferedReader(Reader in)
    BufferedReader(Reader in,int size) //size 为自定义缓存区的大小
    BufferedWriter(Writer out)
    BufferedWriter(Writer out,int sz)
    BufferedInputStream(InputStream in)
    BufferedInputStream(InputStream in,int size)
    BufferedOutputStream(OutputStream out)
    BufferedOutputStream(OutputStream out,int size)
  • 基于字节读
package javaio.buffered;import java.io.BufferedInputStream;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;/** * 使用缓冲流读取指定文件内容 * @author Administrator * */public class TestBufferedInputStream {  public static void main(String[] args) {  BufferedInputStream bis = null;    try {      InputStream fis =  new FileInputStream("D:\\TestFileInputStream.java");      bis = new BufferedInputStream(fis);      if(bis!=null){StringBuffer buffer = new StringBuffer();byte b[] = new byte[1024];while (bis.read(b)!=-1) {buffer.append(new String(b));b = new byte[1024];}System.out.println(buffer.toString());      }      System.out.println();          } catch (IOException e) {    e.printStackTrace();    } finally {     try {     if(bis != null) {     bis.close();     bis = null;     }    } catch (IOException e) {    e.printStackTrace();    }    }  }}
  •  基于字节写
package javaio.buffered;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;/** * 使用缓冲流读取指定文件内容复制到另一个文件 * @author Administrator * */public class TestBufferedOutputStream {public static void main(String[] args) {BufferedInputStream bis = null;BufferedOutputStream bos = null;try {InputStream fis = new FileInputStream("D:\\TestFileInputStream.java");OutputStream out = new FileOutputStream("D:\\TestFileInputStream3.java");bis = new BufferedInputStream(fis);bos = new BufferedOutputStream(out);if (bis != null) {StringBuffer buffer = new StringBuffer();byte b[] = new byte[1];while (bis.read(b) != -1) {buffer.append(new String(b));bos.write(b);b = new byte[1];}}} catch (IOException e) {e.printStackTrace();} finally {try {if (bis != null) {bis.close();bis = null;}if (bos != null) {bos.flush();bos.close();bos = null;}} catch (IOException e) {e.printStackTrace();}}}}
  •  基于字符读写
package javaio.buffered;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.Reader;import java.io.Writer;/** * 从指定文件中用BufferedReader读取数据然后用BufferedWriter写入另一个文件中 *  * @author Administrator *  */public class TestBufferedReaderAndWriter {public static void main(String[] args) {BufferedReader breader = null;BufferedWriter bwriter = null;try {Reader reader = new FileReader("D:\\TestFileReader.java");Writer writer = new FileWriter("D:\\TestFileReader3.java");breader = new BufferedReader(reader);bwriter = new BufferedWriter(writer);if(breader!=null){while(breader.ready()){bwriter.write(breader.readLine());bwriter.newLine();}}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally{if(bwriter!=null){try {bwriter.flush();bwriter.close();bwriter = null;} catch (IOException e) {e.printStackTrace();}}if(breader!=null){try {breader.close();breader = null;} catch (IOException e) {e.printStackTrace();}}}}}

 5.转换流

  • InputStreamReader和OutputStreamWriter用与字节数据到字符数据之间的转换。
  • InputStreamReader需要和InputStream “套接”。
  • OutpStreamWriter需要和OutputStream “套接”。
  • 转换流在构造时可以指定其编码集合,例如:
     InputStream isr = new InputStreamReader(InputStream in, CharsetDecoder dec)
  • TestOutputStreamWriter

 

package javaio.transfer;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStreamWriter;/** * 将字节流转换为字符流输出 *  * @author Administrator *  */public class TestOutputStreamWriter {public static void main(String[] args) {OutputStreamWriter osw = null;try {osw = new OutputStreamWriter(new FileOutputStream("D:\\test.txt"),"gbk");osw.write("测试OutputStreamWriter");osw.write("\r\n");osw.write("测试OutputStreamWriter");osw.flush();osw.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}
  •  TestInputStreamReader
package javaio.transfer;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileWriter;import java.io.IOException;import java.io.InputStreamReader;/** * 在控制台写入内容保存到文件中 * @author Administrator * */public class TestInputStreamReader {public static void main(String args[]) {InputStreamReader isr = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(isr);BufferedWriter writer = null;try {String str = br.readLine();writer = new BufferedWriter(new FileWriter("D:\\write.txt"));while (str != null) {if ("".equals(str)){break;}writer.write(str);writer.newLine();str = br.readLine();}} catch (IOException e) {e.printStackTrace();}finally{if(br!=null){try {br.close();br=null;} catch (IOException e) {e.printStackTrace();}}if(writer!=null){try {writer.flush();writer.close();writer=null;} catch (IOException e) {e.printStackTrace();}}}}}

6.数据流

  • DataInputStream和DataOutputStream分别继承自InputSteam和OutputStream,它属于过滤流,需要分别“套接”在InputStream 和OutputStream类型的节点流上。
  • DataInputStream和DataOutputStream提供了可以存取与机器无关的Java原始类型数据(如:int,double等)的方法。
  • DataInputStream和DataOutputStream的构造方法为:
    DataInputStream(InputStream in)
    DataOutputStream(OutputStream out)
  • TestDataStream
package javaio.datastream;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;public class TestDataStream {public static void main(String[] args) {DataOutputStream dos = null;DataInputStream dis = null;try {dos = new DataOutputStream(new FileOutputStream("d:\\data.txt"));dos.writeInt(5);dos.writeDouble(2.12);dos.flush();dos.close();dis = new DataInputStream(new FileInputStream("d:\\data.txt"));System.out.println(dis.readInt());System.out.println(dis.readDouble());dis.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}

7.Print流

  • PrintWriter和PrintStream都属于输出流,分别针对与字符和字节。
  • PrintWriter和PrintStream提供了重载的print
  • println方法用于多种数据类型的输出。
  • PrintWriter和PrintStream有自动flush功能。
package javaio.print;import java.io.FileOutputStream;import java.io.IOException;import java.io.PrintStream;public class TestPrint {public static void main(String[] args) {PrintStream ps = null;try {FileOutputStream fos = new FileOutputStream("D:\\TestFileReader3.java");ps = new PrintStream(fos);} catch (IOException e) {e.printStackTrace();}if (ps != null) {System.setOut(ps);}System.out.println("我们是中国人");System.out.println("我们是中国人");if(ps!=null){ps.flush();ps.close();}}}

 

8.Object流

  • 直接将Object写入或读出
  • transient声明的部分不会被序列化
  • Serializable接口:序列化
  • Externalizable 接口
    void writeExternal(ObjectOutput out) throws IOException
    void readExternal(ObjectInput in) throws IOException,ClassNotFoundException
package javaio.object;import java.io.Serializable;public class Person implements Serializable{private static final long serialVersionUID = 1L;private String name;private String sex;private transient int age = 20;public String getName() {return name;}public String getSex() {return sex;}public int getAge() {return age;}public void setName(String name) {this.name = name;}public void setSex(String sex) {this.sex = sex;}public void setAge(int age) {this.age = age;}}

 

 

package javaio.object;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;public class TestObjectIO {public static void main(String args[]) throws Exception {Person person = new Person();person.setAge(23);person.setName("张三");person.setSex("男");FileOutputStream fos = new FileOutputStream("D://object.data");ObjectOutputStream oos = new ObjectOutputStream(fos);oos.writeObject(person);oos.flush();oos.close();FileInputStream fis = new FileInputStream("D://object.data");ObjectInputStream ois = new ObjectInputStream(fis);Person tReaded = (Person)ois.readObject();System.out.println(tReaded.getName() + " " + tReaded.getSex() + " " + tReaded.getAge());}}

 

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!

留言需要登陆哦

技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成

网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];

      订阅博客周刊 去订阅

文章归档

文章标签

友情链接

Auther ·HouTiZong
侯体宗的博客
© 2020 zongscan.com
版权所有ICP证 : 粤ICP备20027696号
PHP交流群 也可以扫右边的二维码
侯体宗的博客