T001-UT001-0025

文件读写练习——读取文本文件内容


编写一个程序,从标准输入设备上输入一个待待读取的文件名,敲击回车后读取该文件的内容,并打印在标准输出终端上。 

举例一:

输入:

1
2
input a  file  to  read :
d: /test .txt

输出:

Hello world!
Here is my first file!
代码如下:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

public class D0025 {
	public static void main(String[] args) {
		BufferedReader br= null;
		String filepath=null;
		try{
			br = new BufferedReader(new InputStreamReader(System.in));
			System.out.println("input a file to read:");
			filepath= br.readLine();	//接收用户输入
		}catch(IOException e){
			System.out.println(e.getMessage());
		}finally{
			try {
				br.close();			//关闭对象前会调用bw.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		user(filepath);
	}
	//读取文件内容函数
	public static void user(String filepath){
		FileInputStream fis = null;
		InputStreamReader isr = null;
		BufferedReader br = null; //用于包装InputStreamReader,提高处理性能。因为BufferedReader有缓冲的,而InputStreamReader没有。
		try {
			String str = "";
			String str1 = "";
			fis = new FileInputStream(filepath);// FileInputStream
			// 从文件系统中的某个文件中获取字节
			isr = new InputStreamReader(fis);// InputStreamReader 是字节流通向字符流的桥梁,
			br = new BufferedReader(isr);// 从字符输入流中读取文件中的内容,封装了一个new InputStreamReader的对象
			while ((str = br.readLine()) != null) {
				str1 += str + "\n";
			}
			// 当读取的一行不为空时,把读到的str的值赋给str1
			System.out.println(str1);// 打印出str1
		}catch (FileNotFoundException e) {
			System.out.println("找不到指定文件");
		}catch (IOException e) {
			System.out.println("读取文件失败");
		}finally{
			try{
				br.close();
				isr.close();
				fis.close();
				// 关闭的时候最好按照先后顺序关闭最后开的先关闭所以先关s,再关n,最后关m
			}catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

java文件读写操作: 点击打开链接
(全文完)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值