Coverity中的bug们

本文探讨了Java编程中常见的编码问题与异常处理不当的情况,并提供了改进措施,包括默认编码问题、忽略异常返回值、异常捕获不当、Comparator未实现Serializable、装箱拆箱问题及字符串拼接优化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.DM_DEFAULT_ENCODING
 
1.1 Found reliance on default encoding in com.cmcc.aoi.httprequest.service.HttpRequest.sendGet(String, String): new java.io.InputStreamReader(InputStream)

Found a call to a method which will perform a byte to String (or String to byte) conversion, and will assume that the default platform encoding is suitable. This will cause the application behaviour to vary between platforms. Use an alternative API and specify a charset name or Charset object explicitly.

new BufferedReader(new InputStreamReader(connection.getInputStream()));
 
修改为: InputStreamReader fileData = new InputStreamReader(file ,"utf-8");


2. RV_RETURN_VALUE_IGNORED_BAD_PRACTICE    忽略了 java.io.File.mkdirs() 的异常返回值。

dirFile.mkdirs();
修改为
boolean mkdirs = dirFile.mkdirs();
logger.debug("debug",mkdirs);

3.RuntimeException 捕获 (FB.REC_CATCH_EXCEPTION)

catch(Exception e){}
改为
catch(RunTimeException e){
    throw e
}catch(Exception e){}

4.Comparator不实现Serializable(SE_COMPARATOR_SHOULD_BE_SERIALIZABLE)

implements Comparator,Serializable{}

5.Bx:有问题的装箱 (Boxing) 原语值 (FB.BX_UNBOXING_IMMEDIATELY_REBOXED)

    defect: 装箱 (boxed) 值被拆箱 (unboxed),然后又被立即重新装箱 (reboxed)。

Integer.valueOf(arg).intValue());-->Integer.valueOf(arg); 

6.Bx:有问题的装箱 (Boxing) 原语值 (FB.BX_BOXING_IMMEDIATELY_UNBOXED_TO_PERFORM_COERCION)

1. defect: 原语值被装箱 (boxed),然后又被拆箱 (unboxed) 以执行原语强制。

new Double(value).intValue();-->value.intValue())

7.在循环中使用了 + 运算符连接字符串 (FB.SBSC_USE_STRINGBUFFER_CONCATENATION)

 

每次循环里的字符串+连接,都会新产生一个string对象,在java中,新建一个对象的代价是很昂贵的,特别是在循环语句中,效率较低。故在循环中一般使用StringBuffer.append来代替string的+运算符

// This is bad
  String s = "";
  for (int i = 0; i < field.length; ++i) {
    s = s + field[i];
  }
 

// This is better

  StringBuffer buf = new StringBuffer();
  for (int i = 0; i < field.length; ++i) {
    buf.append(field[i]);
  }
  String s = buf.toString();

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值