注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

放飞自由

年轻人,如果三年的时间里,没有任何想法,他这一生,就基本这个样子,没有多大改变。

 
 
 

日志

 
 

StringUtil常用字符串(三) 网易博客字数限制,接上一篇文章  

2013-06-10 23:38:25|  分类: JAVA后台 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

/**
* 获取文件图标名. Date: 2005-10
*
* @param application
* JSP/Servlet 的 ServletContext
* @param iconDirPath
* 图标文件夹的路径
* @param fileName
* 需要处理的文件名
* @return 图标文件相对路径
*/
public static String getFileIcon(ServletContext application,
String iconDirPath, String fileName) {
String ext = getExtension(fileName);
String filePath = iconDirPath + ext + ".gif";
// return filePath;

if (checkFileExists(application, filePath)) {
return filePath;
}
return iconDirPath + "file.gif";
}

/**
* 输出分页显示的结果.
*
* @param page
* 当前页面
* @param recordCount
* 所有结果
* @param pageSize
* 一页显示的多少
* @param pageCountSize
* 前后跳页的多少
* @param linkpageurl
* 连接页面的 URL 字符串
* @return 分页结果的字符串.
*/
public static String paging(int page, int recordCount, int pageSize,
int pageCountSize, String linkpageurl) {
int PageCount = -1; // 页面总数
String LinkPageName = linkpageurl;
String LinkText = "";
int StartPage;
int TempPage;
int TempPageCount;
TempPage = (page - 1) % pageCountSize; // 唱赣瘤 备窃
StartPage = page - TempPage; // 矫累 其捞瘤 备窃
TempPageCount = recordCount % pageSize;
if (TempPageCount == 0) {
PageCount = recordCount / pageSize;
} else {
PageCount = (recordCount / pageSize) + 1; // 傈眉 其捞瘤 荐
}
String txtPrev = " [前" + pageCountSize + "页] ";
String txtNext = " [后" + pageCountSize + "页] ";
String txtStart = " [首页] ";
String txtEnd = " [末页] ";
// 贸澜栏肺
if (StartPage - 1 > 0) {
LinkText += "<a href='http://houzhiqingjava.blog.163.com/blog/" + LinkPageName + "&page=1' title='到此页'>"
+ txtStart + "</a>";
} else {
LinkText += txtStart;
}
// 捞傈 10俺..
if (StartPage - 1 > 0) {
LinkText += "<a href='http://houzhiqingjava.blog.163.com/blog/" + LinkPageName + "&page=" + (StartPage - 1)
+ "' title='到第" + pageCountSize + "页'>" + txtPrev + "</a>";
} else {
LinkText += txtPrev;
}
for (int i = StartPage; i < StartPage + pageCountSize; i++) {
if (i < PageCount + 1) {
LinkText += "<a href='http://houzhiqingjava.blog.163.com/blog/" + LinkPageName + "&page=";
LinkText += i + "' title='" + i + "页'>";
if (i == page) {
LinkText += "<b>[" + i + "]</b>";
} else {
LinkText += "[" + i + "]";
}
LinkText += "</a>";
}
}
// 中间页面
if (StartPage + pageCountSize - PageCount - 1 < 0) {
LinkText += "<a href='http://houzhiqingjava.blog.163.com/blog/" + LinkPageName + "&page="
+ (StartPage + pageCountSize) + "' title='到第"
+ pageCountSize + "页'>" + txtNext + "</a>";
} else {
LinkText += txtNext;
}
// 最后一页
if (StartPage + pageCountSize <= PageCount) {
LinkText += "<a href='http://houzhiqingjava.blog.163.com/blog/" + LinkPageName + "&page=" + PageCount
+ "' title='最后一页'>" + txtEnd + "</a>";
} else {
LinkText += txtEnd;
}
return LinkText;
}

/**
* Gets the absolute pathname of the class or resource file containing the
* specified class or resource name, as prescribed by the current classpath.
*
* @param resourceName
* Name of the class or resource name.
* @return the absolute pathname of the given resource
*/
public static String getPath(String resourceName) {

if (!resourceName.startsWith("/")) {
resourceName = "/" + resourceName;
}

// resourceName = resourceName.replace('.', '/');

java.net.URL classUrl = new StringUtils().getClass().getResource(
resourceName);

if (classUrl != null) {
// logger.debug("\nClass '" + className +
// "' found in \n'" + classUrl.getFile() + "'");
// logger.debug("\n资源 '" + resourceName +
// "' 在文件 \n'" + classUrl.getFile() + "' 中找到.");

return classUrl.getFile();
}
// logger.debug("\nClass '" + className +
// "' not found in \n'" +
// System.getProperty("java.class.path") + "'");
// logger.debug("\n资源 '" + resourceName +
// "' 没有在类路径 \n'" +
// System.getProperty("java.class.path") + "' 中找到");
return null;
}

// -----------------------------------------------------------
// ---------- 字符串和数字转换工具方法, 2004.03.27 添加 --------
// ------------------------------------------------------------
public static byte getByte(HttpServletRequest httpservletrequest, String s) {
if (httpservletrequest.getParameter(s) == null
|| httpservletrequest.getParameter(s).equals("")) {
return 0;
}
return Byte.parseByte(httpservletrequest.getParameter(s));
}

/**
* Reading a parameter as integer from the http servlet request.
*
*/
public static int getInt(HttpServletRequest httpservletrequest, String s) {
if (httpservletrequest.getParameter(s) == null
|| httpservletrequest.getParameter(s).equals("")) {
return 0;
}
return Integer.parseInt(httpservletrequest.getParameter(s));
}

public static long getLong(HttpServletRequest httpservletrequest, String s) {
if (httpservletrequest.getParameter(s) == null
|| httpservletrequest.getParameter(s).equals("")) {
return 0L;
}
return Long.parseLong(httpservletrequest.getParameter(s));
}

public static short getShort(HttpServletRequest httpservletrequest, String s) {
if (httpservletrequest.getParameter(s) == null
|| httpservletrequest.getParameter(s).equals("")) {
return 0;
}
return Short.parseShort(httpservletrequest.getParameter(s));
}

/**
* 将 TEXT 文本转换为 HTML 代码, 已便于网页正确的显示出来.
*
* @param input
* 输入的文本字符串
* @return 转换后的 HTML 代码
*/
public static String textToHtml(String input) {
if (isEmpty(input)) {
return "";
}

input = replace(input, "<", "&#60;");
input = replace(input, ">", "&#62;");

input = replace(input, "\n", "<br>\n");
input = replace(input, "\t", "&nbsp;&nbsp;&nbsp;&nbsp;");
input = replace(input, " ", "&nbsp;&nbsp;");

return input;
}

public static String toQuoteMark(String s) {
s = replaceString(s, "'", "&#39;");
s = replaceString(s, "\"", "&#34;");
s = replaceString(s, "\r\n", "\n");
log.info(s);
return s;
}

public static String replaceChar(String s, char c, char c1) {
if (s == null) {
return "";
}
return s.replace(c, c1);
}

public static String replaceString(String s, String s1, String s2) {
if (s == null || s1 == null || s2 == null) {
return "";
}
return s.replaceAll(s1, s2);
}

public static String toHtml(String s) {
s = replaceString(s, "<", "&#60;");
s = replaceString(s, ">", "&#62;");
return s;
}

public static String toBR(String s) {
s = replaceString(s, "\n", "<br>\n");
s = replaceString(s, "\t", "&nbsp;&nbsp;&nbsp;&nbsp;");
s = replaceString(s, " ", "&nbsp;&nbsp;");
return s;
}

public static String toSQL(String s) {
s = replaceString(s, "\r\n", "\n");
return s;
}

public static String replaceEnter(String s) throws NullPointerException {
return s.replaceAll("\n", "<br>");
}

public static String replacebr(String s) throws NullPointerException {
return s.replaceAll("<br>", "\n");
}

public static String replaceQuote(String s) throws NullPointerException {
return s.replaceAll("'", "''");
}

public static String replaceSql(String sql, String[] sqlParam) {
StringBuffer sqlBuffer = new StringBuffer(sql);
int index = 0;
for (int i = 0; i < sqlBuffer.length(); i++) {
if (sqlBuffer.substring(i, i + 1).equals("?")) {
sqlBuffer.deleteCharAt(i);
sqlBuffer.insert(i, sqlParam[index]);
index++;
}
}
return sqlBuffer.toString();
}

// Test only.
public static void main(String[] args) throws Exception {
String strTest = "123,33,44,AA,*,222,333,444,*,555,666,777,*";
String str[] = split(strTest, "*");
String[] stros = StringToStringArray(str[0], ",");
log.debug(String.valueOf(str.length));
log.debug(String.valueOf(stros.length));
}

@SuppressWarnings("null")
public static String GetPageContent(String pageURL) {
String pageContent = "";
BufferedReader in = null;
InputStreamReader isr = null;
InputStream is = null;
PrintWriter pw = null;
HttpURLConnection huc = null;
try {
URL url = new URL(pageURL);
// 创建 URL
huc = (HttpURLConnection) url.openConnection();
is = huc.getInputStream();
isr = new InputStreamReader(is);
in = new BufferedReader(isr);
String line = null;
while (((line = in.readLine()) != null)) {
if (line.length() == 0)
continue;
pageContent += line;
}
} catch (Exception e) {
System.err.println(e);
} finally { // 无论如何都要关闭流
try {
is.close();
isr.close();
in.close();
huc.disconnect();
pw.close();
} catch (Exception e) {
}
}
return pageContent;
}

/**
* 判断字符串是否为Null或空字符串
*
* @param String
* 要判断的字符串
* @return String true-是空字符串,false-不是空字符串
*/
public static boolean nil(String s) {
if (s == null || s.equals("")) {
return true;
}
return false;
}

/**
* 转换String到boolean
*/
public static boolean parseBoolean(String flag) {
if (nil(flag))
return false;
else if (flag.equals("true") || flag.equals("1") || flag.equals("是")
|| flag.equals("yes"))
return true;
else if (flag.equals("false") || flag.equals("0") || flag.equals("否")
|| flag.equals("no"))
return false;
return false;
}

/*
* 为分页接收查询条件 转 成 sql 子句 key 或 value 有一个为空(“”)则不进行拼接
*/
public static String map2SqlStr(Map valueMap) {
String sqlStr = "";
Set setEntriy = valueMap.entrySet();
for (Iterator it = setEntriy.iterator(); it.hasNext();) {
Map.Entry obj = (Map.Entry) it.next();
Object key = obj.getKey();
Object value = obj.getValue();
if ((!isEmpty(key.toString())) && (!isEmpty(value.toString()))) {
sqlStr += " and " + key.toString() + "='" + value.toString()
+ "'";
}
}

return sqlStr;
}

public static String getRandString(int length) {
StringBuffer s = new StringBuffer("" + (new java.util.Date().getTime()));
Random r = new Random(10);
s.append(Math.abs(r.nextInt()));
if (s.toString().length() > length)
s.substring(0, length);
return s.toString();
}

// ============================================================================================

public static boolean contains(String s, String text, String delimiter) {
if ((s == null) || (text == null) || (delimiter == null)) {
return false;
}

if (!s.endsWith(delimiter)) {
s += delimiter;
}

int pos = s.indexOf(delimiter + text + delimiter);

if (pos == -1) {
if (s.startsWith(text + delimiter)) {
return true;
}

return false;
}

return true;
}

public static int count(String s, String text) {
if ((s == null) || (text == null)) {
return 0;
}

int count = 0;

int pos = s.indexOf(text);

while (pos != -1) {
pos = s.indexOf(text, pos + text.length());
count++;
}

return count;
}

public static String merge(String array[], String delimiter) {
if (array == null) {
return null;
}

StringBuffer sb = new StringBuffer();

for (int i = 0; i < array.length; i++) {
sb.append(array[i].trim());

if ((i + 1) != array.length) {
sb.append(delimiter);
}
}

return sb.toString();
}

public static String read(ClassLoader classLoader, String name)
throws IOException {

return read(classLoader.getResourceAsStream(name));
}

public static String read(InputStream is) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(is));

StringBuffer sb = new StringBuffer();
String line = null;

while ((line = br.readLine()) != null) {
sb.append(line).append('\n');
}

br.close();

return sb.toString().trim();
}

public static String read(InputStream is, String code) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(is, code));

StringBuffer sb = new StringBuffer();
String line = null;

while ((line = br.readLine()) != null) {
sb.append(line).append("\r\n");
}

br.close();

return sb.toString().trim();
}

public static String remove(String s, String remove, String delimiter) {
if ((s == null) || (remove == null) || (delimiter == null)) {
return null;
}

if (s != null && s.length() > 0 && !s.endsWith(delimiter)) {
s += delimiter;
}

while (contains(s, remove, delimiter)) {
int pos = s.indexOf(delimiter + remove + delimiter);

if (pos == -1) {
if (s.startsWith(remove + delimiter)) {
s = s.substring(remove.length() + delimiter.length(), s
.length());
}
} else {
s = s.substring(0, pos)
+ s.substring(pos + remove.length()
+ delimiter.length(), s.length());
}
}

return s;
}

public static String replace(String s, String[] oldSubs, String[] newSubs) {
if ((s == null) || (oldSubs == null) || (newSubs == null)) {
return null;
}

if (oldSubs.length != newSubs.length) {
return s;
}

for (int i = 0; i < oldSubs.length; i++) {
s = replace(s, oldSubs[i], newSubs[i]);
}

return s;
}

public static String reverse(String s) {
if (s == null) {
return null;
}

char[] c = s.toCharArray();
char[] reverse = new char[c.length];

for (int i = 0; i < c.length; i++) {
reverse[i] = c[c.length - i - 1];
}

return new String(reverse);
}

public static String shorten(String s) {
return shorten(s, 20);
}

public static String shorten(String s, int length) {
return shorten(s, length, "..");
}

public static String shorten(String s, String suffix) {
return shorten(s, 20, suffix);
}

public static String shorten(String s, int length, String suffix) {
if (s == null || suffix == null) {
return null;
}

if (s.length() > length) {
s = s.substring(0, length) + suffix;
}

return s;
}

public static boolean[] split(String s, String delimiter, boolean x) {
String[] array = split(s, delimiter);
boolean[] newArray = new boolean[array.length];

for (int i = 0; i < array.length; i++) {
boolean value = x;

try {
value = Boolean.valueOf(array[i]).booleanValue();
} catch (Exception e) {
}

newArray[i] = value;
}

return newArray;
}

public static double[] split(String s, String delimiter, double x) {
String[] array = split(s, delimiter);
double[] newArray = new double[array.length];

for (int i = 0; i < array.length; i++) {
double value = x;

try {
value = Double.parseDouble(array[i]);
} catch (Exception e) {
}

newArray[i] = value;
}

return newArray;
}

public static float[] split(String s, String delimiter, float x) {
String[] array = split(s, delimiter);
float[] newArray = new float[array.length];

for (int i = 0; i < array.length; i++) {
float value = x;

try {
value = Float.parseFloat(array[i]);
} catch (Exception e) {
}

newArray[i] = value;
}

return newArray;
}

public static int[] split(String s, String delimiter, int x) {
String[] array = split(s, delimiter);
int[] newArray = new int[array.length];

for (int i = 0; i < array.length; i++) {
int value = x;

try {
value = Integer.parseInt(array[i]);
} catch (Exception e) {
}

newArray[i] = value;
}

return newArray;
}

public static long[] split(String s, String delimiter, long x) {
String[] array = split(s, delimiter);
long[] newArray = new long[array.length];

for (int i = 0; i < array.length; i++) {
long value = x;

try {
value = Long.parseLong(array[i]);
} catch (Exception e) {
}

newArray[i] = value;
}

return newArray;
}

public static short[] split(String s, String delimiter, short x) {
String[] array = split(s, delimiter);
short[] newArray = new short[array.length];

for (int i = 0; i < array.length; i++) {
short value = x;

try {
value = Short.parseShort(array[i]);
} catch (Exception e) {
}

newArray[i] = value;
}

return newArray;
}

public static final String stackTrace(Throwable t) {
String s = null;

try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
t.printStackTrace(new PrintWriter(baos, true));
s = baos.toString();
} catch (Exception e) {
}

return s;
}

public static boolean startsWith(String s, char begin) {
return startsWith(s, (new Character(begin)).toString());
}

public static boolean startsWith(String s, String begin) {
if ((s == null) || (begin == null)) {
return false;
}

if (begin.length() > s.length()) {
return false;
}

String temp = s.substring(0, begin.length());

if (temp.equalsIgnoreCase(begin)) {
return true;
} else {
return false;
}
}

public static String wrap(String text) {
return wrap(text, 80);
}

public static String wrap(String text, int width) {
if (text == null) {
return null;
}

StringBuffer sb = new StringBuffer();

try {
BufferedReader br = new BufferedReader(new StringReader(text));

String s = "";

while ((s = br.readLine()) != null) {
if (s.length() == 0) {
sb.append("\n");
} else {
while (true) {
int pos = s.lastIndexOf(' ', width);

if ((pos == -1) && (s.length() > width)) {
sb.append(s.substring(0, width));
sb.append("\n");

s = s.substring(width, s.length()).trim();
} else if ((pos != -1) && (s.length() > width)) {
sb.append(s.substring(0, pos));
sb.append("\n");

s = s.substring(pos, s.length()).trim();
} else {
sb.append(s);
sb.append("\n");

break;
}
}
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}

return sb.toString();
}

public static String getPassword(int length, String key) {

StringBuffer sb = new StringBuffer();

for (int i = 0; i < length; i++) {
sb.append(key.charAt((int) (Math.random() * key.length())));
}

return sb.toString();
}

public static String getPassword(int length) {
String key = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
return getPassword(length, key);
}

/**
* Encode a string using algorithm specified in web.xml and return the
* resulting encrypted password. If exception, the plain credentials string
* is returned
*
* @param password
* Password or other credentials to use in authenticating this
* username
* @param algorithm
* Algorithm used to do the digest
*
* @return encypted password based on the algorithm.
*/
public static String encodePassword(String password, String algorithm) {
byte[] unencodedPassword = password.getBytes();

MessageDigest md = null;

try {
// first create an instance, given the provider
md = MessageDigest.getInstance(algorithm);
} catch (Exception e) {
System.err.print("Exception: " + e);

return password;
}

md.reset();

// call the update method one or more times
// (useful when you don't know the size of your data, eg. stream)
md.update(unencodedPassword);

// now calculate the hash
byte[] encodedPassword = md.digest();

StringBuffer buf = new StringBuffer();

for (int i = 0; i < encodedPassword.length; i++) {
if (((int) encodedPassword[i] & 0xff) < 0x10) {
buf.append("0");
}

buf.append(Long.toString((int) encodedPassword[i] & 0xff, 16));
}

return buf.toString();
}

public static String getSubString(String str, String startStr, String endStr) {
if (isEmpty(str))
return null;
int start = str.indexOf(startStr);
int end = str.indexOf(endStr);
if (end > start)
return str.substring(start, end + 1);
return null;
}

public static boolean isdate(String strDate) {
/*
* String str="国际事务部授权通知 2010-7-16"; String strmid=
* str.substring(str.length()-9,str.length());
*/
Pattern pattern = Pattern
.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
Matcher matcher = pattern.matcher(strDate);
// System.out.println(matcher.matches());
return matcher.matches();
}

/**
* 格式化string
*
* @param str
* @param param
* @return
*/
public static String stringFormat(String str, String[] param) {
MessageFormat format = new MessageFormat(str);
return format.format(param);
}

/***************************************************************************
* 获取操作系统
*/
public static String getClientOS(String userAgent) {
String cos = "unknow os";
Pattern p = Pattern.compile(".*(Windows NT 6\\.1).*");
Matcher m = p.matcher(userAgent);
if (m.find()) {
cos = "Win 7";
return cos;
}

p = Pattern.compile(".*(Windows NT 5\\.1|Windows XP).*");
m = p.matcher(userAgent);
if (m.find()) {
cos = "WinXP";
return cos;
}

p = Pattern.compile(".*(Windows NT 5\\.2).*");
m = p.matcher(userAgent);
if (m.find()) {
cos = "Win2003";
return cos;
}

p = Pattern.compile(".*(Win2000|Windows 2000|Windows NT 5\\.0).*");
m = p.matcher(userAgent);
if (m.find()) {
cos = "Win2000";
return cos;
}

p = Pattern.compile(".*(Mac|apple|MacOS8).*");
m = p.matcher(userAgent);
if (m.find()) {
cos = "MAC";
return cos;
}

p = Pattern.compile(".*(WinNT|Windows NT).*");
m = p.matcher(userAgent);
if (m.find()) {
cos = "WinNT";
return cos;
}

p = Pattern.compile(".*Linux.*");
m = p.matcher(userAgent);
if (m.find()) {
cos = "Linux";
return cos;
}

p = Pattern.compile(".*(68k|68000).*");
m = p.matcher(userAgent);
if (m.find()) {
cos = "Mac68k";
return cos;
}

p = Pattern
.compile(".*(9x 4.90|Win9(5|8)|Windows 9(5|8)|95/NT|Win32|32bit).*");
m = p.matcher(userAgent);
if (m.find()) {
cos = "Win9x";
return cos;
}

return cos;
}

/***************************************************************************
* 浏览器信息
*/
public static String getClientBrowser(String userAgent) {
String browser = "";
userAgent = userAgent.toLowerCase();
if (userAgent.indexOf("msie") > -1) {
if (userAgent.indexOf("msn") > -1)
browser = "MSN Explorer";
else
browser = "Internet Explorer";
} else if (userAgent.indexOf("opera") > -1)
browser = "Opera";
else if (userAgent.indexOf("konqueror") > -1)
browser = "KDE Konqueror";
else if (userAgent.indexOf("x11 ") > -1)
browser = "X Windows Browser";
else if (userAgent.indexOf("firefox") > -1)
browser = "Firefox";
else if (userAgent.indexOf("mozilla") > -1)
browser = "Netscape Navigator";
else if (userAgent.indexOf("safari") != -1)
browser = "Safari";
else
browser = "Unknown";
return browser;
}

public static String toChinese(String strvalue, String charset) {
try {
if (charset == null || charset.equals(""))
charset = "UTF-8";
strvalue = new String(strvalue.getBytes("ISO8859_1"), charset);
return strvalue;
} catch (Exception e) {
return null;
}
}
}



  评论这张
 
阅读(195)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017