main(String args[]) args数组为存储命令行传递进去的参数,如下例子
package findfile; import java.io.File; import java.util.ArrayList; public class FindFile{ public ArrayList<String> fileList = new ArrayList<String>(); // 在pathName文件夹下查找文件名为fileName的文件,结果存入fileList public void findFiles( String pathName, String fileName){ File f=new File( pathName ); if( !f.isDirectory() || fileName.equals("")) return; File [] subFiles = f.listFiles(); if( subFiles==null ) return; for(int i=0; i<subFiles.length; i++){ if( subFiles[i].isFile() ) { if( subFiles[i].getName().equalsIgnoreCase(fileName) ) fileList.add( subFiles[i].getPath() ); } else findFiles( subFiles[i].getPath(), fileName ); } } /*public static void main( String [] args){ FindFile ff= new FindFile(); ff.findFiles("D://ttt", "student1.txt"); for(int i=0; i<ff.fileList.size(); i++) System.out.println( ff.fileList.get(i)); }*/ }
import java.util.Scanner; import java.io.*; import findfile.*; public class TestIO{ public static void main(String []args){ String dirName, fileName; if( args.length<2 ) return; dirName=args[0]; fileName=args[1]; FindFile ff= new FindFile(); ff.findFiles(dirName, fileName); if( ff.fileList.size()>0) try { Scanner sc = new Scanner( new FileInputStream(ff.fileList.get(0).toString())); String name, id; Student studentList[ ] = new Student[ 100 ]; float math, chi; int i=0; while( sc.hasNext()) { name=sc.next(); id = sc.next(); math = sc.nextFloat(); chi= sc.nextFloat(); studentList[i]=new Student( name, id, math, chi); studentList[i].calTotal(); studentList[i].calAverage(); i++; } int n=i; Student.sort(studentList ,n ); for( i=0; i< n; i++) System.out.printf("%10s%15s%10.2f%10.2f%10.2f%10.2f/n", studentList[i].name, studentList[i].id,studentList[i].math, studentList[i].chi, studentList[i].average, studentList[i].total); }catch( IOException e){ e.printStackTrace(); } System.exit(0); } } class Student{ String name, id; float math, chi, average, total; public Student(String name, String id, float math, float chi){ this.name=name; this.id=id; this.math=math; this.chi=chi; } public void calTotal(){ total=math+chi; } public void calAverage(){ average=(math+chi)/2; } public static void sort( Student st[], int n){ int i,j,k; Student temp; for( i=0; i<n-1; i++){ k=i; for(j=i+1; j<n; j++) if( st[j].total>st[k].total ) k=j; if( k!=i){ temp=st[k]; st[k]=st[i]; st[i]=temp; } } } }
在项目上右击 Run As->Run Configurations...->Arguments->在Program arguments:的文本框中输入你要传入的参数,若有几个参数则在参数间空格就行。然后点击Run按钮。
例如有两个参数:args[0]和args[1]分别为文件路劲和文件名称D:/java student.txt(student.txt为欲读取的文件)
只需在Arguments中输入D:/java student.txt即可