创建 .jar 读取用户给定的多个文件
create .jar that reads multiple files given by user
我正在尝试制作一个读取 .txt 文件并打印一些值的 .jar 可执行文件。
我的问题是我不想在制作 .jar 之前指定 .txt 文件名,我想将 .jar 传递给用户,每次在他 运行 .jar 之前他都会指定所需的要读取的 .txt 文件。
有什么办法吗?
您可以让用户插入文件名,程序将其添加到搜索路径中 例如:"C:\"+textname
您可以从传递给 Main 方法的字符串数组中获取命令行参数。
public static void main(String[] args) {
if (args.length <= 0) {
System.out.println("No arguments specified");
return;
}
String filename = args[0];
if (filename.trim().length() <= 0) {
System.out.println("Filename is empty");
return;
}
File file = new File(filename);
if (!file.exists()) {
System.out.println("File doesn't exist");
return
}
// Do what you want with the file here
}
如果您想要多个文件,可以通过将每个命令行参数分解为另一个文件来实现
public static void main(String[] args) {
if (args.length <= 0) {
System.out.println("No arguments specified");
return;
}
List<File> files = new ArrayList<>();
for (String filename : args) {
File file = new File(filename);
if (!file.exists()) {
System.out.println("File doesn't exist");
continue;
}
files.add(file);
}
// Do what you want with your list of files here
}
我正在尝试制作一个读取 .txt 文件并打印一些值的 .jar 可执行文件。 我的问题是我不想在制作 .jar 之前指定 .txt 文件名,我想将 .jar 传递给用户,每次在他 运行 .jar 之前他都会指定所需的要读取的 .txt 文件。
有什么办法吗?
您可以让用户插入文件名,程序将其添加到搜索路径中 例如:"C:\"+textname
您可以从传递给 Main 方法的字符串数组中获取命令行参数。
public static void main(String[] args) {
if (args.length <= 0) {
System.out.println("No arguments specified");
return;
}
String filename = args[0];
if (filename.trim().length() <= 0) {
System.out.println("Filename is empty");
return;
}
File file = new File(filename);
if (!file.exists()) {
System.out.println("File doesn't exist");
return
}
// Do what you want with the file here
}
如果您想要多个文件,可以通过将每个命令行参数分解为另一个文件来实现
public static void main(String[] args) {
if (args.length <= 0) {
System.out.println("No arguments specified");
return;
}
List<File> files = new ArrayList<>();
for (String filename : args) {
File file = new File(filename);
if (!file.exists()) {
System.out.println("File doesn't exist");
continue;
}
files.add(file);
}
// Do what you want with your list of files here
}