简体   繁体   English

从命令行Java编译并运行

[英]Compiling and running from the command line java

I'm working on a project for one of my classes. 我正在为我的一个班级做一个项目。 And the program its self is not so much the problem as is way that it will be tested. 而且程序本身并不是问题,而是要通过测试的方式。 I have no experience working with the command line, and that is how my program will be test. 我没有使用命令行的经验,这就是测试程序的方式。

I created a hill cipher program. 我创建了一个希尔密码程序。 The inputs are a key file and a plaintext file. 输入是密钥文件和纯文本文件。 The command line entry will look like this. 命令行条目将如下所示。

prompt> java hillcipher spr16Key4.txt hill-16spring-01

How can I do this? 我怎样才能做到这一点? Can I modify this code so that it will work with the above command? 我可以修改此代码,使其与上面的命令一起使用吗?

try{ 
        //open plaintext file
        URL url = getClass().getResource("input.txt"); //.getResource(args[0]);?
        File file = new File(url.getPath());
        //used to move data on the encryption path
        sc  = new Scanner(file);

        }catch(Exception e){

        System.out.println("file not found.");

    }

The program needs a couple of minor changes: 该程序需要进行一些小的更改:

  • class.getResource() will only scan for the file in class path. class.getResource()将仅扫描类路径中的文件。 To read the external file, we can use the file constructor that takes a string argument. 要读取外部文件,我们可以使用带有字符串参数的文件构造函数。 Eg File file = new File(args[0]); 例如File file = new File(args[0]);
  • The arguments while running the program need to be changed to full paths (like java hillcipher "D:/spr16Key4.txt" "D:/hill-16spring-01" so that the program would be able to read the files even if they are not in the same directory as class file. 运行程序时需要将参数更改为完整路径(例如java hillcipher "D:/spr16Key4.txt" "D:/hill-16spring-01"以便程序即使它们是与类文件不在同一目录中。

You can create a common method for processing the contents of your file. 您可以创建用于处理文件内容的通用方法。 For that do the following: 为此,请执行以下操作:

public class HillCipher {
    public static void main(String[] args) {
        String keyFile = args[0];
        String plainFile = args[1];

        // Read your key file
        processFile(keyFile);

        // Read plain file
        processFile(plainFile);
    }

    private static void processFile(String filePath) {
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line = br.readLine();

            while (line != null) {
                // do what you need with the file contents
                System.out.println(line);
                line = br.readLine();
            }
        }
    }
}

In order to run it, just do what you mentioned, taking into account the file paths: 为了运行它,只需考虑您的文件路径就可以做到:

>java HillCipher key_file.txt plain_file.txt

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

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