分享一下以前坛里收集的工具类(方法),希望大家一起来共享下,方便以后使用

sunwei_07 2008-10-14 02:42:03
/**
* 中文乱码转换
* @param str
* @return
*/
public String getChinese(String str){
try {
str = new String(str.getBytes("ISO8859_1"),"GBK");
return str;
} catch (Exception e) {
return str;
}
}

/**
* 获取字符串内的中文
* @param str
* @return
*/
public String getChineseCode(String str){
try {
StringBuffer bf = new StringBuffer();
char[] chars = str.toCharArray();
for (int i=0;i <chars.length;i++) {
if(chars[i]>127){
bf.append(chars[i]);
}

}
String str2 = bf.toString();
return str2;

} catch (Exception e) {
return "";
}
}


/**
* 获取字符串内指定长度的中文内容
* @param str
* @param size
* @return
*/
public String getChineseCode(String str,int size){
try {
StringBuffer bf = new StringBuffer();
char[] chars = str.toCharArray();
for(int i=0;i <chars.length;i++) {
if(chars[i]>127){
bf.append(chars[i]);
if(bf.length()>=size){
return bf.toString();
}
}
}
return bf.toString();
} catch (Exception e) {
return "";
}
}

/**
* 字符串长度
*/
public String getCutString(String str,int size){
try {
if(str.length()>size){
str = str.substring(0, size);
}
return str;
} catch (Exception e) {
return str;
}
}

/**
* 更换回车符号
*/
public String checkBR(String message){
try {
message = message.replaceAll("\n", "<BR>");
message = message.replaceAll("\r", "");
return message;
} catch (Exception e) {
System.out.println(e.toString());
return message;
}
}

public String ToSBC(String input)
{
//半角转全角:
char[] c=input.toCharArray();
for (int i = 0; i < c.length; i++)
{
if (c[i]==32)
{
c[i]=(char)12288;
continue;
}
if (c[i]<127)
c[i]=(char)(c[i]+65248);
}
return new String(c);
}

public String ToDBC(String input)
{
char[] c=input.toCharArray();
for (int i = 0; i < c.length; i++)
{
if (c[i]==12288)
{
c[i]= (char)32;
continue;
}
if (c[i]>65280 && c[i]<65375)
c[i]=(char)(c[i]-65248);
}
return new String(c);
}

public String getStrForClob(Clob clob) {
try {
String ret = null;
if (clob != null) {
Reader is = clob.getCharacterStream();
BufferedReader br = new BufferedReader(is);
String s = br.readLine();
StringBuffer sb = new StringBuffer();
while (s != null) {
sb.append(s);
s = br.readLine();
}
ret = sb.toString();
}
return ret;
} catch (Exception e) {
return "";
}
}

public String clob2string(Clob c) {
StringBuffer sb = new StringBuffer(1024);
Reader instream = null;
try {
instream = c.getCharacterStream();
char[] buffer = new char[(int) c.length()];
int length = 0;
while ((length = instream.read(buffer)) != -1) {
sb.append(buffer);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (instream != null)
instream.close();
} catch (Exception dx) {
instream = null;
}
return sb.toString();
}
}

/**
* 分割字符串
*
* @param str String 原始字符串
* @param splitsign String 分隔符
* @return String[] 分割后的字符串数组
*/
@SuppressWarnings("unchecked")
public String[] split(String str, String splitsign) {
int index;
if (str == null || splitsign == null)
return null;
ArrayList al = new ArrayList();
while ((index = str.indexOf(splitsign)) != -1) {
al.add(str.substring(0, index));
str = str.substring(index + splitsign.length());
}
al.add(str);
return (String[]) al.toArray(new String[0]);
}

/**
* 替换字符串
*
* @param from String 原始字符串
* @param to String 目标字符串
* @param source String 母字符串
* @return String 替换后的字符串
*/
public String replace(String from, String to, String source) {
if (source == null || from == null || to == null)
return null;
StringBuffer bf = new StringBuffer("");
int index = -1;
while ((index = source.indexOf(from)) != -1) {
bf.append(source.substring(0, index) + to);
source = source.substring(index + from.length());
index = source.indexOf(from);
}
bf.append(source);
return bf.toString();
}

/**
* 替换字符串,能能够在HTML页面上直接显示(替换双引号和小于号)
*
* @param str String 原始字符串
* @return String 替换后的字符串
*/
public String htmlencode(String str) {
if (str == null) {
return null;
}

return replace("\"", """, replace("<", "<", str));
}

/**
* 替换字符串,将被编码的转换成原始码(替换成双引号和小于号)
*
* @param str String
* @return String
*/
public String htmldecode(String str) {
if (str == null) {
return null;
}

return replace(""", "\"", replace("<", "<", str));
}

private static final String _BR = "<br/>";

/**
* 在页面上直接显示文本内容,替换小于号,空格,回车,TAB
*
* @param str String 原始字符串
* @return String 替换后的字符串
*/
public String htmlshow(String str) {
if (str == null) {
return null;
}

str = replace("<", "<", str);
str = replace(" ", " ", str);
str = replace("\r\n", _BR, str);
str = replace("\n", _BR, str);
str = replace("\t", "    ", str);
return str;
}

/**
* 返回指定字节长度的字符串
*
* @param str String 字符串
* @param length int 指定长度
* @return String 返回的字符串
*/
public String toLength(String str, int length) {
if (str == null) {
return null;
}
if (length <= 0) {
return "";
}
try {
if (str.getBytes("GBK").length <= length) {
return str;
}
} catch (Exception ex) {
}
StringBuffer buff = new StringBuffer();

int index = 0;
char c;
length -= 3;
while (length > 0) {
c = str.charAt(index);
if (c < 128) {
length--;
} else {
length--;
length--;
}
buff.append(c);
index++;
}
buff.append("...");
return buff.toString();
}
...全文
57 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
岁月彼岸 2009-02-12
  • 打赏
  • 举报
回复
不错,谢谢楼主了
76ersjy2 2008-11-14
  • 打赏
  • 举报
回复
我的博客里有几个经常用的类:

http://hi.csdn.net/76ersjy2
76ersjy2 2008-11-11
  • 打赏
  • 举报
回复
来顶一下。
sunwei_07 2008-10-14
  • 打赏
  • 举报
回复
没有兄弟一起来分享吗?……
sunwei_07 2008-10-14
  • 打赏
  • 举报
回复
// 判断时间date1是否在时间date2之前
//时间格式 2005-4-21 16:16:34
public boolean isDateBefore(String date1, String date2) {
try {
DateFormat df = DateFormat.getDateTimeInstance();
return df.parse(date1).before(df.parse(date2));
} catch (Exception e) {
System.out.print("[SYS] " + e.getMessage());
return false;
}
}

// 判断当前时间是否在时间date2之前
// 时间格式 2005-4-21 16:16:34
public boolean isDateBefore(String date2) {
try {
DateFormat df = DateFormat.getDateTimeInstance();
return this.getDate().before(df.parse(date2));
} catch (Exception e) {
System.out.print("[SYS] " + e.getMessage());
return false;
}
}

/**
* 计算时间差
* @param args
*/
public int DateDistance(java.util.Date time){
try {
java.util.Date tempDate = new java.util.Date();

String distance = String.valueOf((tempDate.getTime() - time.getTime())/ (24 * 60 * 60 * 1000));//计算两个日期之间的时间差,本例为计算天数

return Integer.parseInt(distance);
} catch (Exception e) {
return 0;
}
}

public int DateDistance(java.util.Date time1,java.util.Date time2){
try {
java.util.Date tempDate = new java.util.Date();

String distance = String.valueOf((time2.getTime() - time1.getTime())/ (24 * 60 * 60 * 1000));//计算两个日期之间的时间差,本例为计算天数

return Integer.parseInt(distance);
} catch (Exception e) {
return 0;
}
}
sunwei_07 2008-10-14
  • 打赏
  • 举报
回复
/**
* 列出某文件夹及其子文件夹下面的文件,并可根据扩展名过滤
*
* @param path
*/
public static void list(File path)
{
if (!path.exists())
{
System.out.println("文件名称不存在!");
}
else
{
if (path.isFile())
{
if (path.getName().toLowerCase().endsWith(".pdf")
|| path.getName().toLowerCase().endsWith(".doc")
|| path.getName().toLowerCase().endsWith(".html")
|| path.getName().toLowerCase().endsWith(".htm"))
{
System.out.println(path);
System.out.println(path.getName());
}
}
else
{
File[] files = path.listFiles();
for (int i = 0; i < files.length; i++)
{
list(files[i]);
}
}
}
}

/**
* 拷贝一个目录或者文件到指定路径下
*
* @param source
* @param target
*/
public static void copy(File source, File target)
{
File tarpath = new File(target, source.getName());
if (source.isDirectory())
{
tarpath.mkdir();
File[] dir = source.listFiles();
for (int i = 0; i < dir.length; i++)
{
copy(dir[i], tarpath);
}
}
else
{
try
{
InputStream is = new FileInputStream(source);
OutputStream os = new FileOutputStream(tarpath);
byte[] buf = new byte[1024];
int len = 0;
while ((len = is.read(buf)) != -1)
{
os.write(buf, 0, len);
}
is.close();
os.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

/**
* 删除指定文件
*/
public static boolean deleteFile(String filename){
try {
return (new File(filename)).delete();
} catch (Exception e) {
return false;
}
}
zj101582 2008-10-14
  • 打赏
  • 举报
回复
谢谢,分享
sunwei_07 2008-10-14
  • 打赏
  • 举报
回复
/**
* 判断是否为整数
*
* @param str 传入的字符串
* @return 是整数返回true,否则返回false
*/
public boolean isInteger(String str) {
Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
return pattern.matcher(str).matches();
}

/**
* 判断是否为浮点数,包括double和float
*
* @param str 传入的字符串
* @return 是浮点数返回true,否则返回false
*/
public boolean isDouble(String str) {
Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$");
return pattern.matcher(str).matches();
}

/**
* 判断输入的字符串是否符合Email样式.
*
* @param str 传入的字符串
* @return 是Email样式返回true,否则返回false
*/
public boolean isEmail(String str) {
Pattern pattern = Pattern.compile("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
return pattern.matcher(str).matches();
}

/**
* 判断输入的字符串是否为纯汉字
*
* @param str 传入的字符窜
* @return 如果是纯汉字返回true,否则返回false
*/
public boolean isChinese(String str) {
Pattern pattern = Pattern.compile("[\u0391-\uFFE5]+$");
return pattern.matcher(str).matches();
}

/**
* 是否为空白,包括null和""
*
* @param str
* @return
*/
public boolean isBlank(String str) {
return str == null || str.trim().length() == 0;
}

/**
* 判断是否为质数
*
* @param x
* @return
*/
public boolean isPrime(int x) {
if (x <= 7) {
if (x == 2 || x == 3 || x == 5 || x == 7)
return true;
}
int c = 7;
if (x % 2 == 0)
return false;
if (x % 3 == 0)
return false;
if (x % 5 == 0)
return false;
int end = (int) Math.sqrt(x);
while (c <= end) {
if (x % c == 0) {
return false;
}
c += 4;
if (x % c == 0) {
return false;
}
c += 2;
if (x % c == 0) {
return false;
}
c += 4;
if (x % c == 0) {
return false;
}
c += 2;
if (x % c == 0) {
return false;
}
c += 4;
if (x % c == 0) {
return false;
}
c += 6;
if (x % c == 0) {
return false;
}
c += 2;
if (x % c == 0) {
return false;
}
c += 6;
}
return true;
}


// 过滤特殊字符
public String encoding(String src){
if (src==null)
return "";
StringBuilder result=new StringBuilder();
if (src!=null){
src=src.trim();
for (int pos=0;pos<src.length();pos++){
switch(src.charAt(pos)){
case '\"':result.append(""");break;
case '<':result.append("<");break;
case '>':result.append(">");break;
case '\'':result.append("'");break;
case '&':result.append("&");break;
case '%':result.append("&pc;");break;
case '_':result.append("&ul;");break;
case '#':result.append("&shap;");break;
case '?':result.append("&ques;");break;
default:result.append(src.charAt(pos));break;
}
}
}
return result.toString();
}

// 反过滤特殊字符
public String decoding(String src){
if (src==null)
return "";
String result=src;
result=result.replace(""", "\"").replace("'", "\'");
result=result.replace("<", "<").replace(">", ">");
result=result.replace("&", "&");
result=result.replace("&pc;", "%").replace("&ul", "_");
result=result.replace("&shap;", "#").replace("&ques", "?");
return result;
}

/**
* 判断是不是合法手机
* handset 手机号码
*/
public static boolean isHandset(String handset) {
try {
if(!handset.substring(0,1).equals("1")) {
return false;
}
if (handset==null || handset.length()!=11) {
return false;
}
String check = "^[0123456789]+$";
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(handset);
boolean isMatched = matcher.matches();
if(isMatched) {
return true;
} else {
return false;
}
} catch (RuntimeException e) {
return false;
}

}

/**
* 从指定的字符串中提取Email
* content 指定的字符串
*/
public String parse(String content) {
String email = null;
if (content==null || content.length()<1) {
return email;
}
//找出含有@
int beginPos;
int i;
String token = "@";
String preHalf="";
String sufHalf = "";

beginPos = content.indexOf(token);
if (beginPos>-1) {
//前项扫描
String s = null;
i= beginPos;
while(i>0) {
s = content.substring(i-1,i);
if (isLetter(s))
preHalf = s+preHalf;
else
break;
i--;
}
//后项扫描
i= beginPos+1;
while( i<content.length()) {
s = content.substring(i,i+1);
if (isLetter(s))
sufHalf = sufHalf +s;
else
break;
i++;
}
//判断合法性
email = preHalf + "@" + sufHalf;
if (isEmail(email)) {
return email;
}
}
return null;
}



/**
* 判断是不是合法字符
* c 要判断的字符
*/
public boolean isLetter(String c) {
boolean result = false;

if (c==null || c.length()<0) {
return false;
}
//a-z
if (c.compareToIgnoreCase("a")>=0 && c.compareToIgnoreCase("z")<=0) {
return true;
}
//0-9
if (c.compareToIgnoreCase("0")>=0 && c.compareToIgnoreCase("9")<=0) {
return true;
}
//. - _
if (c.equals(".") || c.equals("-") || c.equals("_") ) {
return true;
}
return result;
}

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧