#建立一个222. rb file and enter the character file = File.Open ("222.rb", "w+") file.puts "123\NWADWA\N12124124\NDWDW" File.close #输出222. RB Content Fil
E.open ("222.rb", "r+") do |file|
While line = File.gets puts line end #直接用IO操作文件 Io.foreach ("222.rb") do |line| Puts lines if line =~/abc/#输出匹配到了 ' abc ' of the row where the ' puts ' if line!~/qwe/#输出没有匹配到 ' Qwe ' is the row end #输出文件的绝对路径 puts File.expand_
Path ("222.rb") #count chars from a file file= file.new ("222.rb") W_count = 0 File.each_byte do |byte| W_count + + 1 if byte ==?1 end puts "#{w_count}" #create new file and write some words there print "the" file "is exist ? --> "puts File.exist?" ("Asd.txt") #判断文件是否存在 file= file.new ("Asd.txt", "W") print "The file now is exist?" --> "puts File.exist?" ("Asd.txt") file.write ("Hehe\nhahah") #io. Stream operation require ' Stringio ' iOS = stringio.new ("abcdef\n ABC \ \ 12345 ") Ios.seek (5) #把偏移指针移到5 (e-letter location) ios.puts (" Xyz3 ") #从5开始覆写原有数据 puts Ios.tell #tell--returns the current offset (in bytes)
of iOS. Puts Ios.string puts iOS.String.dump #忽略 \ n Escaped #another example require ' stringio ' iOS = stringio.new ("Abcdef\nq9ert \ 12345") Ios.seek (3) ios.un Getc (? w) #replace the char at index 3 puts "PTR = #{ios.tell}" S1 = ios.gets #filte the "\ n" s2 = Ios.gets puts S1-puts s 2 #Ruby打开文件并写入数据操作 txt = file.open ("File path", "w+") txt.puts ' contents of file to be written ' txt.close #从文件里读取数据 num = file.readlines ("File path") [0]. Chomp #打开文件的方法 System ("Notepad file path")