Here you can find the source of ellipsizeKeepingExtension(String s, int maxChars)
public static String ellipsizeKeepingExtension(String s, int maxChars)
//package com.java2s; /*/*from w ww.j a v a 2 s . co m*/ Copyright (C) 2012 The Stanford MobiSocial Laboratory Licensed 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. */ public class Main { /** converts a very long name.doc -> a very lon...g.doc. * tries to fit s into maxChars, with a best effort to keep the extension */ public static String ellipsizeKeepingExtension(String s, int maxChars) { if (s.length() <= maxChars) return s; int idx = s.lastIndexOf("."); if (idx <= 0) return ellipsize(s, maxChars); // no extension int MAX_EXTENSION_LENGTH = 6; if (s.length() - idx > MAX_EXTENSION_LENGTH) return ellipsize(s, maxChars); // unusually long "extension", don't what's happening, play it safe by ignoring it // keep everything from one char before the . till the end, String tail = s.substring(idx - 1); // tail is [idx-1 to s.length] int maxCharsRemaining = maxChars - tail.length(); return ellipsize(s.substring(0, idx - 1), maxCharsRemaining) + tail; } public static String ellipsize(String s, int maxChars) { if (s == null) return null; if (maxChars < 4) return (s.substring(0, maxChars)); if (s.length() > maxChars) return s.substring(0, maxChars - 3) + "..."; else return s; } }