常用JAVA语句_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 常用JAVA语句

常用JAVA语句

 2013/10/14 18:39:44  心杀心  程序员俱乐部  我要评论(0)
  • 摘要:常用的Java语句1.取得日期,格式为2013-10-14Calendarcalendar=Calendar.getInstance();Stringto_date=newSimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());//取得前5天日期from_datecalendar.add(Calendar.DATE,-5);Stringfrom_date=newSimpleDateFormat
  • 标签:常用 Java
常用的Java语句
1.取得日期,格式为2013-10-14
Calendar calendar = Calendar.getInstance();
String to_date = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
//取得前5天日期from_date
calendar.add(Calendar.DATE, -5);
String from_date = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
//取得前一个月的日期
calendar.add(Calendar.MONTH, -1);
String from_date = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());


2.四舍五入 scale:要保留的小数位
    public static String round(double value, int scale) {
       if(value==0.5){//0.5四舍五入有误,故加上0.00000001校正
           value=0.50000001;
       }
       String temp = Math.abs(value) < 1 ? "0":"###,###";
       if (scale > 0) {
           temp += ".";
           for (int i = 0; i < scale; i++) {
              temp += "0";
           }
       }
       return new DecimalFormat(temp).format(value);
    }


3.验证是否是数字
    private static boolean isNumeric(String str) {
       try{
           Double.parseDouble(str);
       }catch (Exception e) {
           return false;
       }
       return true;
    }


4.判断字符串是否为空
    public static boolean isNull(String str){
       return str==null || "".equals(str.trim()) || "NULL".equalsIgnoreCase(str.trim()) || "undefined".equalsIgnoreCase(str.trim()) || "NaN".equalsIgnoreCase(str.trim());
    }


5.文件读写处理
    //读文件
    public static String readFileToString(String filePath,String encoding){
       File file=null;
       InputStream input = null;
       try {
           file=new File(filePath);
           if(file.exists()){
              input = new FileInputStream(file);
              return IOUtils.toString(input, encoding);
           }
       }catch (Exception e) {
           logger.error("读取文件异常。"+e.getMessage());
       }
       finally {
           IOUtils.closeQuietly(input);
       }
       return "";
    }
    // 写文件
    public static void writeFile(String filePath, String data, String encoding) {
       File file = null;
       OutputStream output = null;
       try {
           if (data != null) {
              file = new File(filePath);
              output = new FileOutputStream(file);

              if (encoding == null) {
                  IOUtils.write(data, output);
              } else {
                  output.write(data.getBytes(encoding));
              }
           }
       } catch (Exception e) {
           logger.error("写入文件异常。" + e.getMessage());
       } finally {
           IOUtils.closeQuietly(output);
       }
    }
    // 写文件
    public static void writeFile(String filePath, InputStream inputStream, String encoding) {
       try {
           BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));  
           StringBuilder sb = new StringBuilder();  

           String line = null;  
           while ((line = reader.readLine()) != null) {  
              sb.append(line + "\n");  
           }  
           writeFile( filePath,  sb.toString(),  encoding);

       } catch (Exception e) {
           e.printStackTrace();
           logger.error("写入文件异常。" + e.getMessage());
       }finally {  
           try {  
              inputStream.close();  
           } catch (IOException e) {  
              e.printStackTrace();  
           }  
       }
    }


6.将list集合组成字符串
       /**
        * @specification :提取list中表头列,形成字符串a,b,c
        * @param list: list列
        * @param flag: 提取map中key值
        * @param initStr: 初始化字符串
        * @return :String
        * @exception :Exception
        */
       public static String getStrFromList(List list,String flag,String initStr) {
           // TODO Auto-generated method stub
           //将字符串大写,方便获取map值
           flag = flag.toUpperCase();
           String flagStr = "";
         
           //获取当前用户、页面对应的条件
           String condition = initStr;
           if(list != null && list.size() > 0){
              for(int i=0;i<list.size();i++){
                  Map map = (Map) list.get(i);
                  flagStr +="," + map.get(flag);
              }
           }
           if(flagStr != null && !"".equals(flagStr)){
              condition = flagStr.substring(1);
           }
         
           return condition;
       }


7.Java反射
/***
         *
         * @specification :通过方法名,寻找反射相应的方法,获得变量值
         * @param :frac_value 方法名 FormMRFractileInfo 类对象
         * @return :方法对应的值
         * @exception :
         */
       public static String getMethodValue(String frac_value,Object frc) {
              // TODO Auto-generated method stub
               String rating_number = null ;
               //  获取反射类
               Class frc_class = frc.getClass();
               Method frc_method;
              try {
                  // 获取反射方法
                  frc_method = frc_class.getDeclaredMethod(frac_value);
                  // 获取值
                  rating_number = (String) frc_method.invoke(frc);
              } catch (SecurityException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              } catch (NoSuchMethodException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              } catch (IllegalArgumentException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              } catch (IllegalAccessException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              } catch (InvocationTargetException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
              return rating_number;
           }
     
       /***
         *
         * @param value
        * @specification :通过方法名,寻找反射相应的方法,设置变量值
         * @param :frac_value 方法名 FormMRFractileInfo 类对象
         * @return :方法对应的值
         * @exception :
         */
       public static void setMethodValue(String frac_value,Object frc, String value) {
           //  获取反射类
           Class frc_class = frc.getClass();
           Method frc_method;
           try {
              // 获取反射方法
              frc_method = frc_class.getDeclaredMethod(frac_value, new Class[]{java.lang.String.class});
              // 设置值
              frc_method.invoke(frc, value);
           } catch (SecurityException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
           } catch (NoSuchMethodException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
           } catch (IllegalArgumentException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
           } catch (IllegalAccessException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
           } catch (InvocationTargetException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
           }
       }


8.截屏
public static void main(String[] args) {
            try {
                int width = (int)Toolkit.getDefaultToolkit().getScreenSize().getWidth();
                int height = (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight();
                Robot robot = new Robot();
                BufferedImage image = robot.createScreenCapture(new Rectangle(width,height));
                ImageIO.write (image, "png" , new File("E:/1.jpg")); 
                
            } catch (AWTException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


9.excel2007读写-POI
private static void test(String strPath) throws Exception{
       XSSFWorkbook xwb;
       xwb = new XSSFWorkbook(strPath);
       XSSFSheet sheet = xwb.getSheetAt(0);
//     读取第一章表格内??
//     定义 row、cell
       XSSFRow row;
       String cell;
//     循环输出表格中的内容
       for (int i = sheet.getFirstRowNum(); i < sheet.getPhysicalNumberOfRows(); i++ ) {
       row = sheet.getRow(i);
       for (int j = row.getFirstCellNum(); j < row.getPhysicalNumberOfCells(); j++ ) {
//     通过 row.getCell(j).toString() 获取单元格内容,
       cell = row.getCell(j)!=null?row.getCell(j).toString():"";
       System.out.print(cell+"\t");
       }
       System.out.println("");
       }
       }
测试:test("F:\\11.xlsx");


10.获取IP地址对应的MAC地址
/**
     *
     * @Title:
     * @Description: 同工ip取得对应的mac值
     * @param @param args    设定文件
     * @return    返回类型
     * @throws
     */
    public String getMACAddress(String ip){
       String str = "";
       String macAddress = "";
     
       try {
       Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
       InputStreamReader ir = new InputStreamReader(p.getInputStream());
       LineNumberReader input = new LineNumberReader(ir);
           for (int i = 1; i < 100; i++) {
              str = input.readLine();
              if (str != null) {
                  if (str.indexOf("MAC") > 1) {
                     macAddress = str.substring(str.indexOf("MAC Address") + 14, str.length());
                     System.out.println(ip+"/macAddress==="+macAddress);
                     break;
                  }
              }
           }
       } catch (IOException e) {
       e.printStackTrace(System.out);
       }
     
       return macAddress;
       }
测试:getMACAddress("10.1.1.1")


11.获取随机数
/**
     *
     * @Title:
     * @Description: 取得随机数据
     * @param @param args    设定文件
     * @return    返回类型
     * @throws
     */
    public static void main(String[] args) {
        Random rd = new Random();
       //随机正数
       System.out.println(Math.abs(Math.random()*10));
       //随机正整数
       System.out.println(Math.abs(rd.nextInt())%10);
    }


12.获取当前系统物理文件夹
//取得目前程序所在电脑系统用户、用户文档地址、当前代码物理地址
System.out.println("user_name:" + System.getProperty("user.name"));   
           System.out.println("user_home:" + System.getProperty("user.home"));   
           System.out.println("user_dir:" + System.getProperty("user.dir"));


13.socket连接
package test;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

public class TestSocket {
    public static void main(String[] args) {
       try {
           ArrayList a = new ArrayList();
           a.add(a);
           //socket接收
           ServerSocket soc = new ServerSocket(6666);
           // 服务器接收到客户端的数据后,创建与此客户端对话的Socket
           Socket socket = soc.accept();

//         用于向客户端发送数据的输出流
           DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
//         用于接收客户端发来的数据的输入流
           DataInputStream dis = new DataInputStream(socket.getInputStream());
         
           System.out.println("服务器接收到客户端的连接请求:" + dis.readUTF());
//         服务器向客户端发送连接成功确认信息
           dos.writeUTF("接受连接请求,连接成功!");
//         不需要继续使用此连接时,关闭连接
           socket.close();
           soc.close();
       } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
    }
    //客户端socket
    void cilentSocketDemo(){
     
       Socket socket = null;
       try {
           socket = new Socket("localhost",6666);//ip,端口

           //获取输出流,用于客户端向服务器端发送数据
           DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
           //获取输入流,用于接收服务器端发送来的数据
           DataInputStream dis = new DataInputStream(socket.getInputStream());
           //客户端向服务器端发送数据
           dos.writeUTF("我是客户端,请求连接!");

           //打印出从服务器端接收到的数据
           System.out.println(dis.readUTF());
           //不需要继续使用此连接时,记得关闭哦
           socket.close();
       } catch (UnknownHostException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }

    }
}
发表评论
用户名: 匿名