java读取input选择打的文件,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.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值