1.当前时间加一天:
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(5, 1);
Date newdate = calendar.getTime();
System.out.println(date);
System.out.println(newdate);
2.邮箱隐藏成**
//format email eg:ddd****@test.com
String email = dddkkkk@test.com;
String formatEamil = email;
int indexLen = email.indexOf("@");
formatEamil = email.substring(0,3) + "******" + email.substring(indexLen);
import java.io.File;
import java.util.ArrayList;
public class FileTest {
private static ArrayList<String> filelist = new ArrayList<String>();
public static void main(String[] args) throws Exception {
String filePath = "E://Struts2";
getFiles(filePath);
}
/*
* 通过递归得到某一路径下所有的目录及其文件
*/
static void getFiles(String filePath){
File root = new File(filePath);
File[] files = root.listFiles();
for(File file:files){
if(file.isDirectory()){
/*
* 递归调用
*/
getFiles(file.getAbsolutePath());
filelist.add(file.getAbsolutePath());
System.out.println("显示"+filePath+"下所有子目录及其文件"+file.getAbsolutePath());
}else{
System.out.println("显示"+filePath+"下所有子目录"+file.getAbsolutePath());
}
}
}
}
File oldFile = new File("a.txt");
String rootPath = oldFile.getParent();
System.out.println("根路径是:"+rootPath);
File newFile = new File(rootPath + File.separator + "b.txt");
System.out.println("修改后文件名称是:"+newFile.getName());
oldFile.renameTo(newFile)
5.综合运用
package boots;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
public class RealnameTest {
private static ArrayList<String> filelist = new ArrayList<String>();
public static void main(String[] args) throws IOException
{
String filePath = "E://OutputFile";
getFiles(filePath);
}
/*
* 通过递归得到某一路径下所有的目录及其文件
*/
static void getFiles(String filePath){
File root = new File(filePath);
File[] files = root.listFiles();
for(File file:files){
if(file.isDirectory()){
/*
* 递归调用
*/
getFiles(file.getAbsolutePath());
filelist.add(file.getAbsolutePath());
// String name = file.getName();
// int leng = name.length();
//
// System.out.println(name.substring(leng-15, leng-7));
System.out.println("***"+file.getName());
String name = file.getName();
//String dateString = "2012-12-06 ";
//file.renameTo()
try
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(name);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(5, -1);
Date newdate = calendar.getTime();
String sdate=(new SimpleDateFormat("yyyy-MM-dd")).format(newdate);
File newFile = new File(filePath + File.separator + sdate);
System.out.println(newFile.getAbsolutePath());
file.renameTo(newFile);
}
catch (ParseException e)
{
System.out.println(e.getMessage());
}
//System.out.println("显示"+filePath+"下所有子目录及其文件"+file.getAbsolutePath());
}else{
// System.out.println(file.getName());
String name = file.getName();
int leng = name.length();
String rname = name.substring(leng-15, leng-7);
try
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date date = sdf.parse(rname);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(5, -1);
Date newdate = calendar.getTime();
rname = (new SimpleDateFormat("yyyyMMdd")).format(newdate);
}
catch (ParseException e)
{
System.out.println(e.getMessage());
}
String n = name.substring(0, leng-14)+rname+"_wx.csv";
File newFile = new File(filePath + File.separator + n);
//System.out.println(newFile.getAbsolutePath());
file.renameTo(newFile);
System.out.println(n);
//System.out.println("TTTTTT**"+file.getName());
//System.out.println("显示"+filePath+"下所有子目录"+file.getAbsolutePath());
}
}
}
}
6.String与date的互转
- String--》Date
-
String dateString = "2012-12-06 "; try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd "); Date date = sdf.parse(dateString); } catch (ParseException e) { System.out.println(e.getMessage()); } -
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.apache.commons.lang.StringUtils; /** * 日期Util类 * * @author calvin */ public class DateUtil { private static String defaultDatePattern = "yyyy-MM-dd "; /** * 获得默认的 date pattern */ public static String getDatePattern() { return defaultDatePattern; } /** * 返回预设Format的当前日期字符串 */ public static String getToday() { Date today = new Date(); return format(today); } /** * 使用预设Format格式化Date成字符串 */ public static String format(Date date) { return date == null ? " " : format(date, getDatePattern()); } /** * 使用参数Format格式化Date成字符串 */ public static String format(Date date, String pattern) { return date == null ? " " : new SimpleDateFormat(pattern).format(date); } /** * 使用预设格式将字符串转为Date */ public static Date parse(String strDate) throws ParseException { return StringUtils.isBlank(strDate) ? null : parse(strDate, getDatePattern()); } /** * 使用参数Format将字符串转为Date */ public static Date parse(String strDate, String pattern) throws ParseException { return StringUtils.isBlank(strDate) ? null : new SimpleDateFormat( pattern).parse(strDate); } /** * 在日期上增加数个整月 */ public static Date addMonth(Date date, int n) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.MONTH, n); return cal.getTime(); } public static String getLastDayOfMonth(String year, String month) { Calendar cal = Calendar.getInstance(); // 年 cal.set(Calendar.YEAR, Integer.parseInt(year)); // 月,因为Calendar里的月是从0开始,所以要-1 // cal.set(Calendar.MONTH, Integer.parseInt(month) - 1); // 日,设为一号 cal.set(Calendar.DATE, 1); // 月份加一,得到下个月的一号 cal.add(Calendar.MONTH, 1); // 下一个月减一为本月最后一天 cal.add(Calendar.DATE, -1); return String.valueOf(cal.get(Calendar.DAY_OF_MONTH));// 获得月末是几号 } public static Date getDate(String year, String month, String day) throws ParseException { String result = year + "- " + (month.length() == 1 ? ("0 " + month) : month) + "- " + (day.length() == 1 ? ("0 " + day) : day); return parse(result); } } - Date--》String
-
String sdate; Date ddate; sdate=(new SimpleDateFormat("yyyy-MM-dd")).format(ddate);
6.【Double】【BigDecimal】转换
double d = 12.22;
BigDecimal bg = new BigDecimal(d);//【double】-->【BigDecimal】
double as = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();//【BigDecimal】-->【double】
金额的计算BigDecimal类
double d = 9.84;
double d2 = 1.22;
//注意需要使用BigDecimal(String val)构造方法
BigDecimal bigDecimal = new BigDecimal(Double.toString(d));
BigDecimal bigDecimal2 = new BigDecimal(Double.toString(d2));
//加法
BigDecimal bigDecimalAdd = bigDecimal.add(bigDecimal2);
double add = bigDecimalAdd.doubleValue();
//减法
BigDecimal bigDecimalSubtract = bigDecimal.subtract(bigDecimal2);
double subtract = bigDecimalSubtract.doubleValue();
//乘法
BigDecimal bigDecimalMultiply = bigDecimal.multiply(bigDecimal2);
double multiply = bigDecimalMultiply.doubleValue();
//除法
int scale = 2;//保留2位小数
BigDecimal bigDecimalDivide = bigDecimal.divide(bigDecimal2, scale, BigDecimal.ROUND_HALF_UP);
double divide = bigDecimalDivide.doubleValue();
//格式化
double format = 12343171.6;
//获取常规数值格式
NumberFormat number = NumberFormat.getNumberInstance();
String str = number.format(format);//12,343,171.6
//获取整数数值格式
NumberFormat integer = NumberFormat.getIntegerInstance();
str = integer.format(format);//如果带小数会四舍五入到整数12,343,172
//获取货币数值格式
NumberFormat currency = NumberFormat.getCurrencyInstance();
currency.setMinimumFractionDigits(2);//设置数的小数部分所允许的最小位数(如果不足后面补0)
currency.setMaximumFractionDigits(4);//设置数的小数部分所允许的最大位数(如果超过会四舍五入)
str = currency.format(format);//¥12,343,171.60
//获取显示百分比的格式
NumberFormat percent = NumberFormat.getPercentInstance();
percent.setMinimumFractionDigits(2);//设置数的小数部分所允许的最小位数(如果不足后面补0)
percent.setMaximumFractionDigits(3);//设置数的小数部分所允许的最大位数(如果超过会四舍五入)
str = percent.format(format);//1,234,317,160.00%
7.产生1-100的整数
Random rand = new Random();
int x = rand.nextInt(100)+1;
int nextInt(int n)
返回一个伪随机数,它是取自此随机数生成器序列的、在 0(包括)和指定值(不包括)之间均匀分布的 int 值
int y = (int)(Math.random()*100)+1;
static double random()
返回带正号的 double 值,该值大于等于 0.0 且小于 1.0。
8.Unicode编码转化为汉字
/**
* @Title: unicodeToChinese
* @Description: Unicode编码转化为汉字
* @param @param result
* @param @return 设定文件
* @return StringBuffer 返回类型
* @throws
*/
public static String unicodeToChinese(StringBuffer result) {
StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile("(?i)\\\\u([\\da-f]{4})");
Matcher m = p.matcher(result);
while(m.find()) {
m.appendReplacement(sb, Character.toString((char)Integer.parseInt(m.group(1), 16)));
}
m.appendTail(sb);
return sb.toString();
}
9.通过IP获取地址
/**
* @Title: getAddressByIP
* @Description: 通过IP获取地址
* @param @param strIP ip
* @param @return 设定文件
* @return IpAdressDto ip所在地bean
* @throws
*/
public static IpAdressDto getAddressByIP(String strIP)
{
try
{
//String strIP = "0.0.0.0";
//调用baiduAPI通过IP获取IP所在地址
URL url = new URL( "http://apistore.baidu.com/microservice/iplookup?ip=" + strIP);
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line = null;
StringBuffer result = new StringBuffer();
while((line = reader.readLine()) != null)
{
result.append(line);
}
reader.close();
//从百度中得到的地址对应的中文是unicode码,所以需要转化下
//String s = "\\u4e2d\\u56fd";
String sb = unicodeToChinese(result);
IpAdressDto ipAdressDto = getBeanFromJSON(sb,IpAdressDto.class,"retData");
return ipAdressDto;
}
catch( IOException e)
{
logger.error("从IP中读取地址失败:"+e.getMessage());
return null;
}
}
对应的实体类IpAdressDto
public class IpAdressDto {
private String ip;
private String country;
private String area;
private String province;
private String city;
private String district;
private String carrier;
//get set方法
public String toString(){
return "*ip:"+ip+" *country:"+country+" *area:"+area+" *province:"+province+
" *city:"+city+" *district:"+district+" *carrier:"+carrier;
}
}
取IP
public static String getIpAddress() {
Enumeration<NetworkInterface> netInterfaces = null;
try {
netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = netInterfaces.nextElement();
System.out.println("DisplayName:" + ni.getDisplayName());
System.out.println("Name:" + ni.getName());
Enumeration<InetAddress> ips = ni.getInetAddresses();
while (ips.hasMoreElements()) {
InetAddress ip = ips.nextElement();
if (!ip.isLoopbackAddress()) {
System.out.println("ip-------------------->" + ip.getHostAddress());
return ip.getHostAddress();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
String ip = request.getHeader("X-FORWARDED-FOR");
if (ip == null) {
ip = request.getRemoteAddr();
}
10.JAVA中Long与Integer比较容易犯的错误
因为Long与Ineger都是包装类型,是对象。 而不是普通类型long与int , 所以它们在比较时必须都应该用equals,或者先使用longValue()或intValue()方法来得到他们的基本类型的值然后使用==比较也是可以的。
但是有一种特殊情况, 其实Long与Integer都将 -128~127 这些对象缓存了。 可以看看Long类型源码里面有一个LongCache类,代码如下:
private static class LongCache {
private LongCache(){}
static final Long cache[] = new Long[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Long(i - 128);
}
}
调用了Long的一个类方法Long.valueOf(Long) , 所以可以得到的结论是Long a = 5L实际上等于 Long a = Long.valueOf(5) ;
然后再看看Long.valueOf()方法是如何定义的:
public static Long valueOf(long l) {
final int offset = 128;
if (l >= -128 && l <= 127) { // will cache
return LongCache.cache[(int)l + offset];
}
return new Long(l);
}
一目了然,会先判断基本类型的值如果在-128~127之间,就会直接从LongCache里面取出缓存的对象返回,否则就new一个新的Long对象返回 。
Long重写了equals方法:
public boolean equals(Object obj) {
if (obj instanceof Long) {
return value == ((Long)obj).longValue();
}
return false;
}
它是先通过.longValue()方法获取Long对象的基本类型long的值之后再做比较的。
所以对于Integer与Long的比较,最好是使用equals来比较才能确保得到我们想要的结果。
String[] spaceAarry = spaceAreaStr.split("\\.");当String用".$|()[{^?*+\\"这些字符进行split分隔时,要对这些字符进行"\\"转义
soure code:
public String[] split(String regex, int limit) {
/* fastpath if the regex is a
(1)one-char String and this character is not one of the
RegEx's meta characters ".$|()[{^?*+\\", or
(2)two-char String and the first char is the backslash and
the second is not the ascii digit or ascii letter.
*/
char ch = 0;
if (((regex.value.length == 1 &&
".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
(regex.length() == 2 &&
regex.charAt(0) == '\\' &&
(((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
((ch-'a')|('z'-ch)) < 0 &&
((ch-'A')|('Z'-ch)) < 0)) &&
(ch < Character.MIN_HIGH_SURROGATE ||
ch > Character.MAX_LOW_SURROGATE))
{
int off = 0;
int next = 0;
boolean limited = limit > 0;
ArrayList<String> list = new ArrayList<>();
while ((next = indexOf(ch, off)) != -1) {
if (!limited || list.size() < limit - 1) {
list.add(substring(off, next));
off = next + 1;
} else { // last one
//assert (list.size() == limit - 1);
list.add(substring(off, value.length));
off = value.length;
break;
}
}
// If no match was found, return this
if (off == 0)
return new String[]{this};
// Add remaining segment
if (!limited || list.size() < limit)
list.add(substring(off, value.length));
// Construct result
int resultSize = list.size();
if (limit == 0)
while (resultSize > 0 && list.get(resultSize - 1).length() == 0)
resultSize--;
String[] result = new String[resultSize];
return list.subList(0, resultSize).toArray(result);
}
return Pattern.compile(regex).split(this, limit);
}
Java实用技巧汇总

被折叠的 条评论
为什么被折叠?



