Java NIO byte array concatenation

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;
                                //The following code is the key point!!!!!!!!
				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;
	}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326213681&siteId=291194637