读书人

关于JAVA中复制文件的有关问题

发布时间: 2012-04-28 11:49:53 作者: rapoo

关于JAVA中复制文件的问题。
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);
}

此段代码的意义何在,很是费解。求解答



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

读书人网 >J2SE开发

热点推荐