Java9 编程参考官方大全(第10版)第13章:IO_Try和其他主题13.5读写文件

本文介绍了一个简单的Java程序,用于读取并打印名为'test.txt'的文件内容到控制台。程序首先检查是否指定了文件名,然后尝试打开文件。如果文件存在,程序将逐字符读取并打印直到文件结束。作者在Eclipse环境中运行时遇到问题,将文件放在类的目录下,并通过命令行方式执行。程序成功执行的关键在于正确定位文件位置。

源代码如下:

//display a text file 
//specify the file name 
// follow the command of below 
// cmd
//java ShowFile test.txt
import java.io.*;
public class ShowFile {
	/////////////////////
	public static void main(String args[]) 
	{
		// TODO Auto-generated method stub
		int i;
		FileInputStream fin;
		// First confirm that a filename has been specified.
		if(args.length!=1){
			System.out.println("Usage:ShowFile filename");
		return;
		}
	/////////////////////
	
	// attempt to open the file 
	try{
		fin=new FileInputStream(args[0]);
	}catch(FileNotFoundException e){
		System.out.println("Can not Open File ");
		return ;
	}
	//at this point ,the file is opend and be read.
	// The following reads characters until EOF is encountered.
	try{
		do{
			i=fin.read();
			if(i!=-1) System.out.println((char) i);
		} while (i!=1);
		
	} catch (IOException e){
		System.out.println("Error Reading File ");
	}
	//Close the file 
	try{
		fin.close();
	} catch (IOException e){
		System.out.println("Error Closing File");
	}

}
}

这个程序比较简单,就是读一个叫test.txt 的文件,打印到控制台。

但是这个程序运行的时候,难住我了,不值得该把这个test.txt 文件放在什么地方? 在Eclipse中运行这个程序,不知道Eclipse去哪里读这个文件去?我就把这个test.txt 放到这个类的目录了,然后进入这个 目录,cmd 模式下 javac ShowFile.java 

java ShowFile test.txt 

基本上是成功了。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值