import java.io.*;public class Copy {
  /** Main method
     @param args[0] for sourcefile
     @param args[1] for target file
   */
  public static void main(String[] args) throws IOException {
    // Check command line parameter usage
    if (args.length != 2) {
      System.out.println(
        "Usage: java CopyFile sourceFile targetfile");
      System.exit(0);
    }    // Check if source file exists
    File sourceFile = new File(args[0]);
    if (!sourceFile.exists()) {
       System.out.println("Source file " + args[0] + " not exist");
       System.exit(0);
    }    // Check if target file exists
    File targetFile = new File(args[1]);
    if (targetFile.exists()) {
      System.out.println("Target file " + args[1] + " already exists");
      System.exit(0);
    }    // Create an input stream
    BufferedInputStream input =
      new BufferedInputStream(new FileInputStream(sourceFile));    // Create an output stream
    BufferedOutputStream output =
      new BufferedOutputStream(new FileOutputStream(targetFile));    // Display the file size
    System.out.println("The file " + args[0] + " has "+
      input.available() + " bytes");    // Continuously read a byte from input and write it to output
    int r;
    while ((r = input.read()) != -1)
      output.write((byte)r);    // Close streams
    input.close();
    output.close();    System.out.println("Copy done!");
  }
}上面的代码中:
 if (args.length != 2) {
      System.out.println(
        "Usage: java CopyFile sourceFile targetfile");
      System.exit(0);
    }此段代码的意义何在,很是费解。求解答

解决方案 »

  1.   

    判断调用此main函数的输入参数,如果个数不是2个,则打出log,退出。
    因为拷贝起码需要有输入输出文件,2个路径。
      

  2.   

    写的要规范啊package Char12;import java.io.*;
    import java.util.Scanner;
    public class FileCopyDemo {
    public static void main(String args[]) throws IOException{
    Scanner cin = new Scanner(System.in);
    String path1 = null,path2 = null;
    while(cin.hasNext()){
    path1 = cin.next();
    path2 = cin.next();
    break;
    }
    File fs = new File(path1);
    File fd = new File(path2);
    if(!fd.exists()){
    System.out.println("要复制的文件不存在,请重新输入文件的路径");
    System.exit(1);
    }
    OutputStream os = null;
    InputStream is  = null;
    os = new FileOutputStream(fs);
    is = new FileInputStream(fd);
    if(os!=null && is!=null){
    int temp = 0;
    while((temp=is.read())!=-1){
    os.write((byte)temp);
    }
    System.out.println("复制成功!");
    is.close();
    os.close();
    }
    else{
    System.out.println("复制失败");
    }
    }
    }
      

  3.   

    String[] args 是数组
    如果args.length 为 0 or 1 ,那么args[0],args[1]会报数组越界的错误、
    如果args.length 大于 2 ,程序不会报错,只不过前2个arg是有效的,后面的是无用的
    加了if (args.length != 2)可以保证参数的数目是符合程序要求的
    lz可以试试只输一个arg,然后把if (args.length != 2)一段给删了,应该会报错
      

  4.   

    我使用的eclipse,也就是说需要在cmd中,用这样的命令。
    java copy t1.java t2.java
    这样的话,args是自动接收t1和t2的?
      

  5.   

     public static void main(String args[]),,,,,args在此,,,