joh*_*mos 2 java command-line bufferedreader
我正在得到一个日食红色下划线错误
br = new BufferedReader(new FileReader(inFile));
Run Code Online (Sandbox Code Playgroud)
关于"inFile"的一行.这是我想要阅读的对象,我认为它包含我在命令行上给出的命令行文件名/路径.我处理这个错误吗?
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
if (0 < args.length) {
File inFile = new File(args[0]);
}
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(inFile));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
改变这个:
if (0 < args.length) {
File inFile = new File(args[0]);
}
Run Code Online (Sandbox Code Playgroud)
对此:
File inFile = null;
if (0 < args.length) {
inFile = new File(args[0]);
} else {
System.err.println("Invalid arguments count:" + args.length);
System.exit();
}
Run Code Online (Sandbox Code Playgroud)
因为该file
变量在if/else
语句之外是不可访问的.
我已添加else
(在没有args
提供的情况下)一条友好的消息,说明参数计数无效并退出程序.