Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 如何排除java.lang.NumberFormatException:null的故障_Scala_Apache Spark_Apache Spark Sql - Fatal编程技术网

Scala 如何排除java.lang.NumberFormatException:null的故障

Scala 如何排除java.lang.NumberFormatException:null的故障,scala,apache-spark,apache-spark-sql,Scala,Apache Spark,Apache Spark Sql,我正在加载一个约有500000条记录的文件,例如 ROW_ID, COLOR_CODE, SHADE_ID 21, 22, 321 23, 31, 321 我这样加载它: val colorSchema = StructType(Array( StructField("ROW_ID", IntegerType, true), StructField("COLOR_CODE", IntegerType, true), StructField

我正在加载一个约有500000条记录的文件,例如

ROW_ID, COLOR_CODE, SHADE_ID
21, 22, 321
23, 31, 321
我这样加载它:

 val colorSchema = StructType(Array(
         StructField("ROW_ID", IntegerType, true),
         StructField("COLOR_CODE", IntegerType, true),
         StructField("SHADE_ID", IntegerType, true)

     def makeSchema(filename:String, tableName:String,
         tableSchema:StructType,uri:String){

         val table = spark.read.
           format("com.databricks.spark.csv").
           option("header", "true").
           schema(tableSchema).load(uri+filename).cache()
         table.registerTempTable(tableName.toUpperCase)
       }

makeSchema("colors.csv","colors",colorSchema,"s3://bucket/")
上面的代码运行良好。但是,当我运行以下查询时,我得到一个错误
java.lang.NumberFormatException:null

val r = spark.sql("select * from colors where COLOR_CODE = 22").take(1)
我做错了什么?我怎样才能有效地发现这个问题?我已目视扫描了文件,以查看
COLOR\u code
是否缺少值,但我无法目视查看任何值

更新


我问了另外一个问题,进一步缩小了问题的范围。CSV现在只有一行,我仍然得到相同的错误

您的csv中可能有空/空值,或者其他无法解析为int的字符串

如果问题是空值,您可以尝试以下方法:

val table = spark.read.
           format("com.databricks.spark.csv").
           option("header", "true").
           option("nullValue","null").
           option("treatEmptyValuesAsNulls,","true").
           schema(tableSchema).load(uri+filename).cache()

逗号后面的空格可能是问题所在。你的NFE看起来像这样吗

Caused by: java.lang.NumberFormatException: For input string: " 22"
这就是我重新创建你的问题时发生的事情。下面是修复它的方法:

    format("com.databricks.spark.csv").
    option("header", "true").
    option("parserLib", "UNIVOCITY").
    option("ignoreLeadingWhiteSpace", "true").

我相信你需要下载univocity jar。请参见

某个地方,
字符串
正试图被解析为数字类型,但是
字符串
的格式不正确。但我不知道在哪里。我假设SQL数据库将
行ID
颜色代码
、或
阴影ID
存储为
varchar
,而不是
int
,但这只是一个猜测。可能与此相关: