2016-02-27 171 views
0

我正在为其中一个类的项目工作。而这个程序本身并不是问题,而是它将被测试的方式。我没有使用命令行的经验,这就是我的程序将如何测试。从命令行编译并运行java

我创建了一个小山密码程序。输入是一个密钥文件和一个纯文本文件。 命令行条目将如下所示。

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

我该怎么做?我可以修改此代码,以便它可以使用上述命令吗?

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."); 

    } 

回答

0

程序需要一个微小的改动:

  • class.getResource()只会扫描类路径中的文件。要读取外部文件,我们可以使用带有字符串参数的文件构造函数。例如。 File file = new File(args[0]);
  • 在运行程序的参数需要将改为全路径(如java hillcipher "D:/spr16Key4.txt" "D:/hill-16spring-01"这样程序就可以,即使他们不在同一个目录中的类文件中读取文件。
0

您可以为处理您的文件的内容的常用方法对于执行以下操作:

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

为了运行它,只是做你所提到的,考虑到该文件路径:

>java HillCipher key_file.txt plain_file.txt