object:write()

类型 函数
对象 文件
io.*
返回值
修订版 发行版 2024.3703
关键字 写入、文件
另请参阅 io.open()
读取和写入文件

概述

向其每个参数所在的文件中写入值。这些参数必须是 字符串数字。要写入其他值,请在调用 File:write() 之前使用 tostring()string.format()

陷阱

出于安全原因,不允许在 system.ResourceDirectory(应用程序存储的目录)中写入文件。在 system.pathForFile() 函数中打开文件以供写入时,必须指定 system.DocumentsDirectorysystem.TemporaryDirectorysystem.CachesDirectory

语法

File:write( arg1 [, arg2] [, ...] )
arg1、arg2、…(必要)

字符串。要写入 File 对象所表示的文件的一个或多个字符串。

示例

-- Data (string) to write
local saveData = "My app state data"

-- Path for the file to write
local path = system.pathForFile( "myfile.txt", system.DocumentsDirectory )

-- Open the file handle
local file, errorString = io.open( path, "w" )

if not file then
    -- Error occurred; output the cause
    print( "File error: " .. errorString )
else
    -- Write data to file
    file:write( saveData )
    -- Close the file handle
    io.close( file )
end

file = nil