/*Java 输入流(读取txt文件)*/

读取txt文件有两种方式,第一种是字符型读取,第二种是字节型读取。
字节流(Byte Stream)每次读写8位二进制数,
也称为二进制字节流或位流。
字符流一次读写16位二进制数,并将其做一个字符而不是二进制位来处理。需要注意的是,为满足字符的国际化表示,Java语言的字符编码
采用的是16位的Unicode码,而普通文本文件中采用的是8位ASCⅡ码。

一.字符型读取
package cn.newdream.class68.chapter04;
import java.io.FileReader;  
import java.io.IOException;  
public class CharReader_02 {  
public static void main(String[] args) throws IOException {  
        /** 
         * 创建读取字符数据的流对象。 
         * 读取路径不正确时会抛 IOException 
         * 用一个读取流对象关联一个已存在文件。 
         */  
String path =System.getProperty("user.dir")+"\\data\\test.txt";
        FileReader fr = new FileReader(path);  
        /** 
         * 用Reader中的read方法读取字符。 
         */  
        /*String ah = fr.read(); 
        System.out.print((char)String ah); 
        String ch1 = fr.read(); 
        System.out.print((char)ch1); 
        String ch2 = fr.read(); 
        System.out.print((char)ch2);*/  
        int ch = 0;  
        while((ch = fr.read()) != -1){  
            System.out.print((char)ch);  
        }  
        fr.close();  
        }  
} 
//FileReader类
1,构造方法
FileReader fr = new FileReader(String fileName);//使用带有指定文件的String参数的构造方法。创建该输入流对象。并关联源文件。
2,主要方法
int read(); // 读取单个字符。返回作为整数读取的字符,如果已达到流末尾,则返回 -1。
int read(char []cbuf);//将字符读入数组。返回读取的字符数。如果已经到达尾部,则返回-1。
void close();//关闭此流对象。释放与之关联的所有资源。

二.字节型读取

package cn.newdream.class68.chapter04;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class ByteReader_02 {
    public static void main(String[] args) throws Exception {
        String filePath = System.getProperty("user.dir");
        filePath = filePath + "\\data\\hello.txt";
        FileInputStream in = new FileInputStream(filePath); 
//System.out.println((char)in.read()); //一个字符读取
        int tempbyte;
        while ((tempbyte = in.read()) != -1) {
//System.out.write(tempbyte);
//System.out.println((char)tempbyte);
            System.out.print((char)tempbyte);
        }
        in.close();
    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值