Mega Code Archive

 
Categories / Java / Data Type
 

Truncates large Strings showing a portion of the Strings head and tail with the center cut out and replaced with

/*  *  Licensed to the Apache Software Foundation (ASF) under one  *  or more contributor license agreements.  See the NOTICE file  *  distributed with this work for additional information  *  regarding copyright ownership.  The ASF licenses this file  *  to you under the Apache License, Version 2.0 (the  *  "License"); you may not use this file except in compliance  *  with the License.  You may obtain a copy of the License at  *    *    http://www.apache.org/licenses/LICENSE-2.0  *    *  Unless required by applicable law or agreed to in writing,  *  software distributed under the License is distributed on an  *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY  *  KIND, either express or implied.  See the License for the  *  specific language governing permissions and limitations  *  under the License.   *    */ /**  * Various string manipulation methods that are more efficient then chaining  * string operations: all is done in the same buffer without creating a bunch of  * string objects.  *   * @author <a href="mailto:dev@labs.apache.org">Dungeon Project</a>  */ public class Main {   /**    * Truncates large Strings showing a portion of the String's head and tail    * with the center cut out and replaced with '...'. Also displays the total    * length of the truncated string so size of '...' can be interpreted.    * Useful for large strings in UIs or hex dumps to log files.    *     * @param str    *            the string to truncate    * @param head    *            the amount of the head to display    * @param tail    *            the amount of the tail to display    * @return the center truncated string    */   public static final String centerTrunc( String str, int head, int tail )   {       StringBuffer buf = null;       // Return as-is if String is smaller than or equal to the head plus the       // tail plus the number of characters added to the trunc representation       // plus the number of digits in the string length.       if ( str.length() <= ( head + tail + 7 + str.length() / 10 ) )       {           return str;       }       buf = new StringBuffer();       buf.append( '[' ).append( str.length() ).append( "][" );       buf.append( str.substring( 0, head ) ).append( "..." );       buf.append( str.substring( str.length() - tail ) );       buf.append( ']' );       return buf.toString();   } }