使用字符流的好处:不用创建一个非常大的buf,把文件分成很多小部分读写。
创建两个txt,from和to,在from中写入文本
//*******************************华丽分割线**********************************//
字符流:读写文件时,以字符为基础
字节输入流:Reader,常用子类FilerReader
常用子类方法
int read(char [] c,int off,int len);
字节输出量:Writer,常用子类FilerWriter
void write(char [] c,int off,int len);
代码基本上与字节流相似
创建两个txt,from和to,在from中写入文本
import java.io.*;//导入java中IO所有的类 class Test{ public static void main(String args[]){ FileInputStream fis = null;//声明输入流引用 FileOutputStream fos = null;//声明输出流引用 try{ //生成代表输入流的对象 fis = new FileInputStream("d:/java/src/from.txt"); //生成代表输出流的对象 fos = new FileOutputStream("d:/java/src/to.txt"); byte [] buffer = new byte[100];//生成一个1K字节数组 while(true)//没有读完就一直执行 { //调用输入流对象的read方法,读取from.txt中的数据 int temp_length =fis.read(buffer,0,buffer.length); if(temp_length == -1)//返回-1说明读取完毕了 直接跳出 break; //调用输出流对象的write方法,写入数据到to.txt fos.write(buffer,0,temp_length); String s = new String(buffer););//将byte还原成字符 //调用trim方法,将会去除掉这个字符串的首尾空格和空字符 //如" abc def " 使用trim之后将变成"abc def" s.trim(); System.out.println(s);//打印出来 } } catch(Exception e) { System.out.println(e); } finally { //再加上一层try捕捉关闭输入输出流的时候出错 /* Test.java:27: 错误: 未报告的异常错误IOException; 必须对其进行捕获或声明以便抛出 fis.close(); ^ Test.java:28: 错误: 未报告的异常错误IOException; 必须对其进行捕获或声明以便抛出 fos.close(); */ try{ fis.close();//关闭输入流 fos.close();//关闭输出流 } catch(Exception e){ System.out.println(e); } } } }以上是字节流的方式读写
//*******************************华丽分割线**********************************//
字符流:读写文件时,以字符为基础
字节输入流:Reader,常用子类FilerReader
常用子类方法
int read(char [] c,int off,int len);
字节输出量:Writer,常用子类FilerWriter
void write(char [] c,int off,int len);
代码基本上与字节流相似
import java.io.*; class Test{ public static void main(String args[]){ FileReader fr =null; FileWriter fw = null; try{ fr = new FileReader("d:/java/src/from.txt"); fw = new FileWriter("d:/java/src/to.txt"); char [] buffer = new char[1024]; while(true) { int temp_length = fr.read(buffer,0,buffer.length); if(temp_length == -1) break; fw.write(buffer,0,temp_length); // String s =new String(buffer); // s = s.trim(); System.out.println(s); } } catch(Exception e) { System.out.println(e); } finally { try{ fr.close(); fw.close(); } catch(Exception e){ System.out.println(e); } } } }
By Urien 2018年4月4日 15:48:39