BufferedReader readLine返回值在scala中不被理解为字符串?

时间:2013-12-01 08:58:04

标签: scala bufferedreader

虽然我知道有一些原生的scala方法可以做到以下几点,但是理解这种行为会很有见地。

对于以下代码片段,for循环迭代器不正确:

val br = new BufferedReader(new FileReader("/tmp/test.txt"))
val stdin = new FileOutputStream("/tmp/x.txt")
for (line : String <- br.readLine) {
  //    val mys = new String(line)
  stdin.write(line)
  stdin.write('\n')
}

迭代器行给出以下编译错误:

scrutinee is incompatible with pattern type;
 found   : String
 required: Char
    for (line : String <- br.readLine) {

            ^

2 个答案:

答案 0 :(得分:5)

br.readLine返回一个字符串,字符串上的map操作适用于Char

for { line <- br.readLine }

相同

br.readLine.map { line =>

您可以这样写:

val br = new BufferedReader(new FileReader("/tmp/test.txt"))
val outfile = new FileOutputStream("/tmp/x.txt")

var line:String = ""

while ({ line = br.readLine() ; line != null } ) {

   outfile.write(line.getBytes)
   outfile.write('\n')
}

答案 1 :(得分:0)

在进一步搞乱后,发现了两个问题。

A)&#34; line&#34;需要成为一个&#34; var&#34;在另外的声明如下:

var line:String = ""
for (line <- br.readLine) {

B)for循环遍历字符串的各个字符(而不是输入中的行)。正确的代码是:

var line:String = ""
while ({line = in.readLine();  line!= null}) {

C)现在整个代码段:

import java.io._
val br = new BufferedReader(new FileReader("/tmp/test.txt"))
val stdin = new FileOutputStream("/tmp/x.txt")
var line:String = ""
  while ({line = in.readLine();  line!= null}) {
    println(line)
    if (line!=null) {
        stdin.write(line.getBytes)
        stdin.write('\n')
    } else {}
}
br.close
stdin.flush
stdin.close

然而,即使这个解决方案最终也会:

java.io.IOException: Stream closed
    at java.io.BufferedReader.ensureOpen(BufferedReader.java:97)
    at java.io.BufferedReader.readLine(BufferedReader.java:292)
    at java.io.BufferedReader.readLine(BufferedReader.java:362)
    at .<init>(<console>:46)
    at .<clinit>(<console>)
    at .<init>(<console>:7)
    at .<clinit>(<console>)
    at $print(<console>)

并注意&#34; println&#34;永远不会执行for循环。