![](/img/trans.png)
[英]how to read from file that was giving in a command line argument in java?
[英]How to read file from command line in java?
我想转到命令行并输入输入,因此BufferReader可以访问该文件。 我应该怎么做?
输入将为“ java TagMatching path_to_html_file.html”
// Importing only the classes we need
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TagMatching {
public static void main(String[] args) {
BufferedReader br = null;
// try to read the file
try {
br = new BufferedReader(new FileReader(**/*DONT KNOW WHAT TO DO*/**));
String line;
} catch (IOException e) {
e.printStackTrace();
}
}
}
输入将是
java TagMatching path_to_html_file.html
在应用程序名称( TagMatching
)之后,您会找到参数( path_to_html_file.html
),这是main方法的String[] args
,因此只需使用它们,在本例中为args[0]
:
public static void main(String[] args) {
BufferedReader br = null;
// try to read the file
try {
// check if there are some arguments
if (null != args[0] &&
// lenght > 5 because a.html will be shortest filename
args[0].lenght > 5 &&
// check if arguments have the correct file extension
args[0].endsWith(".html"))
{
br = new BufferedReader(new FileReader(args[0]));
// do more stuff
}
} catch (IOException e) {
e.printStackTrace();
}
}
要从控制台获取输入,您必须使用Scanner这样;
Scanner in = new Scanner(System.in);
System.out.println("Enter file path");
String s = in.nextLine(); //C:\\testing.txt
要在FIleReader中使用该文件路径,请使用如下代码;
br = new BufferedReader(new FileReader(s));
与args [0]完全一样。
因此, br = new BufferedReader(new FileReader(args[0]));
将按照提问者的意图
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.