栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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流

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/978012.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号