将ArrayIndexOutOfBoundsException扫描文件获取到字节数组

时间:2019-03-07 06:22:24

标签: java

写入文件字节数组时,像java.net.SocketException这样的异常:软件导致连接中止:套接字写入错误java.lang.ArrayIndexOutOfBoundsException:512

returnValue=1;
File file = new File(filename);
    fileLength = file.length();

connect(servername);

private int connect(String host) throws IOException {
    int response = 0;
    if (socket == null) {
        InetAddress ipAddress = InetAddress.getByName(host);
        socket = new Socket(ipAddress, port);
        output = new DataOutputStream(socket.getOutputStream());
        input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }
    return response;
}

byte[] b = convert();

private byte[] convert() throws IOException {
    File file = new File(filename);
    try (InputStream is = new FileInputStream(file)) {
        long alength = 0;
        alength = file.length();
        bytes = new byte[(int) alength];
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }

    } catch (IOException io) {
        return new byte[0];
    }
    return bytes;
}

// Writing Byte Array

output.write(b,0,4);
  output.write(b, 4, ( (int) fileLength)); //exactly here i am facing error  

1 个答案:

答案 0 :(得分:0)

尝试一下:

returnValue=1;
File file = new File(filename);
    fileLength = file.length();

connect(servername);

private int connect(String host) throws IOException {
    int response = 0;
    if (socket == null) {
        InetAddress ipAddress = InetAddress.getByName(host);
        socket = new Socket(ipAddress, port);
        output = new DataOutputStream(socket.getOutputStream());
        input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }
    return response;
}

byte[] b = convert();

private byte[] convert() throws IOException {
    File file = new File(filename);
    try (InputStream is = new FileInputStream(file)) {
        long alength = 0;
        alength = file.length();
        bytes = new byte[(int) alength];
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }

    } catch (IOException io) {
        output.write(b,0,4);
        return new byte[0];
    }
    return bytes;
}

// Writing Byte Array
  output.write(b, 4, ( (int) fileLength)); //exactly here i am facing error