The best Ruby file input and output Tutorial In 2024, In this tutorial you can learn putsstatement,getsStatement,putcstatement,printstatements,Opening and Closing Files,Reading and writing files,Rename and delete files,File mode and ownership,Document Access,Ruby directory,File & Create a temporary directory,Built-in Functions,
Ruby to provide a set of I / O-related methods implemented in the kernel (Kernel) module. All I / O method is derived from the IO class.
IOprovides all the class-based approach, such asread, write, gets, puts,readline, getc andprintf.
This section will explain all available Ruby-based I / O functions. For more functions, please see Ruby'sIOclass.
In the previous section, you assigned to a variable, and then use theputsstatement printout.
putsstatement indicates that the program displays the values stored in variables. This will add a new row at the end of each line.
#!/usr/bin/ruby val1 = "This is variable one" val2 = "This is variable two" puts val1 puts val2
Run the above example output is:
This is variable one This is variable two
getsstatement can be used to obtain user input from the standard screen called STDIN.
The following code demonstrates how to use gets statement. The code will prompt the user to enter a value that will be stored in the variable val, the final will be printed on STDOUT.
#!/usr/bin/ruby puts "Enter a value :" val = gets puts val
Run the above example output is:
Enter a value : This is entered value This is entered value
Andputsa different statement, the statementputsthe output of the whole string to the screen, whileputcstatement can be used to output a character sequence.
The output of the following code only character H:
#!/usr/bin/ruby str="Hello Ruby!" putc str
Run the above example output is:
H
printstatements andputsa similar statement. The only difference is that after the statementputsthe output will jump to the next line, while the use ofprintstatement, the cursor is positioned on the same line.
#!/usr/bin/ruby print "Hello World" print "Good Morning"
Run the above example output is:
Hello WorldGood Morning
As of now, you have to read and write to the standard input and output. Now, we will look at how the actual data files.
You can create aFileobject is used to readFile.newmethod, write or read and write, read and write permissions depending on mode parameters. Finally, you can useFile.closemethod to close the file.
aFile = File.new("filename", "mode") # /en. 处理文件 aFile.close
You can create a new file object usingFile.openmethod, and the object is assigned to the file file. However, there is one difference betweenFile.openandFile.newmethods. The difference isFile.openmethod can be associated with the block, but notFile.newmethod.
File.open("filename", "mode") do |aFile| # /en. process the file end
The following table lists the open files in different modes:
模式 | 描述 |
---|---|
r | 只读模式。文件指针被放置在文件的开头。这是默认模式。 |
r+ | 读写模式。文件指针被放置在文件的开头。 |
w | 只写模式。如果文件存在,则重写文件。如果文件不存在,则创建一个新文件用于写入。 |
w+ | 读写模式。如果文件存在,则重写已存在的文件。如果文件不存在,则创建一个新文件用于读写。 |
a | 只写模式。如果文件存在,则文件指针被放置在文件的末尾。也就是说,文件是追加模式。如果文件不存在,则创建一个新文件用于写入。 |
a+ | 读写模式。如果文件存在,则文件指针被放置在文件的末尾。也就是说,文件是追加模式。如果文件不存在,则创建一个新文件用于读写。 |
The method for simple I / O can also be used for all file objects. So, gets reads a line from standardinput,aFile.gets aFile reads a line from the file object.
However, I / O object provides an additional set of access methods, provides us with convenience.
You can use the methodsysreadto read the contents of the file. When using the method sysread, you can use any one mode to open the file. E.g:
The following is the input text file:
This is a simple text file for testing purpose.
Now let's try to read the file:
#!/usr/bin/ruby aFile = File.new("input.txt", "r") if aFile content = aFile.sysread(20) puts content else puts "Unable to open file!" end
This statement will enter the first 20 characters of the file. The file pointer will be placed in a position in the file 21 characters.
You can use the methodsyswriteto write to the file. When using the method syswrite, you need to open the file in write mode. E.g:
#!/usr/bin/ruby aFile = File.new("input.txt", "r+") if aFile aFile.syswrite("ABCDEF") else puts "Unable to open file!" end
The statements are written "ABCDEF" to a file.
This method belongs to the classFile.Each_byte iterative method is able to string each character. Consider the following code examples:
#!/usr/bin/ruby aFile = File.new("input.txt", "r+") if aFile aFile.syswrite("ABCDEF") aFile.rewind aFile.each_byte {|ch| putc ch; putc ?. } else puts "Unable to open file!" end
One by one character is passed variable ch, and then displayed on the screen, as shown below:
A.B.C.D.E.F.s. .a. .s.i.m.p.l.e. .t.e.x.t. .f.i.l.e. .f.o.r. .t.e.s.t.i.n.g. .p.u.r.p.o.s.e/en.
Fileclass is a subclass of class IO. IO class also has some methods for manipulating files.
IO.readlinesis IO class a method. The progressive method returns the contents of the file. The following code shows a methodIO.readlinesuse:
#!/usr/bin/ruby arr = IO.readlines("input.txt") puts arr[0] puts arr[1]
In this code, the variable is an array arr. Each row is an array arr fileinput.txtan element. Therefore, arr [0] will contain the first line, and arr [1] will contain the second line of the file.
The method also returns progressive output.Foreachbetween different methods and methodsreadlinesis associated methodforeachblock. However, unlike the methodreadlines,foreach method instead of returning an array. E.g:
#!/usr/bin/ruby IO.foreach("input.txt"){|block| puts block}
This code willtestthe contents of the file passed variable progressive block, then the output will be displayed on the screen.
You can rename and delete filesrenameanddeletemethods.
The following example renames a file that already existstest1.txt:
#!/usr/bin/ruby # 重命名文件 test1.txt 为 test2.txt File.rename( "test1.txt", "test2.txt" )
The following example to delete an existing filetest2.txt:
#!/usr/bin/ruby # 删除文件 test2.txt File.delete("text2.txt")
Usechmodto change the method with a mask pattern or file permissions / access list:
Examples of the following changes to an existing filetest.txtmodel for a mask value:
#!/usr/bin/ruby file = File.new( "test.txt", "w" ) file.chmod( 0755 )
The following table lists the different maskschmodmethod can be used:
掩码 | 描述 |
---|---|
0700 | rwx 掩码,针对所有者 |
0400 | r ,针对所有者 |
0200 | w ,针对所有者 |
0100 | x ,针对所有者 |
0070 | rwx 掩码,针对所属组 |
0040 | r ,针对所属组 |
0020 | w ,针对所属组 |
0010 | x ,针对所属组 |
0007 | rwx 掩码,针对其他人 |
0004 | r ,针对其他人 |
0002 | w ,针对其他人 |
0001 | x ,针对其他人 |
4000 | 执行时设置用户 ID |
2000 | 执行时设置所属组 ID |
1000 | 保存交换文本,甚至在使用后也会保存 |
The following command to check the file before opening the file already exists:
#!/usr/bin/ruby File.open("file.rb") if File::exists?( "file.rb" )
The following command to query whether the file is really a file:
#!/usr/bin/ruby # 返回 true 或false File.file?( "text.txt" )
Following command to check whether the given filename is a directory:
#!/usr/bin/ruby # 一个目录 File::directory?( "/usr/local/bin" ) # => true # 一个文件 File::directory?( "file.rb" ) # => false
Are the following command to check the file readable, writable, executable:
#!/usr/bin/ruby File.readable?( "test.txt" ) # => true File.writable?( "test.txt" ) # => true File.executable?( "test.txt" ) # => false
The following command checks the file size to zero:
#!/usr/bin/ruby File.zero?( "test.txt" ) # => true
The following command returns the size of the file:
#!/usr/bin/ruby File.size?( "text.txt" ) # => 1002
The following command is used to check the type of file:
#!/usr/bin/ruby File::ftype( "test.txt" ) # => file
ftype method returns a value of the following to identify the type offile: file, directory, characterSpecial, blockSpecial, fifo, link, socketor unknown.
The following command is used to check the file was created, modified, or last access time:
#!/usr/bin/ruby File::ctime( "test.txt" ) # => Fri May 09 10:06:37 -0700 2008 File::mtime( "text.txt" ) # => Fri May 09 10:44:44 -0700 2008 File::atime( "text.txt" ) # => Fri May 09 10:45:01 -0700 2008
All files are contained in the directory, Ruby provides a process files and directories.Fileclasses for working withfiles,Dir classes for working directory.
To change the directory in the Ruby program, please useDir.chdir.Examples of the following changes to the current directory is/ usr / bin.
Dir.chdir("/usr/bin")
You can view the current directoryDir.pwd:
puts Dir.pwd # 返回当前目录,类似 /usr/bin
Dir.entriesYou can get a list of files and directories inside the specified directory:
puts Dir.entries("/usr/bin").join(' ')
Dir.entriesreturns an array containing all the specified directory.Dir.foreachprovides the same functionality:
Dir.foreach("/usr/bin") do |entry| puts entry end
Get a directory listing of a more concise way is a method by using the Dir class array:
Dir["/usr/bin/*"]
Dir.mkdircan be used to create the directory:
Dir.mkdir("mynewdir")
You can also set permissions on the new directory (not existing directory) adopted mkdir:
Note: Mask 755 Set owner (owner), belongs to the group (group), everyone (world [anyone]) permissions rwxr-xr-x, where r = read read, w = write write, x = execute execution.
Dir.mkdir( "mynewdir", 755 )
Dir.deletebe used to delete directories.Dir.unlinkandDir.rmdirperform the same function, provides us with convenience.
Dir.delete("testdir")
Temporary files are created that are simply in the process of execution of the program, but does not permanently stored information.
Dir.tmpdirprovides a path on the current system temporary directory, which by default, but is unavailable. To makeDir.tmpdiravailable, with the required 'tmpdir' is necessary.
You canDir.tmpdirandFile.joinused together to create a platform-independent temporary files:
require 'tmpdir' tempfilename = File.join(Dir.tmpdir, "tingtong") tempfile = File.new(tempfilename, "w") tempfile.puts "This is a temporary file" tempfile.close File.delete(tempfilename)
This code creates a temporary file in which to write data, and then delete the file. Ruby standard library also contains a library namedTempfile,and the library can be used to create temporary files:
require 'tempfile' f = Tempfile.new('tingtong') f.puts "Hello" puts f.path f.close
The following provides a complete list of files and directories in Ruby's built-in functions: