我知道这段代码在 Eclipse 中会产生一个错误,但是我如何在它出现之前捕获它
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at ArgsContentCopier.main(ArgsContentCopier.java:13)
我想抓住它,然后抛出一个字符串。而不是说线程中的异常......我希望它说例如“需要两个参数”。
感谢您的帮助,我想通了!
import java.io.*;
import java.util.Scanner;
/**
This program copies content of a file into another.
*/
public class ArgsContentCopier
{
public static void main(String[] args)
{
if(args.length != 2) //if args array != 2 then print error
{
System.out.println("Error: Two args required");
}
else{
String one = args[0];
String two = args[1];
String inFile;
String outFile;
Scanner in = new Scanner(System.in);
try
{
//System.out.print("Input file: ");
inFile = one;
//System.out.print("Output file: ");
outFile = two;
InputStream inStream = new FileInputStream(inFile);
OutputStream outStream = new FileOutputStream(outFile);
byte[] b = new byte[1024]; //this line reads a new byte into b from 0 to 1024bytes.
int len; //keeps track of the len (up to the # of bytes to read)
while((len = inStream.read(b)) != -1) //if there is nothing else to read, returns -1
{
outStream.write(b, 0, len); //read the docs on this http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read%28byte[],%20int,%20int%29
}
inStream.close();
outStream.close();
}
catch (IOException exception)
{
System.out.println("Error processing file: " + exception);
}
}
}
}