简单的java代码中的FileNotfoundexception

时间:2012-01-09 18:00:55

标签: java

我正在使用此代码使用filereader对象读取java中的文件。然而,该应用程序抛出一个异常,表明它无法找到该文件。任何人都可以帮助这个新手只进入java编程

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 是一个包含一些内容的简单文本文件

提前多多感谢

6 个答案:

答案 0 :(得分:2)

除了@Adel指出的args [0]错误之外,您还不必在命令行中转义“\”...“C:\ Hello.txt”就足够了。

答案 1 :(得分:1)

您不需要\\。 Java不解析输入字符串中的转义序列,单个反斜杠是Windows shell中的路径分隔符。

答案 2 :(得分:0)

我通常在File对象及其使用之间添加以下行:

if (!objFile.isFile() || !objFile.exists()) {
  System.out.println("Could not find file: " + objFile.getPath().toString();
}

这通常会在文件名的字符串格式中显示问题。

答案 3 :(得分:0)

该代码适用于我的MacOS系统,问题在于您在Windows中编写文件路径的方式。就我而言:

java CFileReader /home/jenaiz/test.txt

答案 4 :(得分:0)

我自己在Windows上编译并测试了这段代码,它运行正常。您所访问的文件不存在,或者在命令行中键入文件名时出错。

答案 5 :(得分:0)

检查输入文件是否确实存在。当我在我的机器上运行代码时,我没有权限在C:的根目录中创建文件。你是如何创建测试文件的?

当我将文件移动到另一个驱动器时,例如“t:\ hello.txt”它第一次工作。