集册 Java实例教程 将给定数组截断为请求长度。

将给定数组截断为请求长度。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

490
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
将给定数组截断为请求长度。


//package com.nowjava;


public class Main {
/*来自 
 时 代 J a v a 公 众 号 - N o w J a v  a . c o m*/

    public static void main(String[] argv) throws Exception {

        byte[] array = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };

        int newLength = 2;

        System.out.println(java.util.Arrays.toString(truncate(array,

                newLength)));

    }


    /**

     * Truncates the given array to the request length.

     * 

     * @param array

     *            the array to be truncated.

     * @param newLength

     *            the new length in bytes.

     * @return the truncated array.

     */

    public static byte[] truncate(byte[] array, int newLength) {

        if (array.length < newLength) {

            return array;

        } else {

            byte[] truncated = 
展开阅读全文