Java/Development Class/Format

Материал из Java эксперт
Перейти к: навигация, поиск

A format for String objects that is easier to persist

 
/***
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *    Project: www.simpledbm.org
 *    Author : Dibyendu Majumdar
 *    Email  : dibyendu@mazumdar.demon.co.uk
 */
import java.nio.ByteBuffer;
/**
 * A format for String objects that is easier to persist. 
 * 
 * @author Dibyendu Majumdar
 * @since 26-Jun-2005
 */
public final class ByteString implements Comparable<ByteString> {
    
    private byte[] bytes;
    
    public ByteString() {
    }
    public ByteString(String s) {
        bytes = s.getBytes();
    }
    
    public ByteString(byte[] bytes) {
        this.bytes = bytes.clone();
    }
    
    @Override
  public String toString() {
        if (bytes == null)
            return "";
        return new String(bytes);
    }
    
    public int getStoredLength() {
        return bytes.length + (Short.SIZE / Byte.SIZE);
    }
    
    public void store(ByteBuffer bb) {
        short n = 0;
        if (bytes != null) {
            n = (short) bytes.length;
        }
        bb.putShort(n);
        if (n > 0) {
            bb.put(bytes, 0, n);
        }
    }
    
    public void retrieve(ByteBuffer bb) {
        short n = bb.getShort();
        if (n > 0) {
            bytes = new byte[n];
            bb.get(bytes);
        }
        else {
            bytes = null;
        }
    }
  public int compareTo(ByteString o) {
    /*
     * FIXME: This is inefficient 
     */
    String s1 = new String(bytes);
    String s2 = new String(o.bytes);
    return s1.rupareTo(s2);
  }
  
  public int length() {
    return bytes.length;
  }
  
  public byte get(int offset) {
    return bytes[offset];
  }
}





Format Size

 
/*
 * Copyright (C) 2001-2003 Colin Bell
 * colbell@users.sourceforge.net
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
import java.io.*;
import java.text.NumberFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * General purpose utilities functions.
 *
 * @author 
 */
public class Utilities
{
  public static String formatSize(long longSize, int decimalPos)
  {
     NumberFormat fmt = NumberFormat.getNumberInstance();
     if (decimalPos >= 0)
     {
        fmt.setMaximumFractionDigits(decimalPos);
     }
     final double size = longSize;
     double val = size / (1024 * 1024);
     if (val > 1)
     {
        return fmt.format(val).concat(" MB");
     }
     val = size / 1024;
     if (val > 10)
     {
        return fmt.format(val).concat(" KB");
     }
     return fmt.format(val).concat(" bytes");
  }
}





Get Percent Value

 
/*
 * Cobertura - http://cobertura.sourceforge.net/
 *
 * Copyright (C) 2005 Jeremy Thomerson
 *
 * Note: This file is dual licensed under the GPL and the Apache
 * Source License (so that it can be used from both the main
 * Cobertura classes and the ant tasks).
 *
 * Cobertura is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by the Free Software Foundation; either version 2 of the License,
 * or (at your option) any later version.
 *
 * Cobertura is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Cobertura; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
 */

import java.text.NumberFormat;
/**
 * Abstract, not to be instantiated utility class for String functions.
 * 
 * @author Jeremy Thomerson
 */
public abstract class StringUtil
{
  /**
   * <p>
   * Replaces all instances of "replace" with "with" from the "original"
   * string.
   * </p>
   *
   * <p>
   * NOTE: it is known that a similar function is included in jdk 1.4 as replaceAll(),
   * but is written here so as to allow backward compatibility to users using SDK"s
   * prior to 1.4
   * </p>
   * 
   * @param original The original string to do replacement on.
   * @param replace The string to replace.
   * @param with The string to replace "replace" with.
   * @return The replaced string.
   */
  public static String replaceAll(String original, String replace, String with)
  {
    if (original == null)
    {
      return original;
    }
    final int len = replace.length();
    StringBuffer sb = new StringBuffer(original.length());
    int start = 0;
    int found = -1;
    while ((found = original.indexOf(replace, start)) != -1)
    {
      sb.append(original.substring(start, found));
      sb.append(with);
      start = found + len;
    }
    sb.append(original.substring(start));
    return sb.toString();
  }
  /**
   * Takes a double and turns it into a percent string.
   * Ex.  0.5 turns into 50%
   * 
   * @param value
   * @return corresponding percent string
   */
  public static String getPercentValue(double value)
  {
    //moved from HTMLReport.getPercentValue()
      value = Math.floor(value * 100) / 100; //to represent 199 covered lines from 200 as 99% covered, not 100 %
    return NumberFormat.getPercentInstance().format(value);
  }
  
}





Int format and conversion

 
/*
 * Created on Dec 27, 2005
 */
/*
 Copyright 2007 Robert C. Ilardi
 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 IntUtils {
  public static int IntLen(int i) {
    int len;
    int result;
    if (i >= 10) {
      len = 2;
      result = i / 10;
      while (result >= 10) {
        len++;
        result /= 10;
      }
    }
    else {
      len = 1;
    }
    return len;
  }
  public static byte[] IntToBytes(int i) {
    int digits, hiLimit, digit;
    byte[] bArr;
    digits = IntLen(i);
    bArr = new byte[digits];
    hiLimit = (int) Math.pow(10, digits - 1);
    for (int j = 0; j < digits; j++) {
      digit = i / hiLimit;
      bArr[j] = (byte) (48 + digit);
      i -= (digit * hiLimit);
      hiLimit /= 10;
    }
    return bArr;
  }
  public static byte[] AddZeroPadding(byte[] bArr, int fixedLen) {
    byte[] flArr;
    int cpStartIndex;
    if (bArr.length >= fixedLen) {
      flArr = bArr;
    }
    else {
      flArr = new byte[fixedLen];
      cpStartIndex = fixedLen - bArr.length;
      //Pre-pend Zeros for Padding as needed...
      for (int i = 0; i < cpStartIndex; i++) {
        flArr[i] = (byte) 48;
      }
      System.arraycopy(bArr, 0, flArr, cpStartIndex, bArr.length);
    }
    return flArr;
  }
  public static int BytesToInt(byte[] bArr) {
    int cnt = 0, num = 0;
    for (int i = bArr.length - 1; i >= 0; i--) {
      num += (bArr[i] - 48) * ((int) Math.pow(10, cnt++));
    }
    return num;
  }
  public static void main(String[] args) {
    byte[] bArr;
    int num;
    System.out.println(BytesToInt(AddZeroPadding("".getBytes(), 4)));
    System.out.println(BytesToInt(AddZeroPadding("1".getBytes(), 4)));
    System.out.println(BytesToInt(AddZeroPadding("23".getBytes(), 4)));
    System.out.println(BytesToInt(AddZeroPadding("555".getBytes(), 4)));
    System.out.println(BytesToInt(AddZeroPadding("1234".getBytes(), 4)));
    System.out.println(BytesToInt(AddZeroPadding("12345".getBytes(), 4)));
    for (int i = 0; i <= 1000000000; i++) {
      bArr = IntToBytes(i);
      num = BytesToInt(bArr);
      //System.out.println(num);
      if (num != i) {
        System.out.println(num + " != " + i);
        break;
      }
      else if (num % 1000000 == 0) {
        System.out.println(num);
      }
    }
  }
}





Make custom Input Text Formatter in Java

   
import java.awt.BorderLayout;
import java.text.ParseException;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.text.DefaultFormatter;
class MyFormatter extends DefaultFormatter {
  public MyFormatter() {
    super();
  }
  public String valueToString(Object arg0) throws ParseException {
    return super.valueToString(arg0);
  }
  public Object stringToValue(String arg0) throws ParseException {
    try {
      int value = Integer.parseInt(arg0);
      if (value >= 1 && value <= 10) {
        return "" + value;
      } else {
        return "Invalid";
      }
    } catch (Exception e) {
      return "Invalid";
    }
  }
}
public class Main extends JFrame {
  public Main() {
    JPanel panel = new JPanel();
    JLabel label = new JLabel("Number :");
    JFormattedTextField tf = new JFormattedTextField(new MyFormatter());
    tf.setColumns(10);
    panel.add(label);
    panel.add(tf);
    getContentPane().add(panel, BorderLayout.SOUTH);
    pack();
  }
  public static void main(String[] args) {
    Main mfe = new Main();
    mfe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mfe.setVisible(true);
  }
}





String Align Demo: extends Format

   
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;
public class StringAlignDemo {
  /** Demonstrate and test StringAlign class */
  public static void main(String[] argv) {
    String[] mesg = {"JavaFun", "JavaFun!" };
    for (int i=0; i<mesg.length; i++) {
      System.out.println("Input String \"" + mesg[i] + "\"");
      dump(StringAlign.JUST_LEFT, 5,
        new StringAlign(5, StringAlign.JUST_LEFT).format(mesg[i]));
      dump(StringAlign.JUST_LEFT, 10,
        new StringAlign(10, StringAlign.JUST_LEFT).format(mesg[i]));
      dump(StringAlign.JUST_CENTER, 5,
        new StringAlign(5, StringAlign.JUST_CENTER).format(mesg[i]));
      dump(StringAlign.JUST_CENTER, 10,
        new StringAlign(10, StringAlign.JUST_CENTER).format(mesg[i]));
      dump(StringAlign.JUST_RIGHT, 5,
        new StringAlign(5, StringAlign.JUST_RIGHT).format(mesg[i]));
      dump(StringAlign.JUST_RIGHT, 10,
        new StringAlign(10, StringAlign.JUST_RIGHT).format(mesg[i]));
    }
  }
  private static void dump(int format, int len, String s) {
    System.out.print((char)format + "[" + len + "]");
    System.out.print(" ==> \"");
    System.out.print(s);
    System.out.print(""");
    System.out.println();
  }
}
/** Bare-minimum String formatter (string aligner).
 * XXX When 1.5 is common, change from ints to enum for alignment.
 */
class StringAlign extends Format {
  /* Constant for left justification. */
  public static final int JUST_LEFT = "l";
  /* Constant for centering. */
  public static final int JUST_CENTRE = "c";
  /* Centering Constant, for those who spell "centre" the American way. */
  public static final int JUST_CENTER = JUST_CENTRE;
  /** Constant for right-justified Strings. */
  public static final int JUST_RIGHT = "r";
  /** Current justification */
  private int just;
  /** Current max length */
  private int maxChars;
    /** Construct a StringAlign formatter; length and alignment are
     * passed to the Constructor instead of each format() call as the
     * expected common use is in repetitive formatting e.g., page numbers.
     * @param nChars - the length of the output
     * @param just - one of JUST_LEFT, JUST_CENTRE or JUST_RIGHT
     */
  public StringAlign(int maxChars, int just) {
    switch(just) {
    case JUST_LEFT:
    case JUST_CENTRE:
    case JUST_RIGHT:
      this.just = just;
      break;
    default:
      throw new IllegalArgumentException("invalid justification arg.");
    }
    if (maxChars < 0) {
      throw new IllegalArgumentException("maxChars must be positive.");
    }
    this.maxChars = maxChars;
  }
  /** Format a String.
     * @param input _ the string to be aligned.
     * @parm where - the StringBuffer to append it to.
     * @param ignore - a FieldPosition (may be null, not used but
     * specified by the general contract of Format).
     */
  public StringBuffer format(
    Object obj, StringBuffer where, FieldPosition ignore)  {
    String s = (String)obj;
    String wanted = s.substring(0, Math.min(s.length(), maxChars));
    // Get the spaces in the right place.
    switch (just) {
      case JUST_RIGHT:
        pad(where, maxChars - wanted.length());
        where.append(wanted);
        break;
      case JUST_CENTRE:
        int toAdd = maxChars - wanted.length();
        pad(where, toAdd/2);
        where.append(wanted);
        pad(where, toAdd - toAdd/2);
        break;
      case JUST_LEFT:
        where.append(wanted);
        pad(where, maxChars - wanted.length());
        break;
      }
    return where;
  }
  protected final void pad(StringBuffer to, int howMany) {
    for (int i=0; i<howMany; i++)
      to.append(" ");
  }
  /** Convenience Routine */
  String format(String s) {
    return format(s, new StringBuffer(), null).toString();
  }
  /** ParseObject is required, but not useful here. */
  public Object parseObject (String source, ParsePosition pos)  {
    return source;
  }
}





The # symbol shows a digit or nothing if no digit present

   
import java.text.DecimalFormat;
import java.text.Format;
public class Main {
  public static void main(String[] argv) throws Exception {
    Format formatter = new DecimalFormat("##");
    String s = formatter.format(-1234.567);
    System.out.println(s);
    s = formatter.format(0);
    System.out.println(s);
  }
}