zoukankan      html  css  js  c++  java
  • scala的io

    import java.io.File
    import scala.io.Source

    val filePath = new File("C:\Users\peanut\Desktop\apple.txt")

    val source=Source.fromFile(filePath)
    val source2=Source.fromFile(filePath,"UTF-8")
    val source3 = Source.fromURL("www.baidu.com","UTF-8")
    val source4 = Source.fromString("i like strawberry")

    //读取文件中所有行,返回一个迭代器
    val lineIterator = source.getLines()
    lineIterator.foreach(println)

    //读取文件中所有行,toArray返回一个数组
    val lineArray = source.getLines().toArray
    for(ele <- lineArray){
    println("line: "+ele)
    }

    //读取文件中所有行,mkstring返回一个字符串
    val lineString = source.getLines().mkString //文件不能过大


    //将文件内容以空格分割,返回一个数组
    val arrayTokens = source.mkString.split("\s+")

    source.close() //关闭流


    import java.io.PrintWriter

    val out =new PrintWriter("C:\Users\peanut\Desktop\appleWrite.txt")
    for (i <- 1 to 10){
    //out.println("hello")
    out.write("Apple")
    }
    out.close()//关闭打印流

    #######################################
    Java的IO操作---File类

    public static final String pathSeparator 常量 表示路径的分隔符(windows:‘;’)

    public static final String separator 常量 表示路径分隔符(windows:‘’)

    public File(String pathname) 构造 创建File类对象,传入完整的路径

    public boolean createNewFile() throws IOException 普通 创建新文件

    public boolean exists() 普通 判断文件是否存在

    public boolean delete() 普通 删除文件

    public boolean isDirectory() 普通 判断给定的路径是否是一个目录

    public long length() 普通 返回文件的大小

    public String[] list() 普通 列出指定目录的全部内容,只是名称

    public File[] listFiles() 普通 列出指定目录的全部内容,会列出路径。

    public boolean mkdir() 普通 创建一个目录

    public boolean renameTo(File dest) 普通 为已有的文件重命名

    /**
    * 遍历出指定目录下的全部文件
    * @param file 指定目录
    * @return Array[File]
    */
    def getFile(file: File): Array[File] = {
    val files = file.listFiles().filter(!_.isDirectory) //过滤掉目录
    .filter(t => t.toString.endsWith(".txt") || t.toString.endsWith(".json") ) //过滤保留特定后缀名的文件
    //递归遍历子目录
    val files2=file.listFiles().filter(_.isDirectory).flatMap(getFile)
    files ++ files2
    }


    val path = new File("C:\Users\peanut\Desktop\myFile")
    for(file <- getFile(path)){
    val filePath=file.getAbsolutePath //获取绝对路径
    System.out.println("getAbsolutePath: " + filePath)
    val fileName=file.getName //获取文件名
    System.out.println("fileName: " + fileName)
    }


    val path2 = new File("C:\Users\peanut\Desktop\apple.txt")

    try {
    path2.createNewFile()
    println("create file success ")
    } catch {
    case e:Exception => println("can't create "+path2)
    }

    if(path2.exists()){
    path2.delete()
    println("delete file success!")
    }

  • 相关阅读:
    python小练习
    python学习笔记
    google测试之道读书笔记一
    webservice头部认证
    我们需要什么样的测试?
    pt-ioprofile在CentOS7上无法运行的解决办法
    推荐Nginx系列文章
    linux开启coredump的3种方法
    55, select/poll returned error
    centos ftp安装
  • 原文地址:https://www.cnblogs.com/ShyPeanut/p/12612662.html
Copyright © 2011-2022 走看看