package cn.ksource.core.test; import java.io.File; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import cn.ksource.core.util.ConvertUtil; public class TestUtil { public static void main(String[] args) { for (int i = 0; i < 100; i++) { System.out.println(getRandomEnglishCharacters(6, 26)); } } /** * 获取英文随机数 * @param minLength * @param maxLength * @return * @version V1.0.0 * @author 杨凯 * @date Jun 8, 2014 5:24:44 PM */ public static String getRandomEnglishCharacters(int minLength, int maxLength){ String content = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; String result = ""; int length = getRandom(minLength, maxLength); int contentLength = content.length(); int start = getRandom(0, contentLength-length); result = content.substring(start, start+length); return result; } /** * 获得指定长度的随机汉字 * @param minLength * @param maxLength * @return * @version V1.0.0 * @author 杨凯 * @date Jun 8, 2014 5:17:02 PM */ public static String getRandomChineseCharacters(int minLength,int maxLength){ String filePath = TestUtil.class.getResource("/cn/ksource/core/test/")+"test_text.txt"; String content = ""; String truePath = StringUtils.removeStart(filePath, "file:/"); String result = ""; try { content = FileUtils.readFileToString(new File(truePath), "utf-8"); int length = getRandom(minLength, maxLength); int contentLength = content.length(); int start = getRandom(0, contentLength-length); result = content.substring(start, start+length); } catch (Exception e) { e.printStackTrace(); } return result; } /** * 获取随机数 * @param max * @return * @version V1.0.0 * @author 杨凯 * @date Jun 8, 2014 4:45:47 PM */ public static int getRandom(int min,int max){ for (int i = 0; i < 100000; i++) { double random = Math.random(); int num = ConvertUtil.obj2Int(String.valueOf(random * max)); if (num < max && num > min) { return num; } } return 0; } }