【问题标题】:Vala `load_contents` error with large files大文件的 Vala `load_contents` 错误
【发布时间】:2021-12-20 15:06:15
【问题描述】:

我正在尝试读取文件的内容(应该很容易...)并且在我尝试读取大文件之前没有任何问题(更多超过 2 GB)。我收到一个我不知道如何解决的错误,并且我还没有找到任何替代方法来读取适用于大文件的内容。这是我的代码:

File file = File.new_for_path (abs_path);
uint8[]  contents;
try {
    string etag_out;
    file.load_contents (null, out contents, out etag_out);
}catch (Error e){
    error("Error reading from file: %s", e.message);
}

content 应该包含从abs_path 读取的所有字节。但我收到一条错误消息:

 Error reading from file: Bad address

我不知道为什么会收到 Bad address 错误。该文件存在。另一个同名但大小仅为 50 MB 的文件运行良好。

有人有替代解决方案来读取 Vala 中的大文件吗?或者知道如何使它起作用?

注意:我使用 load_content 方法是因为我想要字节 (uint8 []),而不是字符串。

【问题讨论】:

  • 您是否需要将整个文件同时存储在内存中,或者您是否能够分块加载文件并在较小的部分上进行操作?
  • 我不需要内存中的整个文件,我必须通过 Soap Message 发送文件的内容,并且可以分块。

标签: vala


【解决方案1】:

正如您所注意到的,将大文件读入内存可能很麻烦而且速度很慢。由于您能够以块的形式处理文件数据,因此您可以使用像这样的缓冲区一次读取文件一点点:

size_t BUFFER_SIZE = 256;
File file = File.new_for_path (abs_path);
Cancellable cancellable = new Cancellable ();
...

try {
    // Stream the file in chunks rather than loading the entire thing into memory
    FileInputStream file_input_stream = file.read (cancellable);
    ssize_t bytes_read = 0;
    uint8[] buffer = new uint8[BUFFER_SIZE];
    while ((bytes_read = file_input_stream.read (buffer, cancellable)) != 0) {
        // Send the buffer content as needed
    }
} catch (GLib.Error e) {
    critical ("Error reading file: %s", e.message);
}

这将读取 BUFFER_SIZE 块中的文件,然后您可以根据需要通过 SOAP 消息等发送。

【讨论】:

  • 不错!谢谢!这就是我一直在寻找的,一种读取 X 字节的方法。这解决了问题。
猜你喜欢
  • 1970-01-01
  • 2011-01-30
  • 1970-01-01
  • 1970-01-01
  • 2013-05-03
  • 2018-11-21
  • 1970-01-01
  • 1970-01-01
  • 2012-02-22
相关资源
最近更新 更多