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流

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_48951688/article/details/125322304
今日推荐