SonarQube对我说“删除对构造函数“ Scanner(InputStream)的使用”

时间:2019-12-05 12:07:33

标签: java sonarqube

为了代替SonarQube,我应该使用什么代替Scanner?

final Scanner scan = new Scanner(System.in);

1 个答案:

答案 0 :(得分:1)

这是由于SonarQube中的以下rule

  

不应使用依赖默认系统编码的类和方法

     

使用依赖默认系统编码的类和方法,可以使代码在其“本地”环境中正常运行。但是对于那些使用不同编码的客户来说,这些代码可能会中断,这种方式极其难以诊断,并且如果不能修复,则几乎无法重现。

要解决此问题,可以使用定义了编码类型的扫描仪:

/**
 * Constructs a new <code>Scanner</code> that produces values scanned
 * from the specified input stream. Bytes from the stream are converted
 * into characters using the specified charset.
 *
 * @param  source An input stream to be scanned
 * @param charsetName The encoding type used to convert bytes from the
 *        stream into characters to be scanned
 * @throws IllegalArgumentException if the specified character set
 *         does not exist
 */
public Scanner(InputStream source, String charsetName) {
    this(makeReadable(Objects.requireNonNull(source, "source"), toCharset(charsetName)),
         WHITESPACE_PATTERN);
}