• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala FileWriter类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中java.io.FileWriter的典型用法代码示例。如果您正苦于以下问题:Scala FileWriter类的具体用法?Scala FileWriter怎么用?Scala FileWriter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了FileWriter类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: copyDataStructures

//设置package包名称以及导入依赖的类
package ppl.delite.framework.codegen

import java.io.{BufferedWriter, FileWriter, File}


trait Utils {
  def copyDataStructures(from: String, to: String, dsmap: String => String = s => s) {
    val dsDir = new File(from)
    if (!dsDir.exists) return
    val outDir = new File(to)
    outDir.mkdirs()
    copyDirectory(dsDir)

    def copyDirectory(dir: File) {
      for (f <- dir.listFiles) {
        if (f.isDirectory) 
          copyDirectory(f)
        else {
          val outFile = to + File.separator + f.getName
          val out = new BufferedWriter(new FileWriter(outFile))
          for (line <- io.Source.fromFile(f).getLines) {
            var remappedLine = dsmap(line)
            remappedLine = remappedLine.replaceAll("ppl.delite.framework.datastruct", "generated")
            out.write(remappedLine + System.getProperty("line.separator"))
          }
          out.close()
        }
      }
    }
  }
} 
开发者ID:leratojeffrey,项目名称:OptiSDR-Compiler,代码行数:32,代码来源:Utils.scala


示例2: FileReaderTest4SourceAndClosing2

//设置package包名称以及导入依赖的类
import java.io.{BufferedWriter, FileWriter}

import org.scalatest._

import scala.io.Source

class FileReaderTest4SourceAndClosing2 extends FlatSpec with Matchers {
  "Hello" should "have tests" in {

    implicit def toClosingSource(source: Source) = new {
      val lines = source.getLines

      def getLinesAndClose() = new Iterator[String] {
        def hasNext = if (!lines.hasNext) {source.close; false} else true
        def next = lines.next
      }
    }

    val w = new BufferedWriter(new FileWriter("/tmp/csv13.txt"))

    (9 to 12).map(i => s"""/tmp/csv${i}.txt""").foreach(fn => {
        Source.fromFile(fn).getLinesAndClose().foreach(ln => {
          w.write(ln)
          w.write("\r\n")
        })
      }
    )


  }
} 
开发者ID:ralreiroe,项目名称:embarcadero,代码行数:32,代码来源:FileReaderTest4SourceAndClosing2.scala


示例3: ChannelHelper

//设置package包名称以及导入依赖的类
package us.illyohs.sinked.helper

import java.io.{File, FileWriter, IOException, Writer}
import java.util

import com.google.gson.{FieldNamingPolicy, Gson, GsonBuilder}
import org.spongepowered.api.Sponge
import us.illyohs.sinked.Sinked
import us.illyohs.sinked.channel.Channel

object ChannelHelper {

  val chanList:util.List[Channel] = new  util.ArrayList[Channel]()

  val sinked:Sinked = null
  val channelPath = "./channels/"

  val channelDir = new File(channelPath)

  def initChannel: Unit = {
    chanList.add(new GlobalChannel)
    chanList.add(new LocalChannel)
    if (!channelDir.exists()) {
      //      sinked.getLogger.warn("Channel directory not found!")
      //      sinked.getLogger.info("Now creating channel directory")

      channelDir.mkdir()
      val gson: Gson = new GsonBuilder()
        .setPrettyPrinting()
        .serializeNulls()
        .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
        .create()
      for (i <- 0 to 1) {
        val ch = chanList.get(i)
        val json = gson.toJson(ch)
        val w: Writer = new FileWriter(channelPath + ch.getName + ".json")
        try {
          w.write(json)
          w.close()
          //          sinked.getLogger.info("Created default channel: " +ch.getName)
        } catch {
          case e: IOException => e.printStackTrace()
        }
      }
      //      createDefualtjons
    }
  }


  case class GlobalChannel() extends Channel("Global", "", "G", "", "", false, true, false, false, true)
  case class LocalChannel() extends Channel("Local", "", "L", "", "", false, true, false, false, false)
} 
开发者ID:DragonTechMC,项目名称:Sinked,代码行数:53,代码来源:ChannelHelper.scala


示例4: HTMLFile

//设置package包名称以及导入依赖的类
package ch.epfl.sbtplugin

import java.io.{BufferedWriter, File, FileWriter}

object HTMLFile {

  val content =
    """
      |<!DOCTYPE html>
      |<html>
      |<meta charset="UTF-8">
      |<title>Scala.js Call Graph Visualization</title>
      |<link rel="stylesheet" type="text/css" href="https://rawgit.com/lionelfleury/scala-js-call-graph/release/style.css">
      |<body>
      |<div id="header"><h1>Scala.js Call Graph Visualization</h1></div>
      |<div id="nav" style="overflow:auto"></div>
      |<div id="main" style="overflow:auto"></div>
      |<script type="text/javascript" src="https://rawgit.com/lionelfleury/scala-js-call-graph/release/scalajs-callgraph-opt.js"></script>
      |<script type="text/javascript" src="https://rawgit.com/lionelfleury/scala-js-call-graph/release/scalajs-callgraph-jsdeps.min.js"></script>
      |<script type="text/javascript" src="https://rawgit.com/lionelfleury/scala-js-call-graph/release/scalajs-callgraph-launcher.js"></script>
      |</body>
      |</html>
    """.stripMargin

  def writeToFile(file: File): Unit = {
    val bw = new BufferedWriter(new FileWriter(file))
    bw.write(content)
    bw.flush()
    bw.close()
  }

} 
开发者ID:lionelfleury,项目名称:scala-js-call-graph,代码行数:33,代码来源:HTMLFile.scala


示例5: EulerUtils

//设置package包名称以及导入依赖的类
package org.nason.euler

import java.io.{File, FileWriter}

object EulerUtils
{
  val DataRoot = "/home/sorensjm/workspace/euler/data"
  val DataRoot2 = "/Users/jon/Documents/IdeaProjects/euler-jms-scala/data"

  def writeFile(file: File, content: String) =
    if (file.exists() && !file.canWrite())
      System.err.println("File " + file + " is not writable")
    else {
      val writer = new FileWriter(file, false)
      writer.write(content)
      writer.close()
    }

  def readDataFile( fileName:String ) : Iterator[String] = {
    val file = new File(DataRoot2,fileName)
    if (!file.exists()) {
      System.err.println("Can not find file %s/%s".format(DataRoot2,fileName))
      Array[String]().iterator
    } else {
      io.Source.fromFile(file).getLines()
    }
  }

  
  def timing[F]( f: =>F ) =
  {
    val then = System.nanoTime
    val ans = f
    val now = System.nanoTime
    println( "Took %g sec".format( (now-then).toDouble*1e-9 ) )
    ans
  }
} 
开发者ID:drkeoni,项目名称:euler-jms-scala,代码行数:39,代码来源:EulerUtils.scala


示例6: KoaAChheh

//设置package包名称以及导入依赖的类
package fr.magistry.utils.taigi

import java.io.FileWriter

import scala.io.Source


class KoaAChheh(path:String) {
  def load() = {
    def readCouplet(text: Iterator[String], hanji: List[String], poj:List[String], hanjiDone: Boolean=false): List[(String, String)] = {
      if(hanjiDone && poj.length == hanji.length) {
        hanji.zip(poj)
      }
      else {
        val nextLine = text.next()
        if (nextLine.trim == "")
          if(hanji.isEmpty) readCouplet(text, hanji, poj, false)
          else readCouplet(text, hanji, poj, true)
        else {
          if (hanjiDone)
            readCouplet(text, hanji, nextLine::poj, hanjiDone)
          else
            readCouplet(text, nextLine::hanji, poj, hanjiDone)
        }
      }
    }
    def readAll(text:Iterator[String], buf: List[(String, String)]=Nil): List[(String,String)] = {
      if (text.hasNext)
        readAll(text, readCouplet(text, Nil,Nil) ::: buf)
      else
        buf.reverse
    }
    val src = Source.fromFile(path)
    val lines = src.getLines()
    val d = readAll(lines)
    src.close()
    d
  }
  val alignedText = load()



  def alignOne(hanji:String, poj: String): String = {
    //assume last char is punctuation
    val hjW = hanji.substring(0, hanji.length - 1).split(" ")
    val pojW = poj.substring(0, poj.length - 1).split(" ")
    (for ((w1, w2) <- hjW.zip(pojW))
      yield s"$w2\t$w1").mkString("\n") +
      s"\n${hanji.substring(hanji.length -1)}\n"
  }

  def writeCorpus(path: String) = {
    val f = new FileWriter(path)
    for ((hanji, poj) <- alignedText) {
      f.write(alignOne(hanji, poj))
    }
    f.close()
  }
} 
开发者ID:a-tsioh,项目名称:TaigiUtils-scala,代码行数:60,代码来源:KoaAChheh.scala


示例7: Recorder

//设置package包名称以及导入依赖的类
package org.argus.amandroid.concurrent.util

import java.io.FileWriter

import org.argus.jawa.core.util.{FileResourceUri, FileUtil}


case class Recorder(outUri: FileResourceUri) {
  def decompile(apkName: String, succ: Boolean): Unit = {
    val rp = FileUtil.toFile(FileUtil.appendFileName(outUri, "decompile_report.txt"))
    this.synchronized {
      val writer = new FileWriter(rp, true)
      try {
        writer.write(apkName + " " + {if(succ) "success" else "failure"} + "\n")
      } catch {
        case e: Exception =>
          throw e
      } finally {
        writer.close()
      }
    }
  }

  def infocollect(apkName: String, succ: Boolean): Unit = {
    val rp = FileUtil.toFile(FileUtil.appendFileName(outUri, "info_collect_report.txt"))
    this.synchronized {
      val writer = new FileWriter(rp, true)
      try {
        writer.write(apkName + " " + {if(succ) "success" else "failure"} + "\n")
      } catch {
        case e: Exception =>
          throw e
      } finally {
        writer.close()
      }
    }
  }

  def pta(apkName: String, time: Long, componentNum: Int, succ: Boolean): Unit = {
    val rp = FileUtil.toFile(FileUtil.appendFileName(outUri, "pta_report.txt"))
    this.synchronized {
      val writer = new FileWriter(rp, true)
      try {
        writer.write(apkName + " " + time + " " + componentNum + " " + {if(succ) "success" else "failure"} + "\n")
      } catch {
        case e: Exception =>
          throw e
      } finally {
        writer.close()
      }
    }
  }
} 
开发者ID:arguslab,项目名称:Argus-SAF,代码行数:54,代码来源:Recorder.scala


示例8: CliLogger

//设置package包名称以及导入依赖的类
package org.argus.saf.cli.util

import java.io.{File, FileWriter, PrintWriter}
import java.text.SimpleDateFormat
import java.util.Date

 
object CliLogger {
  
  def timeStamp: String = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date)
  
  def outPrint(s : String) {
    scala.Console.out.print(s)
    scala.Console.out.flush()
  }

  def outPrintln(s : String) {
    scala.Console.out.println(s)
    scala.Console.out.flush()
  }

  def outPrintln() {
    scala.Console.out.println()
    scala.Console.out.flush()
  }

  def errPrintln(s : String) {
    scala.Console.err.println(s)
    scala.Console.err.flush()
  }

  def errPrintln() {
    scala.Console.err.println()
    scala.Console.err.flush()
  }
  
  def logError(dir: File, text: String, e: Throwable) {
    outPrintln()
    errPrintln(text + e.getMessage)
    val f = new File(dir, ".errorlog")
    f.getParentFile.mkdirs
    val fw = new FileWriter(f)
    try {
      val pw = new PrintWriter(fw)
      pw.println("An error occurred on " + timeStamp)
      e.printStackTrace(pw)
      fw.close()
      outPrintln("Written: " + f.getAbsolutePath)
    } catch {
      case e : Throwable =>
        errPrintln("Error: " + e.getMessage)
    }
  }
} 
开发者ID:arguslab,项目名称:Argus-SAF,代码行数:55,代码来源:CliLogger.scala


示例9: SerializationTest

//设置package包名称以及导入依赖的类
package org.argus.amandroid.serialization

import java.io.{FileReader, FileWriter}

import org.argus.amandroid.alir.componentSummary.ApkYard
import org.argus.amandroid.core.decompile.{ConverterUtil, DecompileLayout, DecompileStrategy, DecompilerSettings}
import org.argus.amandroid.core.model.ApkModel
import org.argus.jawa.core.DefaultReporter
import org.json4s.NoTypeHints
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}
import org.scalatest.{FlatSpec, Matchers}
import org.argus.jawa.core.util.FileUtil


class SerializationTest extends FlatSpec with Matchers {

  "ApkModel" should "successfully serialized and deserialized" in {
    val apkFile = getClass.getResource("/icc-bench/IccHandling/icc_explicit_src_sink.apk").getPath
    val apkUri = FileUtil.toUri(apkFile)
    val outputUri = FileUtil.toUri(apkFile.substring(0, apkFile.length - 4))
    val reporter = new DefaultReporter
    val yard = new ApkYard(reporter)
    val layout = DecompileLayout(outputUri)
    val strategy = DecompileStrategy(layout)
    val settings = DecompilerSettings(debugMode = false, forceDelete = true, strategy, reporter)
    val apk = yard.loadApk(apkUri, settings, collectInfo = true)
    val model = apk.model
    implicit val formats = Serialization.formats(NoTypeHints) + ApkModelSerializer
    val apkRes = FileUtil.toFile(FileUtil.appendFileName(outputUri, "apk.json"))
    val oapk = new FileWriter(apkRes)
    try {
      write(model, oapk)
    } catch {
      case e: Exception =>
        e.printStackTrace()
    } finally {
      oapk.flush()
      oapk.close()
    }
    val iapk = new FileReader(apkRes)
    var newApkModel: ApkModel = null
    try {
      newApkModel = read[ApkModel](iapk)
    } catch {
      case e: Exception =>
        e.printStackTrace()
    } finally {
      iapk.close()
      ConverterUtil.cleanDir(outputUri)
    }
    require(
      model.getAppName == newApkModel.getAppName &&
      model.getComponents == newApkModel.getComponents &&
      model.getLayoutControls == newApkModel.getLayoutControls &&
      model.getCallbackMethods == newApkModel.getCallbackMethods &&
      model.getComponentInfos == newApkModel.getComponentInfos &&
      model.getEnvMap == newApkModel.getEnvMap)
  }
} 
开发者ID:arguslab,项目名称:Argus-SAF,代码行数:61,代码来源:SerializationTest.scala


示例10: Demo7Spec

//设置package包名称以及导入依赖的类
package org.scalatest.examples

// Type-constructor polymorphism

import java.io.{File, FileWriter}

import org.scalactic.TypeCheckedTripleEquals
import org.scalatest.examples.Demo._
import org.scalatest.prop.PropertyChecks
import org.scalatest.{FunSpec, Matchers}

// (Demo 6 was REPL demo of Assertion and Succeeded)

// DEMO 7 File output
class Demo7Spec extends FunSpec with Matchers with PropertyChecks with TypeCheckedTripleEquals {

  describe("The squareRoot1 function") {
    it("should compute the square root") {
      val two = squareRoot1(4.0)
      val outputFile = new FileWriter("squareRoot.out")
      try outputFile.write(two.toString + "\n")
      finally outputFile.close()
    }
    it("should should throw IAE on negative input") {
      an [IllegalArgumentException] should be thrownBy {
        squareRoot1(-1.0)
      }
    }
    it("should should throw IAE on positive infinity input") {
      an [IllegalArgumentException] should be thrownBy {
        squareRoot1(Double.PositiveInfinity)
      }
    }
  }
} 
开发者ID:bvenners,项目名称:scalaX2016Demos,代码行数:36,代码来源:Demo7Spec.scala


示例11: userToString

//设置package包名称以及导入依赖的类
package de.hsrm.cs.kochplattformweb.printer

import de.hsrm.cs.kochplattformweb.client.AbstractUser
import de.hsrm.cs.kochplattformweb.utils.SWTLogger
import java.io.FileWriter
import java.io.IOException
import java.util
import javax.xml.transform.Transformer


	def userToString(user:AbstractUser):String= {
		if(user.isAdmin) return "Admin"
		"MainUser"
	}
	@Override
	def setParameters(transformer: Transformer, out:FileWriter) {
		val res:StringBuffer = new StringBuffer(1024)
		res.append("<list>")
		val iter:java.util.Iterator[AbstractUser]=this.userlist.iterator()
		while (iter.hasNext) {
			var i:AbstractUser=iter.next()
			res.append("<item><name>")
			res.append(i.name)
			res.append("</name><position>")
			res.append(this.userToString(i))
			res.append("</position><password>")
			res.append(i.password)
			res.append("</password><id>")
			res.append(Printer.formatBigInteger(i.id))
			res.append("</id></item>")
		}
		res.append("</list>")
		try {
			out.append(res)
			out.append("</userlist>")
			out.close()
		} catch {
			case e:IOException =>SWTLogger.writeerror(e.getMessage)
		}
	}
} 
开发者ID:situx,项目名称:KochplattformWeb,代码行数:42,代码来源:PrintUserList.scala


示例12: PrintAdmin

//设置package包名称以及导入依赖的类
package de.hsrm.cs.kochplattformweb.printer

import java.io.FileWriter
import java.io.IOException
import javax.xml.transform.Transformer

import de.hsrm.cs.kochplattformweb.client.Admin
import de.hsrm.cs.kochplattformweb.utils.SWTLogger


class PrintAdmin(admin:Admin) extends Parameterable {

	@Override
	override def setParameters(transformer: Transformer,out:FileWriter) {
		transformer.setParameter("name", this.admin.name)
		transformer.setParameter("password", this.admin.password)
		transformer.setParameter("id", Printer.formatBigInteger(this.admin.id))
		try {
			out.append("</admin>")
			out.close()
		} catch{
			case e:IOException => SWTLogger.writeerror(e.getMessage)
		} 
	}
} 
开发者ID:situx,项目名称:KochplattformWeb,代码行数:26,代码来源:PrintAdmin.scala


示例13: PrintMessage

//设置package包名称以及导入依赖的类
package de.hsrm.cs.kochplattformweb.printer

import java.io.FileWriter
import java.io.IOException
import javax.xml.transform.Transformer

import de.hsrm.cs.kochplattformweb.utils.SWTLogger


class PrintMessage(message:String) extends Parameterable {

	@Override
	def setParameters(transformer:Transformer, out:FileWriter) {
		transformer.setParameter("text", this.message)
		try {
			out.append("</message>")
			out.close();
		} catch {
			case e:IOException =>SWTLogger.writeerror(e.getMessage)
		}
	}
} 
开发者ID:situx,项目名称:KochplattformWeb,代码行数:23,代码来源:PrintMessage.scala


示例14: setParameters

//设置package包名称以及导入依赖的类
package de.hsrm.cs.kochplattformweb.printer

import java.io.FileWriter
import java.io.IOException
import javax.xml.transform.Transformer

import de.hsrm.cs.kochplattformweb.db.{Ingredient, RecipeEntry}
import de.hsrm.cs.kochplattformweb.utils.SWTLogger


	var count:Int=0

	@Override
	override def setParameters(transformer:Transformer, out:FileWriter) {
		val res: StringBuffer = new StringBuffer(1024)
		res.append("<list>")
		for (i:RecipeEntry<-this.rlist) {
			res.append("<item><name>")
			res.append(i.name)
			res.append("</name><category>")
			res.append(i.category)
			res.append("</category><time>")
			res.append(i.time)
			res.append("</time><rating>")
			res.append(Printer.formatDouble(i.rating))
			res.append("</rating><ingredient>")
			this.count = 0
			for (intgre:Ingredient <- i.ingredients) {
				if(this.count == i.ingredients
						.size-1) {
					res.append(intgre
							.name)
				}
				else {
					res.append(intgre
							.name)
					res.append(", ")
				}
				this.count+=1
			}
			res.append("</ingredient></item>")
		}
		try {
			out.append(res)
			out.append("</list></recipeentry>")
			out.close()
		} catch { case e:IOException =>	SWTLogger.writeerror(e.getMessage)
		}
	}

} 
开发者ID:situx,项目名称:KochplattformWeb,代码行数:52,代码来源:PrintRecipeEntryList.scala


示例15: PrintUser

//设置package包名称以及导入依赖的类
package de.hsrm.cs.kochplattformweb.printer

import java.io.FileWriter
import java.io.IOException
import javax.xml.transform.Transformer

import de.hsrm.cs.kochplattformweb.client.MainUser
import de.hsrm.cs.kochplattformweb.utils.SWTLogger


class PrintUser(user:MainUser) extends Parameterable {

	@Override
	override def setParameters(transformer:Transformer, out:FileWriter) {
		transformer.setParameter("name", this.user.name)
		transformer.setParameter("password", this.user.password)
		transformer.setParameter("id", Printer.formatBigInteger(this.user.id))
		try {
			out.append("</user>")
			out.close()
		} catch{
			case e:IOException => SWTLogger.writeerror(e.getMessage)
		}
	}
} 
开发者ID:situx,项目名称:KochplattformWeb,代码行数:26,代码来源:PrintUser.scala


示例16: CSVWriteBufOwnTest

//设置package包名称以及导入依赖的类
import java.io.{PrintWriter, BufferedWriter, FileWriter}

import com.github.tototoshi.csv.{CSVWriter, DefaultCSVFormat}
import org.scalatest._

class CSVWriteBufOwnTest extends FlatSpec with Matchers {
  "Hello" should "have tests" in {

    val bw = new PrintWriter(new BufferedWriter(new FileWriter("/tmp/csv2.txt"), 8192*256*4))

    lazy val doit = {
      println("working")
      (1 to 1000000).foreach(i => {
        bw.print(List(1, 2, 3, 4, 5, 6).mkString(","))
        bw.print("\r\n")
      })
      println("finished")
    }

    def timeSpentDoing(f: => Unit) = {

      val start = System.currentTimeMillis
      println(start)
      f
      println(System.currentTimeMillis - start)
    }

    timeSpentDoing(doit)

  }
} 
开发者ID:ralreiroe,项目名称:embarcadero,代码行数:32,代码来源:CSVWriteBufOwnTest.scala


示例17: CSVWriteBufOwnParallelTest

//设置package包名称以及导入依赖的类
import java.io.{BufferedWriter, FileWriter, PrintWriter}
import java.util.concurrent.Executors

import org.scalatest._

import scala.concurrent.{ExecutionContext, Await, Future}
import scala.concurrent.duration.Duration
import scala.util.{Success, Failure}

class CSVWriteBufOwnParallelTest extends FlatSpec with Matchers {
  "Hello" should "have tests" in {


    lazy val doit: Int => Unit = i => {
      val bw = new PrintWriter(new BufferedWriter(new FileWriter(s"""/tmp/csv${i}.txt"""), 8192 * 256 * 4))
      (1 to 10000000).foreach(i => {
        bw.print(List(1, 2, 3, 4, 5, 6).mkString(","))
        bw.print("\r\n")
      })
      bw.close()
    }

    def timeSpentDoing(f: => Unit) = {
      val start = System.currentTimeMillis
      println(start)
      f
      System.currentTimeMillis - start
    }


    implicit val ec = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(5))

    val futures = (9 to 12).map(n => Future{ timeSpentDoing( doit(n) ) })
    val combined = Future.sequence(futures)
    Await.ready(combined, Duration.Inf)
    combined onComplete {
      case Success(duration) => println(duration)
      case Failure(ex) => println(ex)
    }




  }
} 
开发者ID:ralreiroe,项目名称:embarcadero,代码行数:46,代码来源:CSVWriteBufOwnParallelTest.scala


示例18: FileReaderTest2Iterable

//设置package包名称以及导入依赖的类
import java.io.{FileWriter, BufferedReader, File, FileReader}

import org.scalatest._

class FileReaderTest2Iterable extends FlatSpec with Matchers {
  "Hello" should "have tests" in {


    def getContents(fileName: String): Iterable[String] = {
      val fr = new BufferedReader(new FileReader(fileName))
      new Iterable[String] {
        def iterator = new Iterator[String] {
          def hasNext = line != null

          def next = {
            val retVal = line
            line = getLine
            retVal
          }

          def getLine = {
            var line: String = null
            try {
              line = fr.readLine
            } catch {
              case _: Throwable => line = null; fr.close()
            }
            line
          }

          var line = getLine
        }
      }
    }


    val w = new FileWriter("/tmp/csv3.txt")

    Seq("/tmp/csv.txt", "/tmp/csv2.txt").foreach(fn => {
      getContents(fn).foreach(ln => {
        w.write(ln)
        w.write("\r\n")
      })
    }
    )


  }
} 
开发者ID:ralreiroe,项目名称:embarcadero,代码行数:50,代码来源:FileReaderTest2Iterable.scala


示例19: FileReaderTest4SourceAndClosing

//设置package包名称以及导入依赖的类
import java.io.{BufferedReader, FileReader, FileWriter}

import org.scalatest._

import scala.io.Source

class FileReaderTest4SourceAndClosing extends FlatSpec with Matchers {
  "Hello" should "have tests" in {



    implicit def toClosingSource(source: Source) = new {
      val lines = source.getLines
      var stillOpen = true
      def getLinesAndClose() = new Iterator[String] {
        def hasNext = stillOpen && lines.hasNext
        def next = {
          val line = lines.next
          if (!lines.hasNext) { source.close(); stillOpen = false }
          line
        }
      }
    }

    val w = new FileWriter("/tmp/csv6.txt")

    Seq("/tmp/csv.txt", "/tmp/csv2.txt").foreach(fn => {
      Source.fromFile(fn).getLinesAndClose.foreach(ln => {
        w.write(ln)
        w.write("\r\n")
      })
    }
    )


  }
} 
开发者ID:ralreiroe,项目名称:embarcadero,代码行数:38,代码来源:FileReaderTest4SourceAndClosing.scala


示例20: FileReaderTest3Iterator

//设置package包名称以及导入依赖的类
import java.io.{BufferedWriter, BufferedReader, FileReader, FileWriter}

import org.scalatest._

class FileReaderTest3Iterator extends FlatSpec with Matchers {
  "Hello" should "have tests" in {


    def getContents(fileName: String): Iterator[String] = {
      val fr = new BufferedReader(new FileReader(fileName))
      def iterator = new Iterator[String] {
        def hasNext = line != null

        def next = {
          val retVal = line
          line = getLine
          retVal
        }

        def getLine = {
          var line: String = null
          try {
            line = fr.readLine
          } catch {
            case _: Throwable => line = null; fr.close()
          }
          line
        }

        var line = getLine
      }
      iterator
    }

    val w = new BufferedWriter(new FileWriter("/tmp/csv4.txt"))

    Seq("/tmp/csv.txt", "/tmp/csv2.txt").foreach(fn => {
      getContents(fn).foreach(ln => {
        w.write(ln)
        w.write("\r\n")
      })
    }
    )


  }
} 
开发者ID:ralreiroe,项目名称:embarcadero,代码行数:48,代码来源:FileReaderTest3Iterator.scala



注:本文中的java.io.FileWriter类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala Inject类代码示例发布时间:2022-05-23
下一篇:
Scala Charset类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap