Java当中的IO(二)

来源:互联网 发布:行政审批流程优化方案 编辑:程序博客网 时间:2024/04/29 09:24

字符byte 字节char

大文件的读写方法&字符流的使用方法

对于一个大文件的读写,我们不可能一次性定义一个很长的字节数组进行保存,只能用循环的方式进行读取。

//第一步骤:导入类import java.io.*;class Test{public static void main(String args[]){//生成一个字节数组,用来存读取的字节byte [] buffer = new byte[1024];//声明输入流引用(从硬盘读到java程序里)FileInputStream fis = null;//声明输出流引用(从java程序写到硬盘里)FileOutputStream fos = null;try{//生成代表输入流的对象fis = new FileInputStream("D:/src/io/from.txt");fos = new FileOutputStream("D:/src/io/to.txt");while(true){//调用输入流对象的read方法,读取数据//参数1:读取字节所存数组 参数2:偏移量 参数3:读取fis中位数//read方法返回一次读取了多少字节int temp = fis.read(buffer,0,buffer.length);//当fis把文件读到最尾部后,会返回一个值-1if(temp == -1){break;}fos.write(buffer,0,temp);}}catch(Exception e){System.out.println(e);}finally{//开启了输入流和输出流,我们还应该关闭流try{fis.close();fos.close();}catch(Exception e){System.out.println(e);}}}}

字符流:读写文件时,以字符为基础。



字节输入流:Reader(抽象父类)<--------FileReader(子类)
public intread(char[] buffer,intoffset,intcount)
读的方法,返回一个读了多少的值
字节输出流:Writer(抽象父类)<--------FileWriter(子类)
public voidwrite(char[] buffer,intoffset,intcount)
写得方法,就什么都不返回


import java.io.*;public class TestChar{public static void main(String args[]){FileReader fr = null;FileWriter fw = null;try{fr = new FileReader("d:/src/io/from.txt");fw = new FileWriter("d:/src/io/to.txt");char buffer [] = new char[1024];int temp = fr.read(buffer,0,buffer.length);<span style="font-family: Arial, Helvetica, sans-serif;">//读取buffer.length长度的字节放入buffer中,偏移量为0</span>fw.write(buffer,0,temp);}catch(Exception e){}finally{try{fr.close();fw.close();}catch(Exception e){System.out.println(e);}}}}

字节流和字符流,两种用法差不错,就是存的时候不一样,

字节流用byte,字符流用char






0 0