相关疑难解决方法(0)

如何在Scala中写入文件?

对于阅读,有一个有用的抽象Source.如何在文本文件中写入行?

file-io scala scala-2.8

153
推荐指数
11
解决办法
14万
查看次数

Scala:"使用"功能

我已经定义了'使用'功能如下:

def using[A, B <: {def close(): Unit}] (closeable: B) (f: B => A): A =
  try { f(closeable) } finally { closeable.close() }
Run Code Online (Sandbox Code Playgroud)

我可以这样使用它:

using(new PrintWriter("sample.txt")){ out =>
  out.println("hellow world!")
}
Run Code Online (Sandbox Code Playgroud)

现在我很好奇如何定义'使用'函数来获取任意数量的参数,并且能够单独访问它们:

using(new BufferedReader(new FileReader("in.txt")), new PrintWriter("out.txt")){ (in, out) =>
  out.println(in.readLIne)
}
Run Code Online (Sandbox Code Playgroud)

scala tuples using

30
推荐指数
4
解决办法
2万
查看次数

什么是使用scala.io.Source的正确方法?

在许多示例中,描述了您可以使用scala.io.Source来读取整个文件,如下所示:

val str = scala.io.Source.fromFile("test.txt").mkString()
Run Code Online (Sandbox Code Playgroud)

但没有提到关闭底层流.为什么Scala没有提供方便的方法来执行此操作,例如Python中的with子句?它看起来很有用但并不困难.

有没有其他更好的方法在Scala中安全地执行此操作,我的意思是读取整个文件?

scala scala-2.8

28
推荐指数
4
解决办法
2万
查看次数

java try-with-resource不使用scala

在Scala应用程序中,我尝试使用java nio try-with-resource构造从文件中读取行.

Scala版本2.11.8
Java版本1.8

try(Stream<String> stream = Files.lines(Paths.get("somefile.txt"))){
    stream.forEach(System.out::println); // will do business process here
}catch (IOException e) {
    e.printStackTrace(); // will handle failure case here
}  
Run Code Online (Sandbox Code Playgroud)

但是编译器会抛出错误,例如
找不到:值流
◾尝试没有捕获或者最终等同于将其主体放入块中; 没有例外处理.

不确定是什么问题.我是使用Java NIO的新手,所以非常感谢任何帮助.

java scala try-with-resources

11
推荐指数
1
解决办法
7209
查看次数

如何确保Scala中的for-comprehension中的资源被关闭

如何在Scala中进行for-understandingnce中最好地处理带有副作用的函数?

我有一个理解,通过调用函数f1创建一种资源(x)开始.这个资源有一个close -method需要在结束时调用,但是如果for-comprehension以某种方式失败(除非.

所以我们有类似的东西:

import scala.util.{Try,Success,Failure}

trait Resource {
  def close() : Unit
}

// Opens some resource and returns it as Success or returns Failure
def f1 : Try[Resource] = ...
def f2 : Try[Resource] = ...

val res = for {
  x <- f1
  y <- f2
} yield {
  (x,y)
}
Run Code Online (Sandbox Code Playgroud)

我应该在哪里调用close方法?我可以在for-comprehension结束时将其称为最后一个语句(z < - x.close),在yield-part中,或在for-comprehension之后(res._1.close).它们都不能确保在发生错误时调用close(例如,如果f2失败).或者,我可以分开

x <- f1 
Run Code Online (Sandbox Code Playgroud)

出于这样的理解:

val res = f1
res match {
  case Success(x) …
Run Code Online (Sandbox Code Playgroud)

scala

4
推荐指数
1
解决办法
905
查看次数

标签 统计

scala ×5

scala-2.8 ×2

file-io ×1

java ×1

try-with-resources ×1

tuples ×1

using ×1