Idiomatyczny sposób konwersji strumienia wejściowego na ciąg znaków w Scali

Mam przydatną funkcję, której używałem w Javie do konwersji strumienia wejściowego na ciąg znaków. Oto bezpośrednie tłumaczenie do Scali:

  def inputStreamToString(is: InputStream) = {
    val rd: BufferedReader = new BufferedReader(new InputStreamReader(is, "UTF-8")) 
    val builder = new StringBuilder()    
    try {
      var line = rd.readLine 
      while (line != null) { 
        builder.append(line + "\n")
        line = rd.readLine
      }
    } finally {
      rd.close
    }
    builder.toString
  }

Czy istnieje idiomatyczny sposób, aby to zrobić w Scali?

Author: bluish, 2011-03-07

3 answers

Dla Scala > = 2.11

scala.io.Source.fromInputStream(is).mkString

Dla Scali

scala.io.Source.fromInputStream(is).getLines().mkString("\n")
Robi to samo. Nie wiem, dlaczego chcesz uzyskać linie, a następnie przykleić je z powrotem. Jeśli możesz założyć, że strumień nie jest blokowany, możesz po prostu użyć .available, odczytać całość do tablicy bajtów i utworzyć z niej łańcuch znaków.
 161
Author: Rex Kerr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-08 13:15:50

Source.fromInputStream(is).mkString("") zrobi to samo.....

 72
Author: raam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-07 16:19:12

Szybszy sposób na to:

    private def inputStreamToString(is: InputStream) = {
        val inputStreamReader = new InputStreamReader(is)
        val bufferedReader = new BufferedReader(inputStreamReader)
        Iterator continually bufferedReader.readLine takeWhile (_ != null) mkString
    }
 10
Author: Kamil Lelonek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-01 14:53:07