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

被折叠的 条评论
为什么被折叠?



