字节流和字符流分别读取文件

来源:互联网 发布:淘宝三星手机官网 编辑:程序博客网 时间:2024/05/19 11:44
package com.summerkxy.file.one;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;public class readMusic {public static void main(String[] args) throws FileNotFoundException{//read2 read2 = new read2();//read2.readDemo();read1 read1 = new read1();read1.readDemo_one();}}//字符流读取数据class read1{void readDemo_one() throws FileNotFoundException{File file1 = new File("D:\\log.txt");try {FileReader file11 = new FileReader(file1);char[] chars = new char[20];//必须是字符数组,因为定义的是字符流StringBuffer str = new StringBuffer();int c = 0;while((c=file11.read(chars))!=-1){str.append(new String(chars,0,c));}System.out.println(str);} catch (IOException e) {// TODO 自动生成的 catch 块e.printStackTrace();}}}//字节流读取数据class read2{void readDemo() throws FileNotFoundException{File file2 = new File("D:\\log.txt");try {FileInputStream file21 = new FileInputStream(file2);byte[] bytes = new byte[20];StringBuffer str = new StringBuffer();int c = 0;while((c = file21.read(bytes))!=-1){str.append(new String(bytes,0,c));}System.out.println(str);System.out.println(str);} catch (IOException e) {// TODO 自动生成的 catch 块e.printStackTrace();}}}
由上面的例子得出:字符流比较适合处理文本信息,字节流处理图片,声音等信息

0 0
原创粉丝点击