问题描述
提示:scala中读取文本文件的行时,导致死循环
object BugCode extends App {
// 读取数据
// 1. 创建File + FileReader + BufferedReader
val inPath = "1.txt"
private val bufferedReader = new BufferedReader(new FileReader(new File(inPath)))
// 2. 读取数据
private var str: String = ""
while ((str = bufferedReader.readLine) != null) {
println(str)
}
// 3. 关闭流
bufferedReader.close
println("读取完毕")
}
原因分析:
scala-赋值语句返回Unit:
var x: Int = 10
val y: Unit = (x = 100)
(str = bufferedReader.readLine) != null // Unit != null
java-赋值语句返回变量结果值 int x = 10; int y = (x = 100);
解决方案:
// 读取数据
// 1. 创建File + FileReader + BufferedReader
val inPath = "/usr/local/lib/mavne01/profu_12/prozi02/src/main/scala/com/maven/java/1.txt"
private val bufferedReader = new BufferedReader(new FileReader(new File(inPath)))
// 2. 读取数据
private var str: String = bufferedReader.readLine
while (str != null) {
println(str)
str = bufferedReader.readLine
}
// 3. 关闭流
bufferedReader.close
println("读取完毕")