You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala读取CSV文件报Source不属于org.apache.http.io包问题求助

错误原因
  • 包名冲突:代码中优先导入了org.apache.http._,该包下存在io子包,你调用io.Source时编译器会默认匹配org.apache.http.io而非你导入的scala.io包,因此抛出Source类不存在的错误。
  • 变量名不匹配:循环内定义的数组变量名为col,但打印时写为cols,运行时会抛出未定义变量的错误。
  • 资源未释放:使用Source.fromFile读取文件后没有主动关闭资源,可能造成文件句柄泄漏。
  • 代码内存在HTML转义字符:你复制的代码中存在"、<这类HTML转义符,需要替换为正常的双引号、小于号才能正常运行。
修复方案

修改读取CSV的代码段即可解决核心报错:

  1. 将io.Source.fromFile改为Source.fromFile即可,你已经显式导入了scala.io.Source,不需要额外加前缀,也可以写全路径scala.io.Source.fromFile彻底避免包冲突。
  2. 统一变量名,读取完成后关闭文件资源。
  3. 替换所有HTML转义符为正常字符。
完整修复后代码
import java.io._
import org.apache.commons._
import org.apache.http._
import org.apache.http.client._
import org.apache.http.client.methods.HttpPost
import org.apache.http.impl.client.DefaultHttpClient
import java.util.ArrayList
import org.apache.http.message.BasicNameValuePair
import org.apache.http.client.entity.UrlEncodedFormEntity
import com.google.gson.Gson
import scala.io.Source

case class Teacher(firstName: String, lastName: String, age: Int)
//case class Country(name: String, region: String, population: Int, area: Int, popDensity: Int, coastline: Int, netmigration: Int, infantMortality: Int, gdp: Int, literacy: Int, phones: Int, arable: Int, crops: Int, other: Int, climate: Int, birthrate: Int,deathrate: Int, agriculture: Int, industry: Int, service: Int)

object HttpJsonPostTest extends App {
    //read data 
    val source = Source.fromFile("countries.csv")
    for(line <- source.getLines){
        val cols = line.split(",").map(_.trim)
        println(s"${cols(0)}|${cols(1)}|${cols(2)}|${cols(3)}")
    }
    source.close()

    // create our object as a json string
    val marius = new Teacher("Lucas", "Geitle", 32)
    val mariusAsJson = new Gson().toJson(marius)

    // add name value pairs to a post object
    val post = new HttpPost("http://127.0.0.1:2379/v2/keys/big_data_course1")
    val nameValuePairs = new ArrayList[NameValuePair]()
    nameValuePairs.add(new BasicNameValuePair("value", mariusAsJson))
    post.setEntity(new UrlEncodedFormEntity(nameValuePairs))

    // send the post request
    val client = new DefaultHttpClient
    val response = client.execute(post)
    println("--- HEADERS ---")
    response.getAllHeaders.foreach(arg => println(arg))
}
补充说明

如果CSV文件存在字段内含逗号、换行符等复杂格式,不建议直接用split(",")拆分,可引入专门的CSV处理库降低出错概率。

内容的提问来源于stack exchange,提问作者Lucas Nuendel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 07:24:02