lua
1.创建新文件--使用File类
import "java.io.File"--导入File类
File(文件路径).createNewFile()
--使用io库
io.open("/sdcard/aaaa", 'w')
2.创建新文件夹
--使用File类
import "java.io.File"--导入File类
File(文件夹路径).mkdir()
--创建多级文件夹
File(文件夹路径).mkdirs()
--shell
os.execute('mkdir '..文件夹路径)
3.重命名与移动文件
--Shell
os.execute("mv "..oldname.." "..newname)
--os
os.rename (oldname, newname)
--File
import "java.io.File"--导入File类
File(旧).renameTo(File(新))
4.追加更新文件
io.open(文件路径,"a+"):write("更新的内容"):close()
5.更新文件
io.open(文件路径,"w+"):write("更新的内容"):close()
6.写入文件
io.open(文件路径,"w"):write("内容"):close()
7.写入文件(自动创建父文件夹)
function 写入文件(路径,内容)
import "java.io.File"
f=File(tostring(File(tostring(路径)).getParentFile())).mkdirs()
io.open(tostring(路径),"w"):write(tostring(内容)):close()
end
8.读取文件
io.open(文件路径):read("*a")
9.按行读取文件
for c in io.lines(文件路径) do
print(c)
end
10.删除文件或文件夹
--使用File类
import "java.io.File"--导入File类
File(文件路径).delete()
--使用os方法
os.remove (filename)
11.复制文件
LuaUtil.copyDir(from,to)
12.递归删除文件夹或文件
--使用LuaUtil辅助库
LuaUtil.rmDir(路径)
--使用Shell
os.execute("rm -r "..路径)
13.替换文件内字符串
function 替换文件字符串(路径,要替换的字符串,替换成的字符串)
if 路径 then
路径=tostring(路径)
内容=io.open(路径):read("*a")
io.open(路径,"w+"):write(tostring(内容:gsub(要替换的字符串,替换成的字符串))):close()
else
return false
end
end
14.获取文件列表
import("java.io.File")
luajava.astable(File(文件夹路径).listFiles())
15.获取文件名称
import "java.io.File"--导入File类
File(路径).getName()
16.获取文件大小
function GetFileSize(path)
import "java.io.File"
import "android.text.format.Formatter"
size=File(tostring(path)).length()
Sizes=Formatter.formatFileSize(activity, size)
return Sizes
end
17.获取文件或文件夹最后修改时间
function GetFilelastTime(path)
f = File(path);
cal = Calendar.getInstance();
time = f.lastModified()
cal.setTimeInMillis(time);
return cal.getTime().toLocaleString()
end
18.获取文件字节
import "java.io.File"--导入File类
File(路径).length()
19.获取父文件夹路径
import "java.io.File"--导入File类
File(path).getParentFile()
20.获取文件mime类型
function GetFileMime(name)
import "android.webkit.MimeTypeMap"
ExtensionName=tostring(name):match("%.(.+)")
Mime=MimeTypeMap.getSingleton().getMimeTypeFromExtension(ExtensionName)
return tostring(Mime)
end
print(GetFileMime("/sdcard/a.png"))
21.判断路径是不是文件夹或文件
--判断文件夹:
import "java.io.File"--导入File类
File(路径).isDirectory()
--也可用来判断文件夹存不存在
--判断文件:import "java.io.File"--导入File类
File(路径).isFile()
--也可用来判断文件存不存在
22.判断文件或文件夹是否存在
import "java.io.File"--导入File类 File(路径).exists()
--使用io function file_exists(path) local f=io.open(path,'r') if f~=nil then io.close(f) return true else return false end end
23.判断是否系统隐藏文件
import "java.io.File"--导入File类
File(路径).isHidden()
lua-文件操作代码大全