[Scala文件操作]----读取和写入字符

本文介绍了一个使用Scala语言进行文件读写的具体实现案例。包括从指定路径读取文件内容,并将字符串内容写入到另一个文件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果有以下情景,怎么用scala实现读写文件?


1、实现读取以下文件内容

E:/device_level

2、将字符串写入文件

"E:/test.txt"
实现如下:

package com.ngaa.scala.test

import java.io.{ByteArrayInputStream, File, FileInputStream, InputStream}

import scala.io.BufferedSource

/**
  * Created by jfei_yang on 20170705.
  * Update date:
  * Time: 10:50
  * Project: sparkmvn
  * Package: com.ngaa.scala.test
  * Describle : 测试scala读写文件操作
  *
  * Result of Test: 测试通过
  * Command:
  *
  *
  * Email:  jifei.yang@ngaa.com.cn
  * Status:线上正在使用
  * Machine ip:
  * ^^集群----->192.168.1.1(001业务统计)
  * ^^集群----->127.0.0.1  (002业务统计)
  *
  * Attention:
  *
  *
  */
object TestNgaaUtils {

  def main(args: Array[String]) {
    val str="http://stat-y.xywy.com/vclick.png?Type=visit&Url=http%3A%2F%2Fm.so.xywy.com%2Fcomse.php%3Fsrc%3D3gclubso%26keyword%3D%25E5%259B%259B%25E5%258D%2581%25E5%2587%25A0%25E5%25B2%2581%25E7%2594%25B7%25E4%25BA%25BA%25E5%25BF%2583%2\n5E7%2590%2586&Domain=m.so.xywy.com&ClientId=1499086455712135328943326&ClientVisitNumber=7&ClientVisitNumberDay=7&SessionId=149908645571212102385&SessionNumber=7&LoginId=&UserType=&UrlKeyWord=%E5%9B%9B%E5%8D%81%E5%87%A0%E5%B2%81%E7%94%B7%E4%BA%BA%E5%BF%83%E7%90%86&TypeId\n=zhao&XPoint=15&YPoint=172&Height=80&Width=330&ItemId=m_detail_circles&Href=&TagName=DIV&Text=&Params=t%3Dmagicube%26n%3Dm_detail_circles%26p%3D1%26w%3D%E5%85%B6%E4%BB%96%E7%96%BE%E7%97%85%E5%9C%88&RandomNum=0.23594240844249725&RefKeyWord=&Redomain=3g.club.xywy.com&Ref=\nhttp%3A%2F%2F3g.club.xywy.com%2Fstatic%2F20140610%2F45407765.htm"

    //从文件中读取字符串
    val json=inputToString(new FileInputStream ("E:/device_level"))
    //将字符串写入文件
    inputToFile(str2InputStream(str),new File("E:/test.txt"))
    println(json)
    
  }

  //可以从InputStream中读取文件字符串
  def inputToString(is: java.io.InputStream): String = {
    val lines: Iterator[String] = scala.io.Source.fromInputStream(is, "utf-8").getLines()
    val sb = new StringBuilder()
    lines.foreach(sb.append(_))
    sb.toString()
  }

  //将输入流写入文件(test.txt)中
  //参数f---> val file = new File("F:/test.txt")
  def inputToFile(is: java.io.InputStream, f: java.io.File) {
    val in: BufferedSource = scala.io.Source.fromInputStream(is)
    val out = new java.io.PrintWriter(f)
    try {
      in.getLines().foreach(out.print(_))//等价write,只是多了一句if(s==null)s="null"
    }
    finally {
      out.close
    }
  }

  /**
    * string to inputStream
    * @param str
    * @return
    */
  def str2InputStream(str:String):InputStream={
    new  ByteArrayInputStream(str.getBytes())
  }

}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

oo寻梦in记

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值