Luinithil
Luinithil

Reputation: 63

Java args command line parameter-- trying to pass filename as parameter in args to a method but not working

I'm fairly new to Java. Currently trying to have the filename given in args[] passed to this FileReader but when I compile it says it can't find the specified file. If I hardcode the filename it works fine. How's this supposed to work?

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

}

Upvotes: 0

Views: 14669

Answers (3)

Kal
Kal

Reputation: 24910

Your args parameter is not visible to parseCommands.

Plus args is an array. You probably want to send the first element in that array to 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]);
  }

Upvotes: 1

bdabmxican
bdabmxican

Reputation: 41

For one thing, you don't need to create an object to call a function if you're in the object already. Second, pass the args as a parameter to your split function.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1504052

You've only given pseudo-code to start with, but fundamentally you need to learn about the different types of variable in Java.

args in main is a parameter - it's local to that method. If you want another method to be able to use its value then either you need to store that value in a shared variable (e.g. a static or instance variable) or you need to pass it as an argument to the method which needs it.

For example:

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

(At the moment you could also make parseCommands a static method and then call it without creating an instance of StringSplit, btw...)

Upvotes: 5

Related Questions