我正在尝试使用GJS,更准确地说,是以同步方式读取文本文件。下面是一个用于文件读取的异步函数示例
gio-cat.js我发现了如何使用下一个函数处理seed:
function readFile(filename) {
print(filename);
var input_file = gio.file_new_for_path(filename);
var fstream = input_file.read();
var dstream = new gio.DataInputStream.c_new(fstream);
var data = dstream.read_until("", 0);
fstream.close();
return data;
}但不幸的是,它不能与GJS一起工作。有人能帮我吗?
发布于 2017-01-29 23:18:45
GLib有帮助函数GLib.file_get_contents(String fileName)来同步读取文件:
const GLib = imports.gi.GLib;
//...
let fileContents = String(GLib.file_get_contents("/path/to/yourFile")[1]);发布于 2013-04-13 22:09:46
当我使用GJS开发Cinnamon applet时,我经常使用get_file_contents_utf8_sync函数来读取文本文件:
const Cinnamon = imports.gi.Cinnamon;
let fileContent = Cinnamon.get_file_contents_utf8_sync("file path");如果你安装了Cinnamon并且你同意使用它,它会回答你的问题。
否则,这里是cinnamon-util.c中get_file_contents_utf8_sync函数的C代码,希望这能对您有所帮助:
char * cinnamon_get_file_contents_utf8_sync (const char *path, GError **error)
{
char *contents;
gsize len;
if (!g_file_get_contents (path, &contents, &len, error))
return NULL;
if (!g_utf8_validate (contents, len, NULL))
{
g_free (contents);
g_set_error (error,
G_IO_ERROR,
G_IO_ERROR_FAILED,
"File %s contains invalid UTF-8",
path);
return NULL;
}
return contents;
}发布于 2014-01-16 03:17:52
这里有一个只适用于Gio的解决方案。
function readFile(filename) {
let input_file = Gio.file_new_for_path(filename);
let size = input_file.query_info(
"standard::size",
Gio.FileQueryInfoFlags.NONE,
null).get_size();
let stream = input_file.open_readwrite(null).get_input_stream();
let data = stream.read_bytes(size, null).get_data();
stream.close(null);
return data;
}https://stackoverflow.com/questions/15972338
复制相似问题