我编写了以下非常简单的 Java 程序,要求用户输入文件名,然后它将该文件的行数报告到标准输出:
import java.io.*;
import java.util.*;
public class CountLine {
public static void main(String[] args)
{
// prompt the user to enter their file name
System.out.print("Please enter your file name: ");
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String fileName = null;
// read the username from the command-line; need to use try/catch with the
// readLine() method
try {
fileName = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read your name!");
System.exit(1);
}
System.out.println("Thanks for the file name, " + fileName);
File file = new File("C:/Users/Will/Desktop/"+fileName);
Scanner scanner;
try {
scanner = new Scanner(file);
int count =0;
String currentLine;
while(scanner.hasNextLine())
{
currentLine=scanner.nextLine();
count++;
}
System.out.println("The number of lines in this file is "+count);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("There is no such file");
e.printStackTrace();
}
}
}
它正在工作。如果专家能帮助我,我将非常感激
- 看看这个代码片段有什么可以改进的,
- 如果未找到该文件,则在最外层的 catch 语句中捕获异常并打印出堆栈跟踪。但是,我觉得不是很人性化,有没有办法如果文件不存在,那么整个过程从头开始?
提前致谢。