本文整理汇总了Scala中java.io.PrintStream类的典型用法代码示例。如果您正苦于以下问题:Scala PrintStream类的具体用法?Scala PrintStream怎么用?Scala PrintStream使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了PrintStream类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: OutputStreamLoggerAdapter
//设置package包名称以及导入依赖的类
package logoon.adapters.console
import java.io.{ OutputStream, PrintStream }
import logoon._
class OutputStreamLoggerAdapter(output: OutputStream) extends LoggerAdapter {
override def log(name: String, level: LogLevel, message: => String, context: Map[String, String]): Unit = {
output.write("[%-5s] %s\n".format(level, message).getBytes())
context.foreach { case (key, value) => output.write("%25s = %s\n".format(key, value).getBytes) }
}
override def log(name: String, level: LogLevel, message: => String, throwable: => Throwable, context: Map[String, String]): Unit = {
log(name, level, message, context)
throwable.printStackTrace(new PrintStream(output))
}
}
object ConsoleLoggerAdapter extends OutputStreamLoggerAdapter(System.out)
class InMemoryLogLevelConfig extends LogLevelConfig {
var levels: Map[String, LogLevel] = Map("" -> LogLevel.OFF)
override def logLevel(name: String): LogLevel =
levels.get(name) match {
case Some(level) => level
case None => logLevel(name.substring(0, name.length - 1))
}
override def setLogLevel(name: String, level: LogLevel): Unit = levels += (name -> level)
}
示例2: ByteCodeExecutor
//设置package包名称以及导入依赖的类
package org.arnoldc
import java.io.{PrintStream, ByteArrayOutputStream}
class ByteCodeExecutor extends ClassLoader {
val originalOutputStream = System.out
def getOutput(bytecode: Array[Byte], className: String): String = {
val outputRedirectionStream = new ByteArrayOutputStream()
System.setOut(new PrintStream(outputRedirectionStream))
invokeMainMethod(bytecode, className)
System.setOut(originalOutputStream)
outputRedirectionStream.toString
}
def invokeMainMethod(bytecode: Array[Byte], className: String) = {
val template = new ByteCodeExecutor()
val testClass = template.defineClass(className, bytecode, 0, bytecode.length)
val testInstance = testClass.newInstance().asInstanceOf[ {def main(test: Array[String])}]
testInstance.main(null)
}
}
示例3: ConsoleProgressBarTest
//设置package包名称以及导入依赖的类
package hu.ssh.progressbar.console
import java.io.{ByteArrayOutputStream, PrintStream}
import com.google.common.base.{Splitter, Strings}
import com.google.common.collect.Iterables
import org.scalatest.{FlatSpec, Matchers}
class ConsoleProgressBarTest extends FlatSpec with Matchers {
"ProgressBar" should "output as expected" in {
val outputstream = new ByteArrayOutputStream
try {
val progressBar = ConsoleProgressBar.on(new PrintStream(outputstream)).withFormat(":percent")
progressBar.tick(0)
assert(getLastOutput(outputstream.toString) == " 0.00")
progressBar.tick(25)
assert(getLastOutput(outputstream.toString) == " 25.00")
progressBar.tick(30)
assert(getLastOutput(outputstream.toString) == " 55.00")
progressBar.tick(44)
assert(getLastOutput(outputstream.toString) == " 99.00")
progressBar.tickOne()
assert(getLastOutput(outputstream.toString) == "100.00")
} finally outputstream.close()
}
private def getLastOutput(string: String): String = {
if (Strings.isNullOrEmpty(string)) return string
val outputs = Splitter.on(ConsoleProgressBar.CARRIAGE_RETURN).omitEmptyStrings.split(string)
Iterables.getLast(outputs)
}
}
示例4: capture
//设置package包名称以及导入依赖的类
package xyz.hyperreal
import java.io.{PrintStream, ByteArrayOutputStream}
package object gerbil {
def capture( code: String ) = {
val buf = new ByteArrayOutputStream
Console.withOut( new PrintStream(buf) )( Gerbil.run(code) )
buf.toString.trim
}
def captureReturn( code: String ) = {
val buf = new ByteArrayOutputStream
val ret = Console.withOut( new PrintStream(buf) )( Gerbil.run(code) )
(ret, buf.toString.trim)
}
}
示例5: Test
//设置package包名称以及导入依赖的类
package xyz.hyperreal.energize
import java.io.{PrintStream, ByteArrayOutputStream}
object Test {
def dbconnect = Energize.dbconnect( "H2", "org.h2.Driver", "jdbc:h2:mem:", "sa", "" )
def capture( code: String ) = {
val buf = new ByteArrayOutputStream
val (c, s, d) = dbconnect
val key = AUTHORIZATION.getString( "key" )
Console.withOut( new PrintStream(buf) )( Energize.configure(io.Source.fromString(code), c, s, d, key) )
c.close
buf.toString.trim
}
def captureReturn( code: String ) = {
val buf = new ByteArrayOutputStream
val (c, s, d) = dbconnect
val key = AUTHORIZATION.getString( "key" )
val ret = Console.withOut( new PrintStream(buf) )( Energize.configure(io.Source.fromString(code), c, s, d, key) )
c.close
(ret, buf.toString.trim)
}
}
示例6: ByteCodeExecutor
//设置package包名称以及导入依赖的类
package merkelonrails
import java.io.{ByteArrayOutputStream, PrintStream}
class ByteCodeExecutor extends ClassLoader {
val originalOutputStream = System.out
def getOutput(bytecode: Array[Byte], className: String): String = {
val outputRedirectionStream = new ByteArrayOutputStream()
System.setOut(new PrintStream(outputRedirectionStream))
invokeMainMethod(bytecode, className)
System.setOut(originalOutputStream)
outputRedirectionStream.toString
}
def invokeMainMethod(bytecode: Array[Byte], className: String) = {
val template = new ByteCodeExecutor()
val testClass = template.defineClass(className, bytecode, 0, bytecode.length)
val testInstance = testClass.newInstance().asInstanceOf[ {def main(test: Array[String])}]
testInstance.main(null)
}
}
示例7: ConfigTest
//设置package包名称以及导入依赖的类
package delorean.commands
import java.io.{ByteArrayOutputStream, PrintStream}
import java.nio.file._
import delorean._
import org.junit.Assert._
import org.junit._
import scala.util.Try
class ConfigTest {
val outContent = new ByteArrayOutputStream()
/**
* This will redirect the output stream into outContent and we can access the print output from it.
*/
@Before
def setUpStreams(): Unit = System.setOut(new PrintStream(outContent))
/**
* Resetting the stream to null.
*/
@After
def cleanUpStreams(): Unit = System.setOut(null)
@Test
def configTest(): Unit = {
// Adding a new key value pair to configuration
Config(List("Marty", "McFly"))
// Calling list to display the current configuration
Config(List("--list"))
assertEquals("Marty = McFly", outContent.toString.trim)
}
}
object ConfigTest {
// Create CONFIG file. We also create TIME_MACHINE as we need the parent directory to be present
@BeforeClass
def setUp(): Unit = {
Try(Files.createDirectory(Paths.get(TIME_MACHINE)))
Try(Files.createFile(Paths.get(CONFIG)))
}
// Delete CONFIG file and the parent directory.
@AfterClass
def tearDown(): Unit = {
Try(Files.delete(Paths.get(CONFIG)))
Try(Files.delete(Paths.get(TIME_MACHINE)))
}
}
示例8: ClientEventProcessor
//设置package包名称以及导入依赖的类
package org.argus.jc.incremental.jawa
package remote
import java.io.{PrintStream, PrintWriter}
class ClientEventProcessor(client: Client) {
def process(event: Event) {
event match {
case MessageEvent(kind, text, source, line, column) =>
client.message(kind, text, source, line, column)
case ProgressEvent(text, done) =>
client.progress(text, done)
case DebugEvent(text) =>
client.debug(text)
case TraceEvent(message, lines) =>
client.trace(new ServerException(message, lines))
case GeneratedEvent(source, module, name) =>
client.generated(source, module, name)
case DeletedEvent(module) =>
client.deleted(module)
case SourceProcessedEvent(source) =>
client.processed(source)
case CompilationEndEvent() =>
client.compilationEnd()
}
}
}
class ServerException(message: String, lines: Array[String]) extends Exception {
override def getMessage = message
override def printStackTrace(s: PrintWriter) {
lines.foreach(s.println)
}
override def printStackTrace(s: PrintStream) {
lines.foreach(s.println)
}
}
示例9: System
//设置package包名称以及导入依赖的类
package java.lang
import java.io.{InputStream, PrintStream}
import java.util.Properties
import scala.scalanative.native._
import scala.scalanative.runtime.time
final class System private ()
object System {
def arraycopy(src: Object,
srcPos: scala.Int,
dest: Object,
destPos: scala.Int,
length: scala.Int): Unit = {
scalanative.runtime.Array.copy(src, srcPos, dest, destPos, length)
}
def exit(status: Int): Unit = {
Runtime.getRuntime().exit(status)
}
def identityHashCode(x: Object): scala.Int =
x.cast[Word].hashCode
def getenv(name: String): String = ???
def clearProperty(key: String): String = ???
def getProperties(): Properties = ???
def getProperty(key: String): String = ???
def getProperty(key: String, default: String): String = ???
def setProperty(key: String, value: String): String = ???
def nanoTime(): CLong = time.scalanative_nano_time
var in: InputStream = _
var out: PrintStream = new PrintStream(new CFileOutputStream(stdio.stdout))
var err: PrintStream = new PrintStream(new CFileOutputStream(stdio.stderr))
private class CFileOutputStream(stream: Ptr[stdio.FILE])
extends java.io.OutputStream {
private val buf = stdlib.malloc(1)
def write(b: Int): Unit = {
!buf = b.toUByte.toByte
stdio.fwrite(buf, 1, 1, stream)
}
}
}
示例10: UrlPrinterTest
//设置package包名称以及导入依赖的类
package webcrawler
import java.io.PrintStream
import org.mockito.Mockito._
import org.scalatest.{FreeSpec, Matchers}
class UrlPrinterTest extends FreeSpec with Matchers {
"A UrlPrinter" - {
val out = mock(classOf[PrintStream])
val printer = new UrlPrinter(out)
"should print" - {
"the root" in {
printer.printRoot("hello")
verify(out).println("Visiting root: hello")
}
"the urls" in {
val urls = List("/one", "/two")
printer.printUrls(urls)
verify(out).println("|_ /one")
verify(out).println("|_ /two")
}
}
}
}
示例11: write
//设置package包名称以及导入依赖的类
package fr.cnrs.liris.accio.core.report
import java.io.{BufferedOutputStream, FileOutputStream, PrintStream}
import java.nio.file.Path
import fr.cnrs.liris.accio.core.thrift
import fr.cnrs.liris.util.io.FileUtils
def write(reports: Seq[thrift.Report], path: Path): Unit = {
val reportStats = new ReportStatistics(reports)
FileUtils.safeDelete(path)
val out = new PrintStream(new BufferedOutputStream(new FileOutputStream(path.toFile)))
try {
print(reportStats, out)
} finally {
out.close()
}
}
}
示例12: printSummary
//设置package包名称以及导入依赖的类
package fr.cnrs.liris.accio.core.report
import java.io.PrintStream
import fr.cnrs.liris.accio.lib.stats.{AggregatedStats, Distribution}
import fr.cnrs.liris.util.MathUtils.roundAt6
private def printSummary(out: PrintStream, metric: String, stats: AggregatedStats) = {
out.print(f"$metric%20s | ${stats.n}%10s")
if (stats.n > 0) {
out.print(f" | ${roundAt6(stats.min)}%10s")
if (stats.n > 1) {
out.print(f" | ${roundAt6(stats.max)}%10s | ${roundAt6(stats.avg)}%10s | ${roundAt6(stats.stddev)}%10s")
}
}
out.println()
}
private def bold(str: String) = if (useAnsi) s"\033[1m$str\033[0m" else str
}
示例13: prompt
//设置package包名称以及导入依赖的类
package org.kneelawk.simplecursemodpackdownloader.console
import java.io.Console
import java.io.PrintStream
import java.io.InputStream
import java.io.BufferedReader
import java.io.InputStreamReader
trait ConsoleInterface {
def prompt(fmt: String, args: Object*): String
def promptHiddenInput(fmt: String, args: Object*): String
}
class DefaultConsoleInterface(console: Console) extends ConsoleInterface {
override def prompt(fmt: String, args: Object*) = console.readLine(fmt, args)
override def promptHiddenInput(fmt: String, args: Object*) = new String(console.readPassword(fmt, args))
}
class EclipseConsoleInterface(out: PrintStream, in: InputStream) extends ConsoleInterface {
val reader = new BufferedReader(new InputStreamReader(in))
override def prompt(fmt: String, args: Object*) = {
out.printf(fmt, args)
reader.readLine()
}
override def promptHiddenInput(fmt: String, args: Object*) = {
out.printf(fmt, args)
reader.readLine()
}
}
object ConsoleInterfaceFactory {
def getConsoleInterface: ConsoleInterface = {
val console = System.console()
if (console != null) {
return new DefaultConsoleInterface(console)
} else if (System.in != null) {
return new EclipseConsoleInterface(System.out, System.in)
} else {
return null
}
}
}
示例14: RecentChangesBackend
//设置package包名称以及导入依赖的类
package org.vincibean.wikimedia.event.streams
import java.io.PrintStream
import java.net.ServerSocket
import akka.NotUsed
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.client.RequestBuilding.Get
import akka.http.scaladsl.model.sse.ServerSentEvent
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.http.scaladsl.unmarshalling.sse.EventStreamUnmarshalling._
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Source
import play.api.libs.json.{JsObject, Json}
object RecentChangesBackend {
def main(args: Array[String]): Unit = {
implicit val system = ActorSystem()
implicit val mat = ActorMaterializer()
import system.dispatcher
val outStream = new PrintStream(
new ServerSocket(8124).accept().getOutputStream)
val printStreamFun = printStream(outStream) _
Http()
.singleRequest(
Get("https://stream.wikimedia.org/v2/stream/recentchange"))
.flatMap(httpResp =>
Unmarshal(httpResp).to[Source[ServerSentEvent, NotUsed]])
.map(_.map(event => stringToJson(event.data)))
.foreach(_.runForeach(printStreamFun))
}
def stringToJson(message: String): JsObject = {
val json = Json.parse(message)
Json.obj(
"user" -> json \ "user",
"pageUrl" -> s"""${(json \ "server_url")
.as[String]}/wiki/${(json \ "title")
.as[String]
.replaceAll(" ", "_")}""",
"id" -> json \ "id",
"timestamp" -> (json \ "timestamp").as[Long]
)
}
def printStream(outStream: PrintStream)(json: JsObject): Unit = {
outStream.println(json.toString)
outStream.flush()
}
}
示例15: PrintStreamReporter
//设置package包名称以及导入依赖的类
package com.chrisomeara.pillar.core
import java.io.PrintStream
import java.util.Date
import com.datastax.driver.core.Session
class PrintStreamReporter(stream: PrintStream) extends Reporter {
override def initializing(session: Session, keyspace: String, replicationOptions: ReplicationOptions) {
stream.println(s"Initializing $keyspace")
}
override def migrating(session: Session, dateRestriction: Option[Date]) {
stream.println(s"Migrating with date restriction $dateRestriction")
}
override def applying(migration: Migration) {
stream.println(s"Applying ${migration.authoredAt.getTime}: ${migration.description}")
}
override def reversing(migration: Migration) {
stream.println(s"Reversing ${migration.authoredAt.getTime}: ${migration.description}")
}
override def destroying(session: Session, keyspace: String) {
stream.println(s"Destroying $keyspace")
}
}