String 那些事儿

String ,Byte之间的转换
String—>byte:
byte []b;
String str=new String(b);
byte -->String:
String str="";
byte []b=str.getByte();

String 与InputStream之间的转换
String —>InputStream
String str="";
InputStream in=new ByteArrayInputStream(str.getByte());
InputStream—>String
public   String   inputStream2String   (InputStream   in)   throws   IOException   { 
        StringBuffer   out   =   new   StringBuffer(); 
        byte[]   b   =   new   byte[4096]; 
        for   (int   n;   (n   =   in.read(b))   !=   -1;)   { 
                out.append(new   String(b,   0,   n)); 
        } 
        return   out.toString(); 
方法二:
public   static   String   inputStream2String(InputStream   is)   throws   IOException{ 
        ByteArrayOutputStream   baos   =   new   ByteArrayOutputStream(); 
        int   i=-1; 
        while((i=is.read())!=-1){ 
        baos.write(i); 
        } 
        return   baos.toString(); 
}

byte与InputStream之间的转换
byte -->InputStream
InputStream sbs = new ByteArrayInputStream(byte[] buf); 

InputStream --->byte[]
  1.  public static final byte[] input2byte(InputStream inStream)  
  2.             throws IOException {  
  3.         ByteArrayOutputStream swapStream = new ByteArrayOutputStream();  
  4.         byte[] buff = new byte[100];  
  5.         int rc = 0;  
  6.         while ((rc = inStream.read(buff, 0100)) > 0) {  
  7.             swapStream.write(buff, 0, rc);  
  8.         }  
  9.         byte[] in2b = swapStream.toByteArray();  
  10.         return in2b;  
  11.     }

"=="和“equals”的区别
String a="abc" ;
String c=“abc";
String b=new String ("abc");
"=="和“equals”都可以用于值得比较,但是在应用于字符串的比较的时候,“==”比较的是两个对象的引用,上面a的值是abc,b的值也是abc,但是==返回的是false;因为b是一个新生成的一个对象;而c==a返回true,因为在String对象池中已经存在一个字符串abc,这时候JVM就会在栈中去找有没有一个值一样的对象,如果有只是从栈中将数据拿出来即可,并没有生成一个新的对象。当在 栈中找不到赋值给它的值得时候才会创建一个对象。

StringBuffer 和StringBuilder的区别
两者都可以用来动态的扩充字符串,避免不必要的String对象的生成,例如String abcd=a+b+c+d ;这个字符串生成了两个不必要的字符串对象 ab和abc,所以使用上述两个可以避免此现象,但是StringBuffer是线程不安全的,而StringBuilder是线程安全的。

String 字符串为null的问题
String str="";
boolean flag=false;
if(str!=null){
flag=true;
System.out.println("flag=="+flag);
}
结果为true;
str是一个空的字符串,但是在判断str!=null的时候返回的是true ,此时str是一个空的字符串,已经通过new生成了一个空的字符串对象,但是null还没有生成一个字符串对象,未指向任何内存空间,null和“”是不等价的。"".length() 为0,但是并不等于null。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值