java - 简单java代码中的FileNotfound异常

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

提前非常感谢

最佳答案

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

关于java - 简单java代码中的FileNotfound异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8792975/

相关文章:

java - Java 抽象类和接口(interface)

java - Maven 如何为 create-schema 命令指定 sql 文件的目录

java - 名称值对排序

java - 内聚性和耦合性——如何确定阈值?

java - Eclipse 选项卡仅在项目内关闭

java - 当我得到的是 "\uD83D\uDE02"时,如何生成像 "U+1F602"这样的表情符号 unicode ?

java - 井字游戏抛出异常

java - 实例变量声明和实例化

java - 对象可以有访问修饰符吗?

Java 计数功能不起作用。控制台应用程序数字数组