2012-01-26 2 views
0

저는 Java를 처음 접했습니다. 현재 args []에 주어진 파일 이름을이 FileReader에 전달하려고 시도하지만 컴파일 할 때 지정된 파일을 찾을 수 없다고 말합니다. 파일 이름을 하드 코딩하면 제대로 작동합니다. 어떻게이 일을해야 하죠?Java args 명령 줄 매개 변수 - args의 매개 변수로 filename을 메서드로 전달하려고 시도하지만 작동하지 않습니다.

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

} 

답변

1

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]); 
    } 
+0

감사합니다. – Luinithil

5

처음부터 의사 코드를 제공했지만 근본적으로 Java의 다양한 변수 유형에 대해 알아야합니다. main에서

args매개 변수 - 그것은 그 방법에 대해 로컬입니다. 다른 메소드가 값을 사용할 수있게하려면 해당 값을 공유 변수 (예 : 정적 또는 인스턴스 변수)에 저장해야하며 그렇지 않으면이를 필요로하는 메소드에 인수로 전달해야합니다. 예를 들어

:

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 정적 메서드를 만들 수있는 다음 BTW, StringSplit의 인스턴스를 생성하지 않고 호출 ...) 한 가지를 들어

0

, 이미 객체에 있다면 함수를 호출하기 위해 객체를 생성 할 필요가 없습니다. 둘째, args를 매개 변수로 split 함수에 전달하십시오.

+0

메인은 정적 메서드입니다. - parseCommands는 아닙니다. –