我正在使用此代碼使用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