Java代码常用功能实现总结

来源:互联网 发布:淘宝详情页ps怎么切片 编辑:程序博客网 时间:2024/05/21 19:32

1.获取当前系统时间:

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式

System.out.println(df.format(new Date()));

运行结果:

2017-10-22 12:18:37


2.获取当前时间戳
//方法 一
System.currentTimeMillis();
//方法 二
Calendar.getInstance().getTimeInMillis();
//方法 三
new Date().getTime();

补充:获取时间戳三种方法执行效率比较

import java.util.Calendar;import java.util.Date; public class TimeTest {    private static long _TEN_THOUSAND=10000;    public static void main(String[] args) {        long times=1000*_TEN_THOUSAND;        long t1=System.currentTimeMillis();        testSystem(times);        long t2=System.currentTimeMillis();        System.out.println(t2-t1);         testCalander(times);        long t3=System.currentTimeMillis();        System.out.println(t3-t2);         testDate(times);        long t4=System.currentTimeMillis();        System.out.println(t4-t3);    }     public static void testSystem(long times){        for(int i=0;i<times;i++){            long currentTime=System.currentTimeMillis();        }    }     public static void testCalander(long times){        for(int i=0;i<times;i++){            long currentTime=Calendar.getInstance().getTimeInMillis();        }    }     public static void testDate(long times){        for(int i=0;i<times;i++){            long currentTime=new Date().getTime();        }    } }执行结果:43188545Calendar.getInstance().getTimeInMillis() 这种方式速度最慢,这是因为Canlendar要处理时区问题会耗费较多的时间。

Python:

import timeprint (time.time())print(int(round(time.time()*1000)))print(int(time.time()))
运行结果:

1513776456.43
1513776456440
1513776456
疑惑:java上面的三种方法获取的时间戳都是13位的,而python用自带的time模块获取的却是1513776456.43,还得自己转换成10位或13位的

解答:时间戳的位数是根据算法计算的,没有固定的位数。 可信时间戳计算出来的电子文件的数字指纹是40位~
由于精度不同,导致长度不一致,直接转换错误。 JAVA时间戳长度是13位,如:1294890876859 PHP时间戳长度是10位(不知道js默认是多少位,但是在工作中python传给js的时间戳还必须是13位,10位的解析不出来), 如:1294890859 php echo date!


3.获取主机名和IP
InetAddress a=InetAddress.getLocalHost();
String localname=a.getHostName();
String localip=a.getHostAddress();
System.out.println("本机名称是:" + localname);
System.out.println("本机的ip是 :" + localip);
System.out.println(InetAddress.getLocalHost());
运行结果:
本机名称是:h66
本机的ip是 :192.168.205.66
h66/192.168.205.66


4.new String用法:

byte[] bytes = "hui".getBytes(); //String转bytes
String receiveText = new String( bytes,1,2); //bytes转String
System.out.println(receiveText);

运行结果:

ui


5.ByteBuffer和String的互相转换:

String hui = "hehe";
ByteBuffer buffer = ByteBuffer.wrap(hui.getBytes());
Charset charset = Charset.forName("UTF-8");
CharsetDecoder decoder = charset.newDecoder();
CharBuffer charBuffer = decoder.decode(buffer.asReadOnlyBuffer());
System.out.println(buffer);
System.out.println(charBuffer.toString());

运行结果:

java.nio.HeapByteBuffer[pos=0 lim=4 cap=4]
hehe


6.int和string相互转换:
int -> String:
int i=12345;
String s="";
第一种方法:s=i+"";
第二种方法:s=String.valueOf(i);
String -> int:
s="12345";
int i;
第一种方法:i=Integer.parseInt(s);
第二种方法:i=Integer.valueOf(s).intValue();
这两种方法有什么区别呢?作用是不是一样的呢?是不是在任何下都能互换呢?答:
第一种方法:s=i+""; //会产生两个String对象
第二种方法:s=String.valueOf(i); //直接使用String类的静态方法,只产生一个对象
第一种方法:i=Integer.parseInt(s);//直接使用静态方法,不会产生多余的对象,但会抛出异常
第二种方法:i=Integer.valueOf(s).intValue();//Integer.valueOf(s) 相当于 new Integer(Integer.parseInt(s)),也会抛异常,但会多产生一个对象


7.遍历Map的四种方法(来自http://www.cnblogs.com/kristain/articles/2033566.html)

public static void main(String[] args) {Map<String, String> map = new HashMap<String, String>();map.put("1", "value1");map.put("2", "value2");map.put("3", "value3");  //第一种:普遍使用,二次取值System.out.println("通过Map.keySet遍历key和value:");for (String key : map.keySet()) {System.out.println("key= "+ key + " and value= " + map.get(key));}  //第二种System.out.println("通过Map.entrySet使用iterator遍历key和value:");Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();while (it.hasNext()) {Map.Entry<String, String> entry = it.next();System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());}  //第三种:推荐,尤其是容量大时System.out.println("通过Map.entrySet遍历key和value");for (Map.Entry<String, String> entry : map.entrySet()) {System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());}//第四种System.out.println("通过Map.values()遍历所有的value,但不能遍历key");for (String v : map.values()) {System.out.println("value= " + v);}}
参考:http://blog.csdn.net/luanlouis/article/details/43017071


8.除去字符串(String)中的换行字符(\r \n \t):
String hui = "'ab cd" + "\n" + "efg'";
System.out.println("转换前:"+hui);
hui = hui.replaceAll("\r|\n", "");
System.out.println("转换后:"+hui);
运行结果:
转换前:'ab cd
efg'
转换后:'ab cdefg'

补充:

例2:System.out.println("\\r 输出:"+"abc"+"\r"+"abc");System.out.println("\\n 输出:"+"abc"+"\n"+"abc");以上两句在控制台输出的格式是一样的:\r输出:abcabc\r输出:abcabc那么他们有什么区别呢?例3:String hui = "'ab cd" + "\n\r" + "efg'";System.out.println("转换前:"+hui);hui = hui.replaceAll("\r|\n", "");System.out.println("转换后:"+hui);运行结果:转换前:'ab cdefg'转换后:'ab cdefg'可以看出\r表示回车,\n表示另起一行(\r 叫回车 Carriage Return  ;\n 叫新行 New Line)我们可以再做一个实验:String hui = "'ab cd" + "\r\n" + "efg'";System.out.println("转换前:"+hui);hui = hui.replaceAll("\r|\n", "");System.out.println("转换后:"+hui);运行结果:转换前:'ab cdefg'转换后:'ab cdefg'注:trim()用来去首尾的空格符\n 换行(\u000a)\t 水平制表符(\u0009)\s 空格(\u0008)\r 回车(\u000d)

9.System.getProperty("属性名")方法的使用:(参考自:http://blog.csdn.net/wodewutai17quiet/article/details/68946890)

System.out.println("操作系统的名称:"+System.getProperty("os.name"));//Windows 8System.out.println("操作系统的架构:"+System.getProperty("os.arch"));//amd64System.out.println("操作系统的版本:"+System.getProperty("os.version"));//6.2System.out.println("Java 运行时环境版本:"+System.getProperty("java.version"));//1.7.0_25System.out.println("Java 运行时环境供应商:"+System.getProperty("java.vendor"));//Oracle CorporationSystem.out.println("Java 供应商的 URL:"+System.getProperty("java.vendor.url"));//http://java.oracle.com/System.out.println("Java 安装目录:"+System.getProperty("java.home"));//C:\Program Files\Java\jdk1.7.0_25\jreSystem.out.println("Java 虚拟机规范版本:"+System.getProperty("java.vm.specification.version"));//1.7System.out.println("Java 虚拟机规范供应商:"+System.getProperty("java.vm.specification.vendor"));//Oracle CorporationSystem.out.println("Java 虚拟机规范名称:"+System.getProperty("java.vm.specification.name"));//Java Virtual Machine SpecificationSystem.out.println("Java 虚拟机实现版本:"+System.getProperty("java.vm.version"));//23.25-b01System.out.println("Java 虚拟机实现供应商:"+System.getProperty("java.vm.vendor"));//Oracle CorporationSystem.out.println("Java 虚拟机实现名称:"+System.getProperty("java.vm.name"));//Java HotSpot(TM) 64-Bit Server VMSystem.out.println("Java 运行时环境规范版本:"+System.getProperty("java.specification.version"));//1.7System.out.println("Java 运行时环境规范供应商:"+System.getProperty("java.specification.vendor"));//Oracle CorporationSystem.out.println("Java 运行时环境规范名称:"+System.getProperty("java.specification.name"));//Java Platform API SpecificationSystem.out.println("Java 类格式版本号:"+System.getProperty("java.class.version"));//51.0System.out.println("Java 类路径:"+System.getProperty("java.class.path"));System.out.println("加载库时搜索的路径列表:"+System.getProperty("java.library.path"));System.out.println("默认的临时文件路径:"+System.getProperty("java.io.tmpdir"));System.out.println("要使用的 JIT 编译器的名称:"+System.getProperty("java.compiler"));System.out.println("一个或多个扩展目录的路径:"+System.getProperty("java.ext.dirs"));System.out.println("文件分隔符(在 UNIX 系统中是“/”):"+System.getProperty("file.separator"));System.out.println("路径分隔符(在 UNIX 系统中是“:”):"+System.getProperty("path.separator"));System.out.println("行分隔符(在 UNIX 系统中是“/n”):"+System.getProperty("line.separator"));System.out.println("用户的账户名称:"+System.getProperty("user.name"));System.out.println("用户的主目录:"+System.getProperty("user.home"));System.out.println("用户的当前工作目录:"+System.getProperty("user.dir"));