该段代码报索引越界异常的原因是在读取文件内容并写入目标文件时,使用了错误的长度参数。在循环中,通过调用in.read()方法读取数据,并将返回的长度赋值给变量length。然后,将读取到的数据通过out.write(chars, 0, length)方法写入目标文件。

然而,在代码中定义的char数组chars的长度为1024,而每次读取数据时,只将length设置为单个字符的长度。因此,在写入目标文件时,使用的长度参数length实际上是错误的,超过了有效数据的长度。这导致了索引越界异常的发生。

要解决这个问题,应该将读取到的数据存储在char数组中,并将数组的有效长度作为写入目标文件时的长度参数。修改代码如下:

public class StreamCopyDemo {

public static void main(String[] args) throws IOException {

    FileReader in = new FileReader("D:\\powernode\\IOStream\\src\\Files\\CopyBeFore.txt");
    FileWriter out = new FileWriter("D:\\powernode\\IOStream\\src\\Files\\CopyAfter.txt");

    char[] chars = new char[1024];

    int length = 0;
    while ((length = in.read(chars)) != -1) {
        System.out.println(length);
        out.write(chars, 0, length);
    }
    out.close();
    in.close();
}

}

这样修改后,每次读取到的数据都会存储在char数组中,并且有效数据的长度作为写入目标文件时的长度参数,解决了索引越界异常的问题

package StreamCopy;import javaioFileReader;import javaioFileWriter;import javaioIOException;public class StreamCopyDemo public static void mainString args throws IOException FileReader in

原文地址: https://www.cveoy.top/t/topic/iqN0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录