Java NIO byte数组拼接

public static byte[] readFile (String filePath, int bufsize){
		
		byte[] retval = null;
		try {
			RandomAccessFile raf = new RandomAccessFile(filePath, "rw");
			FileChannel inChannel = raf.getChannel();
			ByteBuffer buf = ByteBuffer.allocate(bufsize);
			int byteRead = inChannel.read(buf);
			int readLength = 0;
			while (byteRead != -1){
				buf.flip();
				byte[] tempval = null;
                                //以下代码划重点!!!!!!!!
				if (retval == null){
					retval = new byte[byteRead];
				}else{
					tempval = retval;
					readLength = tempval.length;
					retval = new byte[readLength+byteRead];
					System.arraycopy(tempval, 0, retval, 0, tempval.length);
				}
				int i = readLength;
				while (buf.hasRemaining()){
					byte b = buf.get();
					retval[i] = b;
					i++;
				}
				buf.clear();
				byteRead = inChannel.read(buf);
			}
			raf.close();
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return retval;
	}

 

你可能感兴趣的:(java)