Java中用I/O流操作读入.txt文件(面试小记)

随便在一个目录下创建一个.txt文件,我在D盘根目录下创建了a.txt文件,内容为:
a.txt:

zhongguoweiwu!
the world peace!

代码如下:

package com.strong.IO;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class StreamDemo {
    public static void main(String[] args){
        FileInputStream fis = null; //因txt是文件,需用字节输入流FileInputStream或者InputStream
        try{
            fis = new FileInputStream("d:/a.txt");

            StringBuffer sb = new StringBuffer();

            int temp = 0;
            //循环读入字符
            while(true){
                try {
                    if (((temp = fis.read()) == -1)) break;
                    sb.append((char)temp); //将读到的字符的ASCII码值逐个强制转成字符,并放入StringBuffer/StringBuilder中
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println(temp); //逐个输出字符的ASCII码值

            }
            System.out.println(sb.toString()); //输出txt文件中所有的字符

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {

        }
    }
}

输出结果:

122
104
111
110
103
103
117
111
119
101
105
119
117
33
13
10
116
104
101
32
119
111
114
108
100
32
112
101
97
99
101
33
zhongguoweiwu!
the world peace!

Process finished with exit code 0

StringBuilder与StringBuffer的区别
String 是字符串常量;
StringBuffer 字符串变量(线程安全),低效的;
StringBuilder 字符串变量(非线程安全)高效的。

再说一下常用的I/O流

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值