【问题标题】:Java args command line parameter-- trying to pass filename as parameter in args to a method but not workingJava args 命令行参数 - 尝试将文件名作为 args 中的参数传递给方法但不起作用
【发布时间】:2012-01-27 00:23:25
【问题描述】:

我对 Java 还很陌生。目前试图将 args[] 中给出的文件名传递给这个 FileReader,但是当我编译它时说它找不到指定的文件。如果我对文件名进行硬编码,它可以正常工作。这应该如何工作?

public class StringSplit
{

   public void parseCommands
   {
     try
     {
       //not working, why? It works if I do FileReader fr= new FileReader("hi.tpl").
       FileReader fr= new FileReader(args);

     }

 public static void main (String[] args)// args holds the filename to be given to FileReader
 {
  if (args.length==0)
   {
     System.out.println("Error: Bad command or filename. Syntax: java [filename.tpl]);
     System.exit(0)
   }
   StringSplit ss= new StringSplit();
   ss.parseCommands();
  }

}

【问题讨论】:

    标签: java command-line-arguments


    【解决方案1】:

    一开始你只给出了伪代码,但基本上你需要了解 Java 中不同类型的变量。

    args in main 是一个参数 - 它是该方法的本地参数。如果您希望另一个方法能够使用它的值,那么您需要将该值存储在共享变量(例如静态或实例变量)中,或者您需要将其作为参数传递给需要它的方法。

    例如:

    public class StringSplit
    {
      public void parseCommands(String[] files)
      {
        try
        {
          FileReader fr= new FileReader(files[0]);
    
        }
        // Rest of code
     }
    
     public static void main (String[] args)
     {
        if (args.length==0)
        {
          System.out.println("...");
          System.exit(0)
        }
        StringSplit ss= new StringSplit();
        ss.parseCommands(args);
      }
    }
    

    (目前您还可以将parseCommands 设为静态方法,然后在不创建StringSplit 实例的情况下调用它,顺便说一句...)

    【讨论】:

      【解决方案2】:

      您的 args 参数对 parseCommands 不可见。

      加上 args 是一个数组。您可能希望将该数组中的第一个元素发送到 parseCommands。

      public void parseCommands(String fileName)
         {
           try
           {
             //not working, why? It works if I do FileReader fr= new FileReader("hi.tpl").
             FileReader fr= new FileReader(fileName);
      
           }
        }
      
      public static void main (String[] args)// args holds the filename to be given to FileReader
       {
        if (args.length==0)
         {
           System.out.println("Error: Bad command or filename. Syntax: java [filename.tpl]);
           System.exit(0)
         }
         StringSplit ss= new StringSplit();
         ss.parseCommands(args[0]);
        }
      

      【讨论】:

        【解决方案3】:

        一方面,如果您已经在对象中,则无需创建对象来调用函数。其次,将 args 作为参数传递给您的 split 函数。

        【讨论】:

          猜你喜欢
          • 2018-07-23
          • 2012-12-21
          • 2022-11-02
          • 2010-12-11
          • 2015-09-12
          • 2023-04-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多