Scala文件读写锁问题

时间:2019-02-25 15:39:01

标签: scala locking filewriter file-locking

问题描述

我有一个应用程序,可以将值写入文件,然后在while循环中将其读回程序。失败是因为仅在退出循环时才写入文件,而不是在每次迭代时才写入。因此,在下一个迭代中,我无法访问先前的迭代中应该写入文件的值。这是一个应用程序,用于从scala项目及其依赖项中读取测试文件,然后对其进行编辑并写回其原始文件。循环进行迭代编辑。我使用scalafix和scalameta。

我的文件

经过一些较早的讨论,我发现我有两个文件:localsourceFilelocal包含sourceFilelocal是Scala项目目录,sourceFile.scala子目录中的test/scala/文件。

代码说明

main方法中,我从local获取类和jar,并从sourceFile构建句法文档。然后,我通过ScalaFix修补程序API使用SemanticDocument进行编辑。最后,我想将编辑后的字符串写回到sourceFile,直到退出循环(也许是JVM),此操作才会失败。 查看有关代码的注释。这似乎与锁定有关。可能是我以前寻找jar,类和semanticdb的函数没有释放sourceFilelocal的锁。我通过在local以外的其他文件中进行写入来测试了这一点,并且得到了预期的行为。

问题

如何使Scala释放对这些文件的锁定?我尝试通过这些功能,然后把所有东西弄混了。我没有找到释放文件的方法。 与以下内容有关:Scala writing and reading from a file inside a while loop

package scalafix

import java.io.File
import java.net.URLClassLoader
import java.nio.file.Paths

import org.apache.commons.io.FileUtils
import org.apache.commons.io.filefilter.{DirectoryFileFilter, TrueFileFilter}
import scalafix.internal.patch.PatchInternals
import scalafix.internal.v1.InternalSemanticDoc
import scalafix.rule.RuleIdentifier
import scalafix.v1.{Patch, SemanticDocument, SyntacticDocument, _}
import scalafix.{Patch, RuleCtx, RuleName}

import scala.meta.Term.ApplyInfix
import scala.meta._
import scala.meta.inputs.Input
import scala.meta.internal.semanticdb.{Locator, TextDocument}
import scala.meta.internal.symtab.GlobalSymbolTable
import scala.meta.io.{AbsolutePath, Classpath}
import scala.meta.transversers.{SimpleTraverser, Transformer}
import scala.meta.{Name, Source}
import FileIO.enrichFile

import scala.sys.process._
import java.io.PrintWriter
import java.io.BufferedWriter
import java.io.FileWriter


object Printer{

//My function to write back to file
  def saveFile(filename: File, data: String): Unit ={
    val fileWritter: FileWriter = new FileWriter(filename)
    fileWritter.write(data)
    fileWritter.close()
  }
}

object Main extends App {
  //My variables to be updated after every loop
  var doc: SyntacticDocument = null
  var ast: Source = null
  var n = 3
  val firstRound = n
  var editedSuite:String = null
  do {
    val base  = "/Users/soft/Downloads/simpleAkkaProject/"
    // The local file
    val local = new File(base)
    // run an external command to compile source files in local into SemanticDocuments
    val result = sys.process.Process(Seq("sbt","semanticdb"), local).!
    // find jars in local.
    val jars = FileUtils.listFiles(local, Array("jar"), true).toArray(new Array[File](0))
      .toList
      .map(f => Classpath(f.getAbsolutePath))
      .reduceOption(_ ++ _)
    // find classes in local
    val classes = FileUtils.listFilesAndDirs(local, TrueFileFilter.INSTANCE, DirectoryFileFilter.DIRECTORY).toArray(new Array[File](0))
      .toList
      .filter(p => p.isDirectory && !p.getAbsolutePath.contains(".sbt") && p.getAbsolutePath.contains("target") && p.getAbsolutePath.contains("classes"))
      .map(f => Classpath(f.getAbsolutePath))
      .reduceOption(_ ++ _)
    // compute the classpath
    val classPath = ClassLoader.getSystemClassLoader.asInstanceOf[URLClassLoader].getURLs
      .map(url => Classpath(url.getFile))
      .reduceOption(_ ++ _)
    val all = (jars ++ classes ++ classPath).reduceOption(_ ++ _).getOrElse(Classpath(""))
    //combine classes, jars, and classpaths as dependencies into GlobalSymbolTable
    val symbolTable = GlobalSymbolTable(all)
    val filename = "AkkaQuickstartSpec.scala"
    val root = AbsolutePath(base).resolve("src/test/scala/")
    println(root)
    val abspath = root.resolve(filename)
    println(root)
    val relpath = abspath.toRelative(AbsolutePath(base))
    println(relpath)
    // The sourceFile
    val sourceFile = new File(base+"src/test/scala/"+filename)
   // use source file to compute a syntactic document
    val input = Input.File(sourceFile)
    println(input)
    if (n == firstRound){
      doc = SyntacticDocument.fromInput(input)
    }
    //println(doc.tree.structure(30))
    var documents: Map[String, TextDocument] = Map.empty
    //use scalameta internalSemantic document to locate semantic documents in the local directory
    Locator.apply(local.toPath)((path, db) => db.documents.foreach({
      case document@TextDocument(_, uri, text, md5, _, _, _, _, _) if !md5.isEmpty => { // skip diagnostics files
        if (n == firstRound){
          ast= sourceFile.parse[Source].getOrElse(Source(List()))
        }
        documents = documents + (uri -> document)
        println(uri)
      }
       println(local.canWrite)
        if (editedSuite != null){
          Printer.saveFile(sourceFile,editedSuite)
        }
    }))

    //compute an implicit semantic document of the sourceFile for editing
   val impl = new InternalSemanticDoc(doc, documents(relpath.toString()), symbolTable)
    implicit val sdoc = new SemanticDocument(impl)
    val symbols = sdoc.tree.collect {
      case t@ Term.Name("<") => {
        println(s"symbol for $t")
        println(t.symbol.value)
        println(symbolTable.info(t.symbol.value))
      }
    }
    //edit the sourceFile semanticDocument
    val staticAnalyzer = new StaticAnalyzer()  
    val p3 = staticAnalyzer.duplicateTestCase()
    val r3 = RuleName(List(RuleIdentifier("r3")))
    val map:Map[RuleName, Patch] = Map(r3->p3)
    val r = PatchInternals(map, v0.RuleCtx(sdoc.tree), None)
    val parsed = r._1.parse[Source]
    ast = parsed.getOrElse(Source(List()))
    doc =SyntacticDocument.fromTree(parsed.get)
    val list: List[Int] = List()

    editedSuite = r._1
     println(local.canWrite)
    //Write back to the sourceFile for every loop. This works only when we exit!
    Printer.saveFile(sourceFile,r._1)
    println("Loop: "+ n)
    n-=1

  } while(n>0)

}


  [1]: https://stackoverflow.com/questions/54804642/scala-writing-and-reading-from-a-file-inside-a-while-loop

1 个答案:

答案 0 :(得分:1)

您是否尝试过在循环结束时关闭localsourceFile?您确实不能确定在文件仍处于打开状态时数据是否已刷新到文件系统。

如果将不变式移出循环,这也将使事情变得更容易理解(候选包括basefilenamerootabspath,甚至可能更多),并将代码分为不同的功能,这样您就可以更清楚地看到代码的结构,并着重于引起问题的部分。

[这是我在回答上一个问题时给出的建议的重复内容]