源代码如下:
//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
基本上是成功了。