Java如何使用FileInputStream读取文件?

下面的示例使用java.io.FileInputStream该类读取文本文件的内容。我们将读取操作系统定义的临时目录中的文件。可以使用java.io.tmpdirsystem属性访问此临时目录。

package org.nhooo.example.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStreamDemo {
    public static void main(String[] args) {
        //获取临时目录。我们将阅读data.txt文件
        // 从此目录。
        String tempDir = System.getProperty("java.io.tmpdir");
        File file = new File(tempDir + "/data.txt");

        StringBuilder builder = new StringBuilder();
        FileInputStream fis = null;
        try {
            // 创建一个FileInputStream来读取文件。
            fis = new FileInputStream(file);

            int data;
            //读取整个文件数据。当返回-1时
            // 意味着没有更多内容可供阅读。
            while ((data = fis.read()) != -1) {
                builder.append((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        // 打印文件内容
        System.out.println("File Contents = " + builder.toString());
    }
}

从输入流中读取的内容将被附加到一个StringBuilder对象中。在代码段的末尾,的内容将使用toString()方法转换为字符串。

这是我们data.txt文件的内容。

File Contents = Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the
1500s, when an unknown printer took a galley of type and scrambled it to
make a type specimen book. It has survived not only five centuries, but
also the leap into electronic typesetting, remaining essentially unchanged.
It was popularised in the 1960s with the release of Letraset sheets
containing Lorem Ipsum passages, and more recently with desktop publishing
software like Aldus PageMaker including versions of Lorem Ipsum.