zoukankan      html  css  js  c++  java
  • ruby 对文件的操作

    读取一个文件,将其打印出来:

    lines = File.open('dom.js').readlines
    puts "======================="
    lines.each { |line| puts(line)}
    

    或者:

    File.open("dom.js") do |file|
      while line = file.gets
        puts line
      end
    end
    

    后一种能确保文件用完后被关闭。

    向目标文件追加内容:

    file = File.open("dom.js","a")
    file.puts "//this is new content. "
    file.close
    

    但这有时可能出现不能添加中文内容的情况,报“invalid multibyte char (US-ASCII) ”错误,我们就要在当前脚本的最上面添加这么一下注释,就没事了,即

    # coding: utf-8 
    file = File.open("dom.js","a")
    file.puts "//这是新追加的内容. "
    file.close
    

    创建一个新文件,并往其里面添加内容。

    # coding: utf-8 
    file = File.new("new_file.js","w");
    file << 'var a = "test";'
    file.close;
    

    文件重命名:

    # coding: utf-8 
    File.rename( "new_file.js", "new.js" )
    

    文件重命名:

    # coding: utf-8 
    File.rename( "new_file.js", "new.js" )#原来的文件名,新的文件名
    

    删除文件

    # coding: utf-8 
    File.delete( "new.js" )#原来的文件名
    

    目录操作:

    # coding: utf-8 
    Dir.mkdir("new")#创建一个新文件夹
    Dir.rmdir("new")#删除指定的文件夹
    

    将一个文件拷贝到目标目标:

    require 'fileutils'
    FileUtils.cp 'new.js', 'new'
    

    将一个文件移动到目标目标:

    require 'fileutils'
    FileUtils.mv 'new.js', 'new'
    
    http://www.kuqin.com/rubycndocument/man/addlib/fileutils.html
  • 相关阅读:
    shiro实战系列(三)之架构
    shiro实战系列(二)之入门实战续
    ShopNC B2B2C多用户商城2014商业版,带微商城
    开源 SHOPNC B2B2C结算营运版 wap IM客服 API 手机app 短信通知
    PHP5.3下加速器ZendGuardLoader安装 (LNMP/lnmpa)
    XAMPP + Xdebug+Zend Studio
    magento 12 配置安装教程
    C#控件一览表
    GetXamarin.xambe
    新建电子监控点与测速点
  • 原文地址:https://www.cnblogs.com/rubylouvre/p/2005122.html
Copyright © 2011-2022 走看看