已复制
全屏展示
复制代码

Scala文件读写等常见操作


· 1 min read

文件移动位置

import java.nio.file.{Files, Paths, StandardCopyOption}

val path = Files.move(
  Paths.get(sourceFilename),
  Paths.get(destinationFilename),
  StandardCopyOption.REPLACE_EXISTING
)

if (path != null) {
  println(s"moved the file $sourceFilename successfully")
} else {
  println(s"######could NOT move the file $sourceFilename######")
}

读取文件为字符串

import scala.io.{BufferedSource, Source}

val source: BufferedSource = Source.fromFile("/etc/profile")
val string: String = source.mkString
print(string)

写入字符串到文件

import java.io.{File, PrintWriter}

import scala.io.Source

object FileIO {
  def main(args: Array[String]): Unit = {
    //从文件中读取数据
    Source.fromFile("src/main/resources/test.txt").foreach(print)

    //将数据写入文件
    val writer = new PrintWriter(new File("src/main/resources/output.txt"))
    writer.write("hello scala from java writer")
    writer.close()
  }
}

从指定位置开始读取

索引从 0 开始,英文一个字符占用一个索引,中文一个汉字占用 3 个字符。

package org.example

import java.io.RandomAccessFile

object MainExample {

  def readFileFromPosition(filePath: String, position: Long): Unit = {
    val file = new RandomAccessFile(filePath, "r")
    val channel = file.getChannel()
    channel.position(position)
    val buffer = java.nio.ByteBuffer.allocate(1024)
    var bytesRead = channel.read(buffer)

    while (bytesRead != -1) {
      buffer.flip()
      while (buffer.hasRemaining()) {
        print(buffer.get().toChar)
      }
      buffer.clear()
      bytesRead = channel.read(buffer)
    }
    channel.close()
    file.close()
  }

  def main(args: Array[String]): Unit = {
    val filePath = "/tmp/profile"
    val position = 10 // 指定位置
    readFileFromPosition(filePath, position)
  }

}
🔗

文章推荐