Command line 如何使程序使用在命令行上指定名称的文件
如何让这个程序在命令行的“lab13.txt”中读取?我花了一个多小时试图弄明白这一点,但似乎什么都不管用 提示是“编写一个程序,该程序确定并显示在命令行上指定名称的文件中的行数。使用lab13.txt测试程序。”Command line 如何使程序使用在命令行上指定名称的文件,command-line,java.util.scanner,java-io,file-processing,Command Line,Java.util.scanner,Java Io,File Processing,如何让这个程序在命令行的“lab13.txt”中读取?我花了一个多小时试图弄明白这一点,但似乎什么都不管用 提示是“编写一个程序,该程序确定并显示在命令行上指定名称的文件中的行数。使用lab13.txt测试程序。” 如果希望用户能够从eclipse中的命令行或控制台输入文件名,请尝试使用 BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Pleas
如果希望用户能够从eclipse中的命令行或控制台输入文件名,请尝试使用
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter filename : ");
String filename = null;
try {
filename = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
然后,您可以将文件名插入扫描仪对象
在程序名之后添加到命令行的内容将进入args数组,因此:
Scanner inFile= new Scanner(new File(args[0]));
在代码中,您需要将新文件(“lab13.txt”)
替换为新文件(args[0])
用于命令行
public static void main(String[] args) {
File inFile =null;
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();
}
}
}
Try this
public static void main(String[] args) {
File inFile =null;
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();
}
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\lab13.txt"));
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();
}
}
}
}