Scala文件读写锁定问题

问题描述 投票:0回答:1

问题描述

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

我的文件

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

代码说明

main方法中,我从local获得类和罐子,并从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
scala locking filewriter file-locking
1个回答
1
投票

你有没有尝试在循环结束时关闭localsourceFile?当文件仍处于打开状态时,您确实无法确定数据是否已刷新到文件系统。

如果你将不变量移出循环(候选包括basefilenamerootabspath,甚至更多),它也会使事情变得更容易理解,并将代码分组到单独的函数中,以便您可以看到代码的结构更清楚,并专注于导致问题的部分。

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

© www.soinside.com 2019 - 2024. All rights reserved.