繁体   English   中英

从Windows cmd启动带有参数的Java应用程序?

[英]Launch a java application with parameters from Windows cmd?

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

当我想从Windows cmd启动Java项目时,我会这样做:

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

然后: java main

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

我试过了: java main parameters但是不好。

你有主意吗

非常感谢您的帮助 :)

图片

这里是代码:

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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM