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

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

   

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.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

   

BigDecimal bd = new BigDecimal("10");

    

   String 去掉换行

 

    

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

 

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

 

 

        二、Date与String之间的转换

 

        String转Date    

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

    

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[]

 

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[] 转文件

 

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 的转换

 

  /** 
         * 文本文件转换为指定编码的字符串 
         * 
         * @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 的转换

 

 /** 
         * 将字符串写入指定文件(当指定的父路径中文件夹不存在时,会最大限度去创建,以保证保存成功!) 
         * 
         * @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进制字符串转换

 

	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[]

 

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[]

 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 方便调用

 

//方法一
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="https://img-blog.csdnimg.cn/2022010709001590259.png"> ,关于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

 

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

 

         

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

 

 

    五,json 与 xml 互相转换

   

   字符串转json

 

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

 

JAVA中如何将一个json形式的字符串转为json对象?

      

   JSON对象和字符串之间的相互转换

     

       Java版本 XML转JSON 或 JSON转XML

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值