使用来自 Windows cmd 的参数启动 java 应用程序?

Launch a java application with parameters from Windows cmd?

对不起,我的英语说得不太好..:)

当我想从 windows cmd 启动一个 java 项目时,我会这样做:

javac main.java(main = 我的文件名)

然后:java main

但是如果我使用参数,我该怎么办?

我试过了:java main parameters但效果不佳。

你有想法吗?

非常感谢您的帮助:)

Image

这里有代码:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import elements.*;

public class Main
{
    public static void main(String[] parameters)
    {
        try
        {
            String nameFile = parameters[0];
            FileInputStream fileInputStream = new FileInputStream(new File(nameFile));
            Processing processing = new Processing();
            processing.read(fileInputStream);
            try 
            {
                fileInputStream.close();
            } 
            catch (IOException exception) 
            {
                System.out.println("Une erreur s'est produite lors de la fermeture de l'InputStream");
            }
        }
        catch(FileNotFoundException exeption)
        {
            System.out.println("Le nom de fichier placé en paramètre est incorrect");
        }
    }
}

问题是第 14 行:String nameFile = parameters[0];

看起来您可以读取参数,但您收到了 FileNotFoundException。按照您读取文件的方式,exercice4.txt 应该出现在您的 src 文件夹中,否则您当前的代码将无法读取它。传递文件的完整路径或更新您的代码

好吧,代码似乎是正确的,但可以肯定它不会工作,因为该文件不在您 运行 java blah blah 命令所在的目录中。尝试 运行宁

java Main ..\exercice4.txt

顺便说一句,这种问题通常很容易通过一些打印语句进行调试,例如:

String nameFile = parameters[0];
System.out.println("Trying to open file "+nameFile);
FileInputStream fileInputStream = new FileInputStream(new File(nameFile));

此外,当出现异常时,显示异常堆栈跟踪也很有用,例如:

catch(FileNotFoundException exeption)
{
    System.out.println("Le nom de fichier placé en paramètre est incorrect");
    exeption.printStackTrace();
}