import java.io._
/*
*
*
*
* */
// 4. BufferedReader & BufferedWriter
object BufferCharStreamTest extends App {
// 读取数据
// 1. 创建File + FileReader + BufferedReader
val inPath = "sparkcore/src/main/data/word.txt"
private val bufferedReader = new BufferedReader(new FileReader(new File(inPath)))
// 2. 创建File + FileWriter + BufferedWriter
val outPath = "sparkcore/src/main/data/bufferedOut.txt"
private val bufferedWriter = new BufferedWriter(new FileWriter(new File(outPath)))
// 3. 读取数据
private var str: String = bufferedReader.readLine
while (str != null) {
println(str)
str = bufferedReader.readLine
}
// 4. 关闭流
bufferedReader.close
println("读取完毕")
//写入数据
private val strings: Array[String] = Array[String]("悟空\n", "八戒\n", "沙僧\n", "三藏\n")
strings.foreach(bufferedWriter.write)
//关闭流
bufferedWriter.close
println("写入完毕")
}
// 5. BufferedInputStream & BufferOutputStream
object BufferByteStreamTest extends App {
//1. 创建File + FileInputStream + BufferedInputStream 对象
val inPath = "sparkcore/src/main/data/yarn架构图.png"
private val bufferedInputStream = new BufferedInputStream(new FileInputStream(inPath))
//2. 创建File + FileOutputStream + BufferedOutputStream 对象
val outPath = "sparkcore/src/main/data/yarn架构图2.png"
private val bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(outPath))
//读取数据
private var bytes: Array[Byte] = new Array[Byte](10)
private var i: Int = bufferedInputStream.read(bytes)
while (i != -1) {
println(bytes.mkString(" "))
i = bufferedInputStream.read(bytes, 0, i)
}
// 0 0 0 73 69 78 68 -82 66 96 倒数第二行
// -126 0 0 73 69 78 68 -82 66 96 倒数第一行
// 关闭流
bufferedInputStream.close
println("读取完成")
// 写入数据
bufferedOutputStream.write(100)
// 关闭流
bufferedOutputStream.close
}
// 6. BufferedInputStream & BufferOutputStream - 复制非文本文件 及测速 10毫秒
object CopyFileByBufferTest extends App {
// 定义方法
// 复制inPath指定的文件 到outPath指定的文件
def copyFile(inPath: String, outPath: String) = {
//1. 创建File对象 + FileInputSteam对象
val inStream = new BufferedInputStream(new FileInputStream(inPath)) //new FileInputStream(new File(inPath))
//2. 创建File对象 + FileOutputSteam对象
val outStream = new BufferedOutputStream(new FileOutputStream(outPath)) //new FileOutputStream(new File(outPath))
//3. 读取
var bytes = new Array[Byte](10)
var i: Int = inStream.read(bytes)
while (i != -1) {
outStream.write(bytes, 0, i)
i = inStream.read(bytes)
}
//4. 关闭流
inStream.close
outStream.close
}
//调用方法
val inPath = "sparkcore/src/main/data/yarn架构图.png"
val outPath = "sparkcore/src/main/data/yarn架构图1.png"
//计时
val start: Long = System.currentTimeMillis
copyFile(inPath, outPath)
val end: Long = System.currentTimeMillis
println(s"耗时 : ${end - start}毫秒")
}