gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:32:04 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com