`

几种常见的数据类型转换(一)------String转其他类型

    博客分类:
  • JAVA
阅读更多

常用数据类型转换:

1.String 数据类型

<1> String-------->int

 

    
       /**
    	 * function1
    	 */
       String str0 = "123";
    	try {
    	    int a = Integer.parseInt(str0);
    	} catch (NumberFormatException e) {
    	    e.printStackTrace();
    	}
       /**
    	 * function2
    	 */ 
    	String str1 = "234";
    	try {
    	    int b = Integer.valueOf(str1).intValue();
    	} catch (NumberFormatException e) {
    	    e.printStackTrace();
    	}

 在转换过程中需要注意,因为字符串中可能会出现非数字的情况,所以在转换的时候需要捕捉处理异常

 

<2>String-------->long

       /**
    	 * function1
    	 */ 
	String str0 ="123";
    	try {
		long l1 = Long.parseLong(str0);
    	} catch (NumberFormatException e) {
    	    e.printStackTrace();
    	}
       /**
    	 * function2
    	 */ 
		String str1 = "234";
		try {
		long l2 = Long.parseLong(str1,3);
		} catch (NumberFormatException e) {
    	    e.printStackTrace();
    	}
       /**
    	 * function3
    	 */ 
		String str2 = "456";
		try {
		long l3 = Long.valueOf("123").longValue();
		} catch (NumberFormatException e) {
	    e.printStackTrace();
		}

         Long.ValueOf("String")返回Long包装类型
       
        Long.parseLong("String")返回long基本数据类型

 

 

<3>String-------->double

 

         double db;  
    	 String str;  
    	 str = "6.12345";  
    	   try {  
        /**
    	  * function1
    	  */ 
    	    db = new Double(str).doubleValue();//xxxValue() method  
    	    //Returns a new double initialized to the value represented  
    	    //by the specified String 
       /**
    	 * function2
    	 */ 
    	    db = Double.parseDouble(str); 
       /**
    	 * function3
    	 */ 
    	    db = Double.valueOf(str).doubleValue();//doubleValue() method  
    	   } catch (Exception e) {  
    	    e.printStackTrace();  
    	   }

 

<4>String-------->date

      /**
    	 * function1
    	 */ 
       String dateString = "2017-7-26 ";  
        try  
        {  
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd ");  
            Date date = sdf.parse(dateString);  
        }  
        catch (ParseException e)  
        {  
            System.out.println(e.getMessage());  
        }
       /**
    	 * function2
    	 */ 
        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);  
            }  
        } 

 

分享到:
评论
1 楼 阿拉扫思密达 2017-07-26  
转自:http://swordshadow.iteye.com/blog/1927685
java 常用的几种数据类型转换

    博客分类: java

java

几种常见的数据类型转换,记录一下
      
一、Timestap与String  BigDecimal与String



        项目使用的数据库Oracle,字段类型为Date与Number,ORM框架为Mybatis,返回类型和参数类型均为         java.util.Map,此时方法返回的Map {END_DATE=2012-11-11 14:39:35.0, FLAG=0} ,本以为(String)map.get(""),直接转换为String类型,最后报错了,为了保证代码健壮,强制类型转换时可以使用instance of判段类型

   

        Timestap转String
Java代码  收藏代码

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 
    java.sql.Timestamp ts= (java.sql.Timestamp) map.get("END_DATE"); 
    String endDate=sdf.format(ts); 



        String转化为Timestamp

  
Java代码  收藏代码

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
    String time = sdf.format(new Date()); 
    Timestamp ts = Timestamp.valueOf(time); 

    

        BigDecimal转String

当valueOf()和toString()返回相同结果时,宁愿使用前者

因为调用null对象的toString()会抛出空指针异常,如果我们能够使用valueOf()获得相同的值,那宁愿使用valueOf(),传递一个null给valueOf()将会返回“null”,尤其是在那些包装类,像Integer、Float、Double和BigDecimal。    
Java代码  收藏代码

    java.math.BigDecimal bd = (BigDecimal)m1.get("FLAG"); 
    String flag = bd.toString();  // 
    如果bd为null抛出 "Exception in thread "main" java.lang.NullPointerException" 
     
    String flag = String.valueOf(bd); 



        String转BigDecimal

  
Java代码  收藏代码

    BigDecimal bd = new BigDecimal("10"); 

   

   String 去掉换行



   
Java代码  收藏代码

    str.replaceAll("\n\r","").replaceAll("\n",""); 


java去除字符串中的空格、回车、换行符、制表符




        二、Date与String之间的转换



        String转Date   
Java代码  收藏代码

    DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
    Date date = null;String str = null; 
    str = "2010-10-10"; 
    date = format.parse(str); //Sun Oct 10 00:00:00 CST 2010 
    date = java.sql.Date.valueOf(str); //返回的是java.sql.Date 2010-10-10 



        Date转String

   
Java代码  收藏代码

    DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
    Date date = null;String str = null; 
    date = new Date();  
    str = format.format(date);  

        省略了异常处理部分



        把字符串转化为java.sql.Date

        字符串必须是"yyyy-mm-dd"格式,否则会抛出IllegalArgumentException异常

    java.sql.Date sdt=java.sql.Date.valueOf("2010-10-10");





三、文件与byte数组的相互转换



所有的文件在硬盘或在传输时都是以字节的形式传输的



文件转byte[]


Java代码  收藏代码

    public static void readFile() throws Exception { 
            FileInputStream fis = new FileInputStream("luffy.gif"); 
            BufferedInputStream bis = new BufferedInputStream(fis); 
            ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
            int num = bis.read();                 //可能会溢出  超过int最大值  Exception in thread "main" java.lang.OutOfMemoryError: Java heap space 
            while (num != -1) { 
                baos.write(num); 
            } 
            bis.close(); 
            byte[] array = baos.toByteArray(); 
            System.out.println(array.toString()); 
             
        } 
     
    //推荐 
     
     
    FileInputStream in = new FileInputStream(new File("d:/one.gif"));   
             ByteArrayOutputStream out = new ByteArrayOutputStream(4096);   
             byte[] b = new byte[4096];   
             int n;   
             while ((n = in.read(b)) != -1) {   
                 out.write(b, 0, n);   
             }   
             in.close();   
             out.close();   
             byte[] ret = out.toByteArray(); 



byte[] 转文件


Java代码  收藏代码

    public static void writeFile(byte[] array) throws Exception{ 
            FileOutputStream fos =new FileOutputStream("one.gif"); 
            BufferedOutputStream bos =new BufferedOutputStream(fos); 
            bos.write(array); 
            bos.close(); 
            System.out.println("success"); 
        } 



文件与 String 的转换


Java代码  收藏代码

    /** 
           * 文本文件转换为指定编码的字符串 
           * 
           * @param file         文本文件 
           * @param encoding 编码类型 
           * @return 转换后的字符串 
           * @throws IOException 
           */  
          public static String file2String(File file, String encoding) {  
                  InputStreamReader reader = null;  
                  StringWriter writer = new StringWriter();  
                  try {  
                          if (encoding == null || "".equals(encoding.trim())) {  
                                  reader = new InputStreamReader(new FileInputStream(file), encoding);  
                          } else {  
                                  reader = new InputStreamReader(new FileInputStream(file));  
                          }  
                          //将输入流写入输出流  
                          char[] buffer = new char[1024];  
                          int n = 0;  
                          while (-1 != (n = reader.read(buffer))) {  
                                  writer.write(buffer, 0, n);  
                          }  
                  } catch (Exception e) {  
                          e.printStackTrace();  
                          return null;  
                  } finally {  
                          if (reader != null)  
                                  try {  
                                          reader.close();  
                                  } catch (IOException e) {  
                                          e.printStackTrace();  
                                  }  
                  }  
                  //返回转换结果  
                  if (writer != null)  
                          return writer.toString();  
                  else return null;  
          } 



String 与 File 的转换


Java代码  收藏代码

    /** 
            * 将字符串写入指定文件(当指定的父路径中文件夹不存在时,会最大限度去创建,以保证保存成功!) 
            * 
            * @param res            原字符串 
            * @param filePath 文件路径 
            * @return 成功标记 
            */  
           public static boolean string2File(String res, String filePath) {  
                   boolean flag = true;  
                   BufferedReader bufferedReader = null;  
                   BufferedWriter bufferedWriter = null;  
                   try {  
                           File distFile = new File(filePath);  
                           if (!distFile.getParentFile().exists()) distFile.getParentFile().mkdirs();  
                           bufferedReader = new BufferedReader(new StringReader(res));  
                           bufferedWriter = new BufferedWriter(new FileWriter(distFile));  
                           char buf[] = new char[1024];         //字符缓冲区  
                           int len;  
                           while ((len = bufferedReader.read(buf)) != -1) {  
                                   bufferedWriter.write(buf, 0, len);  
                           }  
                           bufferedWriter.flush();  
                           bufferedReader.close();  
                           bufferedWriter.close();  
                   } catch (IOException e) {  
                           e.printStackTrace();  
                           flag = false;  
                           return flag;  
                   } finally {  
                           if (bufferedReader != null) {  
                                   try {  
                                           bufferedReader.close();  
                                   } catch (IOException e) {  
                                           e.printStackTrace();  
                                   }  
                           }  
                   }  
                   return flag;  
           } 









byte与16进制字符串转换


Java代码  收藏代码

    public static String byte2hex(byte[] b) { 
           String hs = "";   
           String stmp = "";   
           for (int n = 0; n < b.length; n++) {   
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));   
            if (stmp.length() == 1)   
             hs = hs + "0" + stmp;   
            else   
             hs = hs + stmp;   
           }   
           return hs;   
        }   
       
        public static byte[] hex2byte(String str) {   
           if (str == null)   
            return null;   
           str = str.trim();   
           int len = str.length();   
           if (len == 0 || len % 2 == 1)   
            return null;   
           
           byte[] b = new byte[len / 2];   
           try {   
            for (int i = 0; i < str.length(); i += 2) {   
             b[i / 2] = (byte) Integer   
               .decode("0x" + str.substring(i, i + 2)).intValue();   
            }   
            return b;   
           } catch (Exception e) {   
            return null;   
           }   
        }   



InputStream 转化为 byte[]


Java代码  收藏代码

    public static byte[] readStream(InputStream is) throws Exception{   
            byte[] bytes = new byte[1024];   
            int leng;   
            ByteArrayOutputStream baos = new ByteArrayOutputStream();   
            while((leng=is.read(bytes)) != -1){   
                baos.write(bytes, 0, leng);   
            }   
            return baos.toByteArray();   
        }   



图像文件转byte[]
Java代码  收藏代码

    public static byte[] toByteArray(File file) throws Exception { 
        BufferedImage img = ImageIO.read(file); 
        ByteArrayOutputStream buf = new ByteArrayOutputStream((int) file.length()); 
        try { 
            ImageIO.write(img, "", buf); 
        } catch (Exception e) { 
            e.printStackTrace(); 
            return null; 
        } 
        return buf.toByteArray(); 
    } 









四、byte[]与base64转换



BASE64应用广泛,在很多API中参数设计为String,可以将base64转为String 方便调用


Java代码  收藏代码

    //方法一 
    sun.misc.BASE64Decoder dec = new BASE64Decoder(); 
    sun.misc.BASE64Encoder enc = new BASE64Encoder(); 
      
    //javax.xml.bind.DatatypeConverter it has 2 methods of interest: 
    //方法二  
    public static byte[] parseBase64Binary( String lexicalXSDBase64Binary ) 
    public static String printBase64Binary( byte[] val ) 





可用于图片显示  <img alt="" src="data:image/png;base64,base64String...."> ,关于base64图片参考:html img Src base64 图片显示



注意两种方式生成的字符串长度不同,很多第三方的 jar 也含有 base64 功能,可能存在差异, 在项目中要统一为一种方式





     As of v6, Java SE ships with JAXB. javax.xml.bind.DatatypeConverter has static methods that make this easy. See parseBase64Binary() and printBase64Binary().



      Decode Base64 data in Java



    有时候需要去掉特殊字符如:



        
Java代码  收藏代码

    uploadImgMap.put("FILE",enc.encode(fileByte).replaceAll("(\r\n|\n)", "")) ;  //伪代码 





    五,json 与 xml 互相转换

  

   字符串转json


Java代码  收藏代码

    String str = "{ \"data\": \"{a:1,b:2}\" }"; 
    JSONObject json = (JSONObject)JSONSerializer.toJSON(str); 

相关推荐

    java数据类型的转换简单数据类型之间的转换 (2). 字符串与其它数据类型的转换 (3). 其它实用数据类型转换

    一些初学JAVA的朋友可能会遇到JAVA的数据类型之间转换的苦恼,例如,整数和float,double型之间的转换,整数和String类型之间的转换,以及处理、显示时间方面的问下面笔者就开发中的一些体会介绍给大家。 我们知道,...

    java中long类型转换为int类型-java long转int.pdf

    由int类型转换为long类型是向上转换,可以直接进行隐式转换,但由long类型转换为int类型是向下转换,可能会出现数据溢出情况: 主要以下几种转换方法,供参考: 一、强制类型转换 [java] long ll = 300000; int ...

    浅析C#数据类型转换的几种形式

    1、Convert.ToInt32(); //转换成32位的整数。2、变量.ToString();/最常见的转换成 字符串。3、”订单”+2514 //后面的数字会转换为字符串。4、((类名A)对象名X) //强行将 ...隐式数值C#数据类型转换:从 sbyte 到 sho

    大小写金额转换-源码

    票据和结算凭证是银行、单位和个人凭以记载账务的会计凭证,是记载经济业务和明确经济责任的一种书面证明。因此,填写票据和结算凭证,必须做到标准化、规范化,要要素齐全、数字正确、字迹清晰、不错漏、不潦草,...

    详解Javascript数据类型的转换规则

    三、数据类型转换 JS内部提供不同数据类型的自动转换机制,在某处预期为某种类型而不是某种类型时,就会自动转换为预期类型,这就是我们常说的隐式转换。 1、强制类型转换 在了解隐式转换的规则前

    简单数据类型的转换

    这里我们简单讲一下这几种数据类型之间的转换: 1、其他数据转换为数值 Number(),这是将括号里的内容看做一个整体然后进行转换,如果内容为一个合法的数字, 则转换为一个数字,例:Number(‘100’) =&gt; 100 ...

    powerbuilder

    参数printjobnumber:用PrintOpen()函数打开的打印作业号string:string类型,指定要打印的文本x:integer类型,指定文本开始打印位置的x坐标,以千分之一英寸为单位y:integer类型,指定文本开始打印位置的y坐标,...

    C# char类型字符转换大小写的实现代码

    您可能感兴趣的文章:C#中使用强制类型实现字符串和ASCII码之间的转换C#、.Net中把字符串(String)格式转换为DateTime类型的三种方法C#自定义类型强制转换实例分析浅析C#数据类型转换的几种形式C#基础之数据类型转换...

    Advanced Bash-Scripting Guide <>

    33.3. 测试和比较: 另一种方法 33.4. 递归 33.5. 彩色脚本 33.6. 优化 33.7. 各种小技巧 33.8. 安全话题 33.8.1. 被感染的脚本 33.8.2. 隐藏Shell 脚本源码 33.9. 移植话题 33.10. 在Windows 下进行Shell 编程 34. ...

    新版Android开发教程.rar

    开放手机联盟包括手机制造商、手机芯片厂商和移动运营商几类。目前,联盟成员 数 量已经达到了 43 家。 移动手机联盟创始成员: Aplix 、 Ascender 、 Audience 、 Broadcom 、中国移动、 eBay 、 Esmertec 、谷歌、...

    JavaScript笔记

    7.数据类型转换函数 :(方法前不需要对象调用的:全局函数) |--toString():转换成字符串。所有数据类型均可转换为 string 类型; |--parseInt():强制转换成整数。如果不能转换,则返回 NaN(not a number); ...

    springmybatis

    查询出列表,也就是返回list, 在我们这个例子中也就是 List&lt;User&gt; , 这种方式返回数据,需要在User.xml 里面配置返回的类型 resultMap, 注意不是 resultType, 而这个resultMap 所对应的应该是我们自己配置的 ...

    基于c#CP3平面网严密平差数据处理

    基于c#CP3平面网严密平差数据处理 using System; using System.Collections.Generic; using System.Collections;//使用动态数组需要添加的语句 using System.ComponentModel; using System.Data; using System....

    如何将图片转换成二进制存储

    图片的常见存储与读取凡是有以下几种: 存储图片:以二进制的形式存储图片时,要把数据库中的字段设置为Image数据类型(SQL Server),存储的数据是Byte[]. 1.参数是图片路径:返回Byte[]类型: public byte[] ...

    Linux高级bash编程

    "Including"一个数据文件 11-21. 一个没什么用的,source自身的脚本 11-22. exec的效果 11-23. 一个exec自身的脚本 11-24. 在继续处理之前,等待一个进程的结束 11-25. 一个结束自身的脚本. 12-1. 使用ls命令来创建一...

    ExtAspNet v2.2.1 (2009-4-1) 值得一看

    -一个典型应用,在Window控件中打开新页面,如果传递的参数不正确,则首先提示参数不对然后关闭此弹出窗口。 -ExtAspNet.Alert.Show("参数错误!", String.Empty, ExtAspNet.ActiveWindow.GetCloseReference());...

    Android使用Json与Asp.Net交互(上传/下载数据集)

    示例中传输的数据未实体类集合,其中以int,string,string[],DateTime几种常用的数据类型作为实体类的字段。 Asp.Net服务器端借用Newtonsoft.Json.dll进行直接把对象转换成成Json格式的字符串,或把Json字符串转换...

    简单介绍Python中的几种数据类型

    大体上把Python中的数据类型分为如下几类: Number(数字) 包括int,long,float,complex String(字符串) 例如:hello,"hello",hello List(列表) 例如:[1,2,3],[1,2,3,[1,2,3],4] Dictionary(字典) 例如:{1:...

    java-servlet-api.doc

    Servlet引擎载入Servlet后,Servlet引擎必须对Servlet进行初始化,在这一过程中,你可以读取一些固定存储的数据、初始化JDBC的连接以及建立与其他资源的连接。 在初始化过程中,javax.servlet.Servlet接口的init()...

    二进制XML存储方案

    · 暂时只实现了string/long/byte[],还没有提供其它类型的解析与转换; · XML标签不支持属性,只支持子元素:) · 是不是可以提供一个oxm模型,完成BinXML与Object之间的直接映射,现在这个映射工作还是人工...

Global site tag (gtag.js) - Google Analytics