Scala IO ,基本文件读写


package service.spider.fileLocSys

import scala.io.Source
import java.io.{BufferedWriter, OutputStreamWriter, FileOutputStream, File}

/**
 * Scala Io 基本文件读写
 *  author: w.j.w
 *  time: 15-12-11
 *  email: wujavei@163.com
 *
 *出其西门,有女如云,虽则如云,匪我思存。
 *
 */
object FileLocService {

  val docSaveDir:String="E:/WjWork/MIS/AliBabaAdSpider/spiderFile"

  def readFile(file: String): String = {
    //val doc = Source.fromFile(file)("UTF-8").mkString
    val doc = Source.fromFile(file).mkString
    println(doc)

    doc
  }

  //write

  def writeLocFile(code:String,encode:String):String={

    //定义文件路径
    val tpu=TimeUrlPathUtil
    val timeFileName=System.currentTimeMillis()+""+ (Math.random()*1000).asInstanceOf[Int];

    var filepath=this.docSaveDir+"/"+tpu.getTimePath()+"/"+timeFileName+".html"

      val f=new File(filepath)

      val fileParent=f.getParentFile

        if(fileParent.exists()==false){
          fileParent.mkdirs()
        }
     val fout=new FileOutputStream(f)
      //指定输出文件编码
     val ow=new OutputStreamWriter(fout,encode)

      val bw=new BufferedWriter(ow)


      bw.write(code)

      bw.flush()

    //关闭文件输出流
      bw.close()

      ow.close()
      fout.close()


   // println(filepath)

    filepath
  }

  def main(args: Array[String]) {
    val fcs = FileLocService
    fcs.readFile("E:\\WjWork\\MIS\\AliBabaAdSpider\\1688spider_html_code.txt")

   val path= fcs.writeLocFile("中文文档测试","utf-8")
    println(path)

    println("写入文件内容:"+fcs.readFile(path))


  }


}

按时间定义文件相对路径

package service.spider.fileLocSys
import java.util.Date
import java.text.SimpleDateFormat
/**
 * Created by Administrator on 15-12-11.
 */
object TimeUrlPathUtil {

    def getTimePath(): String ={

      val tp=getNowDate()

      tp
    }

  def getNowDate():String={
    var now:Date = new Date()
    var  dateFormat:SimpleDateFormat = new SimpleDateFormat("yyyy/MM/dd")
    var hehe = dateFormat.format( now )
    hehe
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值