问题描述
我有一个应用程序,在这个应用程序中,我要将值写入一个文件中,并在一个while循环中将它们读入程序中。这会失败,因为只有当我退出循环而不是每次迭代时,文件才会被写入。因此,在下一次迭代中,我不能访问应该在前一次迭代中写入文件的值。这是一个应用程序,用于从scala项目及其依赖项读取测试文件,然后编辑它并将其写回原始文件。循环中的迭代编辑。我用的是标号和刻度。
我的文件
在之前的一些讨论之后,我突然想到我有两个文件:local和sourceFile。local包含sourceFile。local是Scala项目目录,sourceFile是test/scala/子目录中的.scala文件。
代码描述
在main方法中,我从local获得类和jars,并从sourceFile构建语法文档。然后,我通过SemanticDocument补丁程序接口使用ScalaFix执行编辑。最后,我想将编辑后的字符串写回sourceFile,直到退出循环(也许还有JVM),才会失败。参见代码上的注释。这似乎是一个与锁定有关的问题。可能是我以前寻找jars、类和semanticdb的函数没有释放sourceFile和local的锁。我在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发布于 2019-02-25 17:31:53
您试过在循环结束时关闭local和sourceFile吗?当文件仍然打开时,您确实无法确定数据是否被刷新到文件系统。
如果您将不变量移出循环(包括base、filename、root、abspath等),并将代码分组为单独的函数,这样您就可以更清楚地看到代码的结构,并专注于导致问题的部分,这也将使您更容易理解。
这是我在回答你上一个问题时提出的建议的重复。
https://stackoverflow.com/questions/54869755
复制相似问题