我正在使用此代码使用filereader对象在java中读取文件。然而,应用程序会抛出异常,说明它无法找到file.Can谁能帮助这个新手家伙刚进入Java编程简单java代码中的FileNotfound异常
import java.util.*;
import java.io.*;
import java.util.Scanner;
import java.io.FileReader;
import java.io.PrintWriter;
public class CFileReader {
/**
* @param args
*/
public static void main(String[] args) throws FileNotFoundException
{
String objLine;
String strInputFileName;
FileReader objReader = null;
Scanner objScanner;
File objFile;
if(args.length > 0)
{
for(int i = 0;i < args.length ;i++)
{
//Gets the arguments into the strInputFileName variable
strInputFileName = args[i];
System.out.println("Filename entered was : " + strInputFileName);
//Create a file object which points to the filename i.e strInputFileName
objFile = new File(strInputFileName);
//Create a FileReader object with the File object i.e objFile as the input parameter
objReader = new FileReader(objFile);
System.out.println("Filereader object is : " + objReader.toString());
//Create a scanner object with FileReader as input parameter
objScanner = new Scanner(objReader);
System.out.println(args);
//Scans the file if it has next line
while(objScanner.hasNextLine())
{
//Store the contents i.e. first line in the objLine Variable
objLine = objScanner.nextLine();
//prints the contents
if(objLine.indexOf(i) > 0)
{
System.out.println(objLine);
}
}
}
}
else
{
//Warn the user to enter the command line arguments if he has not entered
System.out.println("Please Enter Command line args");
}
}
}
编译我使用
javac CFileReader.java
和运行程序
java CFileReader "C:\\Hello.txt"
其中hello.txt的是一些内容的简单文本文件
非常感谢您提前致谢
你可以打印stacktrace(错误信息?) – OscarRyz 2012-01-09 18:03:19
你的(root)'C:'目录中是否存在'Hello.txt'?你真的需要双倍\\在那里? (不是100%肯定后者)。 – 2012-01-09 18:05:20
有一件事要检查:尝试打印出'objFile.getAbsolutePath()'(在创建文件后),看看它是否是你期望的。我不确定这些命令将如何解析。 – 2012-01-09 18:06:01