mirror of
https://github.com/godotengine/godot-docs-l10n.git
synced 2025-12-31 09:49:22 +03:00
1488 lines
119 KiB
ReStructuredText
1488 lines
119 KiB
ReStructuredText
:github_url: hide
|
||
|
||
.. _class_FileAccess:
|
||
|
||
FileAccess
|
||
==========
|
||
|
||
**Наследует:** :ref:`RefCounted<class_RefCounted>` **<** :ref:`Object<class_Object>`
|
||
|
||
Предоставляет методы для операций чтения и записи файлов.
|
||
|
||
.. rst-class:: classref-introduction-group
|
||
|
||
Описание
|
||
----------------
|
||
|
||
Этот класс можно использовать для постоянного хранения данных в файловой системе пользовательского устройства и для чтения из неё. Это полезно для хранения сохраненных данных игры или файлов конфигурации игрока.
|
||
|
||
\ **Пример:** Как записать и прочитать файл. Файл с именем ``"save_game.dat"`` будет сохранён в папке пользовательских данных, как указано в документации :doc:`Пути к данным <../tutorials/io/data_paths>`:
|
||
|
||
|
||
.. tabs::
|
||
|
||
.. code-tab:: gdscript
|
||
|
||
func save_to_file(content):
|
||
var file = FileAccess.open("user://save_game.dat", FileAccess.WRITE)
|
||
file.store_string(content)
|
||
|
||
func load_from_file():
|
||
var file = FileAccess.open("user://save_game.dat", FileAccess.READ)
|
||
var content = file.get_as_text()
|
||
return content
|
||
|
||
.. code-tab:: csharp
|
||
|
||
public void SaveToFile(string content)
|
||
{
|
||
using var file = FileAccess.Open("user://save_game.dat", FileAccess.ModeFlags.Write);
|
||
file.StoreString(content);
|
||
}
|
||
|
||
public string LoadFromFile()
|
||
{
|
||
using var file = FileAccess.Open("user://save_game.dat", FileAccess.ModeFlags.Read);
|
||
string content = file.GetAsText();
|
||
return content;
|
||
}
|
||
|
||
|
||
|
||
Экземпляр **FileAccess** имеет собственный файловый курсор, который представляет собой позицию в байтах в файле, где будет выполнена следующая операция чтения/записи. Такие функции, как :ref:`get_8()<class_FileAccess_method_get_8>`, :ref:`get_16()<class_FileAccess_method_get_16>`, :ref:`store_8()<class_FileAccess_method_store_8>` и :ref:`store_16()<class_FileAccess_method_store_16>`, перемещают файловый курсор вперёд на количество прочитанных/записанных байтов. Файловый курсор можно переместить в определённую позицию с помощью :ref:`seek()<class_FileAccess_method_seek>` или :ref:`seek_end()<class_FileAccess_method_seek_end>`, а его позицию можно получить с помощью :ref:`get_position()<class_FileAccess_method_get_position>`.
|
||
|
||
Экземпляр **FileAccess** закрывает свой файл при освобождении. Поскольку он наследует :ref:`RefCounted<class_RefCounted>`, это происходит автоматически, когда файл больше не используется. Для его более раннего закрытия можно вызвать :ref:`close()<class_FileAccess_method_close>`. В C# ссылку необходимо удалить вручную, что можно сделать с помощью оператора ``using`` или путём прямого вызова метода ``Dispose``.
|
||
|
||
\ **Примечание:** Для доступа к ресурсам проекта после экспорта рекомендуется использовать :ref:`ResourceLoader<class_ResourceLoader>` вместо **FileAccess**, поскольку некоторые файлы преобразуются в форматы, специфичные для движка, и их исходные файлы могут отсутствовать в экспортированном пакете PCK. При использовании **FileAccess** убедитесь, что файл включён в экспорт, изменив его режим импорта на **Сохранить файл (экспортируется как есть)** в панели импорта, или, для файлов, для которых этот параметр недоступен, измените фильтр экспорта без ресурсов в диалоговом окне экспорта, включив расширение файла (например, ``*.txt``).
|
||
|
||
\ **Примечание:** Файлы автоматически закрываются только при «нормальном» завершении процесса (например, нажатием кнопки закрытия в менеджере окон или сочетанием клавиш :kbd:`Alt + F4`). Если остановить выполнение проекта, нажав :kbd:`F8` во время его работы, файл не будет закрыт, так как игровой процесс будет завершён. Эту проблему можно обойти, регулярно вызывая :ref:`flush()<class_FileAccess_method_flush>`.
|
||
|
||
.. rst-class:: classref-introduction-group
|
||
|
||
Обучающие материалы
|
||
--------------------------------------
|
||
|
||
- :doc:`Файловая система <../tutorials/scripting/filesystem>`
|
||
|
||
- :doc:`Загрузка и сохранение файла времени выполнения <../tutorials/io/runtime_file_loading_and_saving>`
|
||
|
||
- :doc:`API двоичной сериализации <../tutorials/io/binary_serialization_api>`
|
||
|
||
- `Демоверсия 3D вокселей <https://godotengine.org/asset-library/asset/2755>`__
|
||
|
||
.. rst-class:: classref-reftable-group
|
||
|
||
Свойства
|
||
----------------
|
||
|
||
.. table::
|
||
:widths: auto
|
||
|
||
+-------------------------+---------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`big_endian<class_FileAccess_property_big_endian>` |
|
||
+-------------------------+---------------------------------------------------------+
|
||
|
||
.. rst-class:: classref-reftable-group
|
||
|
||
Методы
|
||
------------
|
||
|
||
.. table::
|
||
:widths: auto
|
||
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| |void| | :ref:`close<class_FileAccess_method_close>`\ (\ ) |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`FileAccess<class_FileAccess>` | :ref:`create_temp<class_FileAccess_method_create_temp>`\ (\ mode_flags\: :ref:`int<class_int>`, prefix\: :ref:`String<class_String>` = "", extension\: :ref:`String<class_String>` = "", keep\: :ref:`bool<class_bool>` = false\ ) |static| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`eof_reached<class_FileAccess_method_eof_reached>`\ (\ ) |const| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`file_exists<class_FileAccess_method_file_exists>`\ (\ path\: :ref:`String<class_String>`\ ) |static| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| |void| | :ref:`flush<class_FileAccess_method_flush>`\ (\ ) |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`int<class_int>` | :ref:`get_8<class_FileAccess_method_get_8>`\ (\ ) |const| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`int<class_int>` | :ref:`get_16<class_FileAccess_method_get_16>`\ (\ ) |const| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`int<class_int>` | :ref:`get_32<class_FileAccess_method_get_32>`\ (\ ) |const| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`int<class_int>` | :ref:`get_64<class_FileAccess_method_get_64>`\ (\ ) |const| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`int<class_int>` | :ref:`get_access_time<class_FileAccess_method_get_access_time>`\ (\ file\: :ref:`String<class_String>`\ ) |static| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`String<class_String>` | :ref:`get_as_text<class_FileAccess_method_get_as_text>`\ (\ ) |const| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`PackedByteArray<class_PackedByteArray>` | :ref:`get_buffer<class_FileAccess_method_get_buffer>`\ (\ length\: :ref:`int<class_int>`\ ) |const| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`PackedStringArray<class_PackedStringArray>` | :ref:`get_csv_line<class_FileAccess_method_get_csv_line>`\ (\ delim\: :ref:`String<class_String>` = ","\ ) |const| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`float<class_float>` | :ref:`get_double<class_FileAccess_method_get_double>`\ (\ ) |const| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Error<enum_@GlobalScope_Error>` | :ref:`get_error<class_FileAccess_method_get_error>`\ (\ ) |const| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`PackedByteArray<class_PackedByteArray>` | :ref:`get_extended_attribute<class_FileAccess_method_get_extended_attribute>`\ (\ file\: :ref:`String<class_String>`, attribute_name\: :ref:`String<class_String>`\ ) |static| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`String<class_String>` | :ref:`get_extended_attribute_string<class_FileAccess_method_get_extended_attribute_string>`\ (\ file\: :ref:`String<class_String>`, attribute_name\: :ref:`String<class_String>`\ ) |static| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`PackedStringArray<class_PackedStringArray>` | :ref:`get_extended_attributes_list<class_FileAccess_method_get_extended_attributes_list>`\ (\ file\: :ref:`String<class_String>`\ ) |static| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`PackedByteArray<class_PackedByteArray>` | :ref:`get_file_as_bytes<class_FileAccess_method_get_file_as_bytes>`\ (\ path\: :ref:`String<class_String>`\ ) |static| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`String<class_String>` | :ref:`get_file_as_string<class_FileAccess_method_get_file_as_string>`\ (\ path\: :ref:`String<class_String>`\ ) |static| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`float<class_float>` | :ref:`get_float<class_FileAccess_method_get_float>`\ (\ ) |const| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`float<class_float>` | :ref:`get_half<class_FileAccess_method_get_half>`\ (\ ) |const| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`get_hidden_attribute<class_FileAccess_method_get_hidden_attribute>`\ (\ file\: :ref:`String<class_String>`\ ) |static| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`int<class_int>` | :ref:`get_length<class_FileAccess_method_get_length>`\ (\ ) |const| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`String<class_String>` | :ref:`get_line<class_FileAccess_method_get_line>`\ (\ ) |const| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`String<class_String>` | :ref:`get_md5<class_FileAccess_method_get_md5>`\ (\ path\: :ref:`String<class_String>`\ ) |static| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`int<class_int>` | :ref:`get_modified_time<class_FileAccess_method_get_modified_time>`\ (\ file\: :ref:`String<class_String>`\ ) |static| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Error<enum_@GlobalScope_Error>` | :ref:`get_open_error<class_FileAccess_method_get_open_error>`\ (\ ) |static| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`String<class_String>` | :ref:`get_pascal_string<class_FileAccess_method_get_pascal_string>`\ (\ ) |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`String<class_String>` | :ref:`get_path<class_FileAccess_method_get_path>`\ (\ ) |const| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`String<class_String>` | :ref:`get_path_absolute<class_FileAccess_method_get_path_absolute>`\ (\ ) |const| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`int<class_int>` | :ref:`get_position<class_FileAccess_method_get_position>`\ (\ ) |const| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`get_read_only_attribute<class_FileAccess_method_get_read_only_attribute>`\ (\ file\: :ref:`String<class_String>`\ ) |static| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`float<class_float>` | :ref:`get_real<class_FileAccess_method_get_real>`\ (\ ) |const| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`String<class_String>` | :ref:`get_sha256<class_FileAccess_method_get_sha256>`\ (\ path\: :ref:`String<class_String>`\ ) |static| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`int<class_int>` | :ref:`get_size<class_FileAccess_method_get_size>`\ (\ file\: :ref:`String<class_String>`\ ) |static| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| |bitfield|\[:ref:`UnixPermissionFlags<enum_FileAccess_UnixPermissionFlags>`\] | :ref:`get_unix_permissions<class_FileAccess_method_get_unix_permissions>`\ (\ file\: :ref:`String<class_String>`\ ) |static| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Variant<class_Variant>` | :ref:`get_var<class_FileAccess_method_get_var>`\ (\ allow_objects\: :ref:`bool<class_bool>` = false\ ) |const| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`is_open<class_FileAccess_method_is_open>`\ (\ ) |const| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`FileAccess<class_FileAccess>` | :ref:`open<class_FileAccess_method_open>`\ (\ path\: :ref:`String<class_String>`, flags\: :ref:`ModeFlags<enum_FileAccess_ModeFlags>`\ ) |static| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`FileAccess<class_FileAccess>` | :ref:`open_compressed<class_FileAccess_method_open_compressed>`\ (\ path\: :ref:`String<class_String>`, mode_flags\: :ref:`ModeFlags<enum_FileAccess_ModeFlags>`, compression_mode\: :ref:`CompressionMode<enum_FileAccess_CompressionMode>` = 0\ ) |static| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`FileAccess<class_FileAccess>` | :ref:`open_encrypted<class_FileAccess_method_open_encrypted>`\ (\ path\: :ref:`String<class_String>`, mode_flags\: :ref:`ModeFlags<enum_FileAccess_ModeFlags>`, key\: :ref:`PackedByteArray<class_PackedByteArray>`, iv\: :ref:`PackedByteArray<class_PackedByteArray>` = PackedByteArray()\ ) |static| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`FileAccess<class_FileAccess>` | :ref:`open_encrypted_with_pass<class_FileAccess_method_open_encrypted_with_pass>`\ (\ path\: :ref:`String<class_String>`, mode_flags\: :ref:`ModeFlags<enum_FileAccess_ModeFlags>`, pass\: :ref:`String<class_String>`\ ) |static| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Error<enum_@GlobalScope_Error>` | :ref:`remove_extended_attribute<class_FileAccess_method_remove_extended_attribute>`\ (\ file\: :ref:`String<class_String>`, attribute_name\: :ref:`String<class_String>`\ ) |static| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Error<enum_@GlobalScope_Error>` | :ref:`resize<class_FileAccess_method_resize>`\ (\ length\: :ref:`int<class_int>`\ ) |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| |void| | :ref:`seek<class_FileAccess_method_seek>`\ (\ position\: :ref:`int<class_int>`\ ) |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| |void| | :ref:`seek_end<class_FileAccess_method_seek_end>`\ (\ position\: :ref:`int<class_int>` = 0\ ) |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Error<enum_@GlobalScope_Error>` | :ref:`set_extended_attribute<class_FileAccess_method_set_extended_attribute>`\ (\ file\: :ref:`String<class_String>`, attribute_name\: :ref:`String<class_String>`, data\: :ref:`PackedByteArray<class_PackedByteArray>`\ ) |static| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Error<enum_@GlobalScope_Error>` | :ref:`set_extended_attribute_string<class_FileAccess_method_set_extended_attribute_string>`\ (\ file\: :ref:`String<class_String>`, attribute_name\: :ref:`String<class_String>`, data\: :ref:`String<class_String>`\ ) |static| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Error<enum_@GlobalScope_Error>` | :ref:`set_hidden_attribute<class_FileAccess_method_set_hidden_attribute>`\ (\ file\: :ref:`String<class_String>`, hidden\: :ref:`bool<class_bool>`\ ) |static| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Error<enum_@GlobalScope_Error>` | :ref:`set_read_only_attribute<class_FileAccess_method_set_read_only_attribute>`\ (\ file\: :ref:`String<class_String>`, ro\: :ref:`bool<class_bool>`\ ) |static| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Error<enum_@GlobalScope_Error>` | :ref:`set_unix_permissions<class_FileAccess_method_set_unix_permissions>`\ (\ file\: :ref:`String<class_String>`, permissions\: |bitfield|\[:ref:`UnixPermissionFlags<enum_FileAccess_UnixPermissionFlags>`\]\ ) |static| |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`store_8<class_FileAccess_method_store_8>`\ (\ value\: :ref:`int<class_int>`\ ) |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`store_16<class_FileAccess_method_store_16>`\ (\ value\: :ref:`int<class_int>`\ ) |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`store_32<class_FileAccess_method_store_32>`\ (\ value\: :ref:`int<class_int>`\ ) |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`store_64<class_FileAccess_method_store_64>`\ (\ value\: :ref:`int<class_int>`\ ) |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`store_buffer<class_FileAccess_method_store_buffer>`\ (\ buffer\: :ref:`PackedByteArray<class_PackedByteArray>`\ ) |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`store_csv_line<class_FileAccess_method_store_csv_line>`\ (\ values\: :ref:`PackedStringArray<class_PackedStringArray>`, delim\: :ref:`String<class_String>` = ","\ ) |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`store_double<class_FileAccess_method_store_double>`\ (\ value\: :ref:`float<class_float>`\ ) |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`store_float<class_FileAccess_method_store_float>`\ (\ value\: :ref:`float<class_float>`\ ) |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`store_half<class_FileAccess_method_store_half>`\ (\ value\: :ref:`float<class_float>`\ ) |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`store_line<class_FileAccess_method_store_line>`\ (\ line\: :ref:`String<class_String>`\ ) |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`store_pascal_string<class_FileAccess_method_store_pascal_string>`\ (\ string\: :ref:`String<class_String>`\ ) |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`store_real<class_FileAccess_method_store_real>`\ (\ value\: :ref:`float<class_float>`\ ) |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`store_string<class_FileAccess_method_store_string>`\ (\ string\: :ref:`String<class_String>`\ ) |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`store_var<class_FileAccess_method_store_var>`\ (\ value\: :ref:`Variant<class_Variant>`, full_objects\: :ref:`bool<class_bool>` = false\ ) |
|
||
+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
|
||
.. rst-class:: classref-section-separator
|
||
|
||
----
|
||
|
||
.. rst-class:: classref-descriptions-group
|
||
|
||
Перечисления
|
||
------------------------
|
||
|
||
.. _enum_FileAccess_ModeFlags:
|
||
|
||
.. rst-class:: classref-enumeration
|
||
|
||
enum **ModeFlags**: :ref:`🔗<enum_FileAccess_ModeFlags>`
|
||
|
||
.. _class_FileAccess_constant_READ:
|
||
|
||
.. rst-class:: classref-enumeration-constant
|
||
|
||
:ref:`ModeFlags<enum_FileAccess_ModeFlags>` **READ** = ``1``
|
||
|
||
Открывает файл для чтения. Курсор файла устанавливается в начало файла.
|
||
|
||
.. _class_FileAccess_constant_WRITE:
|
||
|
||
.. rst-class:: classref-enumeration-constant
|
||
|
||
:ref:`ModeFlags<enum_FileAccess_ModeFlags>` **WRITE** = ``2``
|
||
|
||
Opens the file for write operations. If the file exists, it is truncated to zero length and its contents are cleared. Otherwise, it is created.
|
||
|
||
\ **Note:** When creating a file it must be in an already existing directory. To recursively create directories for a file path, see :ref:`DirAccess.make_dir_recursive()<class_DirAccess_method_make_dir_recursive>`.
|
||
|
||
.. _class_FileAccess_constant_READ_WRITE:
|
||
|
||
.. rst-class:: classref-enumeration-constant
|
||
|
||
:ref:`ModeFlags<enum_FileAccess_ModeFlags>` **READ_WRITE** = ``3``
|
||
|
||
Открывает файл для чтения и записи. Не обрезает файл. Курсор файла устанавливается в начало файла.
|
||
|
||
.. _class_FileAccess_constant_WRITE_READ:
|
||
|
||
.. rst-class:: classref-enumeration-constant
|
||
|
||
:ref:`ModeFlags<enum_FileAccess_ModeFlags>` **WRITE_READ** = ``7``
|
||
|
||
Opens the file for read and write operations. If the file exists, it is truncated to zero length and its contents are cleared. Otherwise, it is created. The file cursor is positioned at the beginning of the file.
|
||
|
||
\ **Note:** When creating a file it must be in an already existing directory. To recursively create directories for a file path, see :ref:`DirAccess.make_dir_recursive()<class_DirAccess_method_make_dir_recursive>`.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _enum_FileAccess_CompressionMode:
|
||
|
||
.. rst-class:: classref-enumeration
|
||
|
||
enum **CompressionMode**: :ref:`🔗<enum_FileAccess_CompressionMode>`
|
||
|
||
.. _class_FileAccess_constant_COMPRESSION_FASTLZ:
|
||
|
||
.. rst-class:: classref-enumeration-constant
|
||
|
||
:ref:`CompressionMode<enum_FileAccess_CompressionMode>` **COMPRESSION_FASTLZ** = ``0``
|
||
|
||
Использует метод сжатия `FastLZ <https://fastlz.org/>`__.
|
||
|
||
.. _class_FileAccess_constant_COMPRESSION_DEFLATE:
|
||
|
||
.. rst-class:: classref-enumeration-constant
|
||
|
||
:ref:`CompressionMode<enum_FileAccess_CompressionMode>` **COMPRESSION_DEFLATE** = ``1``
|
||
|
||
Использует метод сжатия `DEFLATE <https://en.wikipedia.org/wiki/DEFLATE>`__.
|
||
|
||
.. _class_FileAccess_constant_COMPRESSION_ZSTD:
|
||
|
||
.. rst-class:: classref-enumeration-constant
|
||
|
||
:ref:`CompressionMode<enum_FileAccess_CompressionMode>` **COMPRESSION_ZSTD** = ``2``
|
||
|
||
Использует метод сжатия `Zstandard <https://facebook.github.io/zstd/>`__.
|
||
|
||
.. _class_FileAccess_constant_COMPRESSION_GZIP:
|
||
|
||
.. rst-class:: classref-enumeration-constant
|
||
|
||
:ref:`CompressionMode<enum_FileAccess_CompressionMode>` **COMPRESSION_GZIP** = ``3``
|
||
|
||
Использует метод сжатия `gzip <https://www.gzip.org/>`__.
|
||
|
||
.. _class_FileAccess_constant_COMPRESSION_BROTLI:
|
||
|
||
.. rst-class:: classref-enumeration-constant
|
||
|
||
:ref:`CompressionMode<enum_FileAccess_CompressionMode>` **COMPRESSION_BROTLI** = ``4``
|
||
|
||
Использует метод сжатия `brotli <https://github.com/google/brotli>`__ (поддерживается только распаковка).
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _enum_FileAccess_UnixPermissionFlags:
|
||
|
||
.. rst-class:: classref-enumeration
|
||
|
||
flags **UnixPermissionFlags**: :ref:`🔗<enum_FileAccess_UnixPermissionFlags>`
|
||
|
||
.. _class_FileAccess_constant_UNIX_READ_OWNER:
|
||
|
||
.. rst-class:: classref-enumeration-constant
|
||
|
||
:ref:`UnixPermissionFlags<enum_FileAccess_UnixPermissionFlags>` **UNIX_READ_OWNER** = ``256``
|
||
|
||
Прочитайте информацию о владельце.
|
||
|
||
.. _class_FileAccess_constant_UNIX_WRITE_OWNER:
|
||
|
||
.. rst-class:: classref-enumeration-constant
|
||
|
||
:ref:`UnixPermissionFlags<enum_FileAccess_UnixPermissionFlags>` **UNIX_WRITE_OWNER** = ``128``
|
||
|
||
Напишите для владельца бита.
|
||
|
||
.. _class_FileAccess_constant_UNIX_EXECUTE_OWNER:
|
||
|
||
.. rst-class:: classref-enumeration-constant
|
||
|
||
:ref:`UnixPermissionFlags<enum_FileAccess_UnixPermissionFlags>` **UNIX_EXECUTE_OWNER** = ``64``
|
||
|
||
Выполнить для владельца бита.
|
||
|
||
.. _class_FileAccess_constant_UNIX_READ_GROUP:
|
||
|
||
.. rst-class:: classref-enumeration-constant
|
||
|
||
:ref:`UnixPermissionFlags<enum_FileAccess_UnixPermissionFlags>` **UNIX_READ_GROUP** = ``32``
|
||
|
||
Прочитайте для группового бита.
|
||
|
||
.. _class_FileAccess_constant_UNIX_WRITE_GROUP:
|
||
|
||
.. rst-class:: classref-enumeration-constant
|
||
|
||
:ref:`UnixPermissionFlags<enum_FileAccess_UnixPermissionFlags>` **UNIX_WRITE_GROUP** = ``16``
|
||
|
||
Пишите для группового бита.
|
||
|
||
.. _class_FileAccess_constant_UNIX_EXECUTE_GROUP:
|
||
|
||
.. rst-class:: classref-enumeration-constant
|
||
|
||
:ref:`UnixPermissionFlags<enum_FileAccess_UnixPermissionFlags>` **UNIX_EXECUTE_GROUP** = ``8``
|
||
|
||
Выполнить для группового бита.
|
||
|
||
.. _class_FileAccess_constant_UNIX_READ_OTHER:
|
||
|
||
.. rst-class:: classref-enumeration-constant
|
||
|
||
:ref:`UnixPermissionFlags<enum_FileAccess_UnixPermissionFlags>` **UNIX_READ_OTHER** = ``4``
|
||
|
||
Прочтите другой бит.
|
||
|
||
.. _class_FileAccess_constant_UNIX_WRITE_OTHER:
|
||
|
||
.. rst-class:: classref-enumeration-constant
|
||
|
||
:ref:`UnixPermissionFlags<enum_FileAccess_UnixPermissionFlags>` **UNIX_WRITE_OTHER** = ``2``
|
||
|
||
Напишите для другого бита.
|
||
|
||
.. _class_FileAccess_constant_UNIX_EXECUTE_OTHER:
|
||
|
||
.. rst-class:: classref-enumeration-constant
|
||
|
||
:ref:`UnixPermissionFlags<enum_FileAccess_UnixPermissionFlags>` **UNIX_EXECUTE_OTHER** = ``1``
|
||
|
||
Выполнить для другого бита.
|
||
|
||
.. _class_FileAccess_constant_UNIX_SET_USER_ID:
|
||
|
||
.. rst-class:: classref-enumeration-constant
|
||
|
||
:ref:`UnixPermissionFlags<enum_FileAccess_UnixPermissionFlags>` **UNIX_SET_USER_ID** = ``2048``
|
||
|
||
Установить идентификатор пользователя при выполнении бита.
|
||
|
||
.. _class_FileAccess_constant_UNIX_SET_GROUP_ID:
|
||
|
||
.. rst-class:: classref-enumeration-constant
|
||
|
||
:ref:`UnixPermissionFlags<enum_FileAccess_UnixPermissionFlags>` **UNIX_SET_GROUP_ID** = ``1024``
|
||
|
||
Установить идентификатор группы при выполнении бита.
|
||
|
||
.. _class_FileAccess_constant_UNIX_RESTRICTED_DELETE:
|
||
|
||
.. rst-class:: classref-enumeration-constant
|
||
|
||
:ref:`UnixPermissionFlags<enum_FileAccess_UnixPermissionFlags>` **UNIX_RESTRICTED_DELETE** = ``512``
|
||
|
||
Бит ограниченного удаления (прикрепленный).
|
||
|
||
.. rst-class:: classref-section-separator
|
||
|
||
----
|
||
|
||
.. rst-class:: classref-descriptions-group
|
||
|
||
Описания свойств
|
||
--------------------------------
|
||
|
||
.. _class_FileAccess_property_big_endian:
|
||
|
||
.. rst-class:: classref-property
|
||
|
||
:ref:`bool<class_bool>` **big_endian** :ref:`🔗<class_FileAccess_property_big_endian>`
|
||
|
||
.. rst-class:: classref-property-setget
|
||
|
||
- |void| **set_big_endian**\ (\ value\: :ref:`bool<class_bool>`\ )
|
||
- :ref:`bool<class_bool>` **is_big_endian**\ (\ )
|
||
|
||
Если ``true``, файл читается с big-endian `порядком байтов <https://en.wikipedia.org/wiki/Endianness>`__. Если ``false``, файл читается с little-endian порядком байтов. Если сомневаетесь, оставьте это ``false``, так как большинство файлов записываются с little-endian порядком байтов.
|
||
|
||
\ **Примечание:** Это всегда сбрасывается на системный порядок байтов, который является little-endian на всех поддерживаемых платформах, всякий раз, когда вы открываете файл. Поэтому вы должны установить :ref:`big_endian<class_FileAccess_property_big_endian>` *после* открытия файла, а не до.
|
||
|
||
.. rst-class:: classref-section-separator
|
||
|
||
----
|
||
|
||
.. rst-class:: classref-descriptions-group
|
||
|
||
Описания метода
|
||
------------------------------
|
||
|
||
.. _class_FileAccess_method_close:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
|void| **close**\ (\ ) :ref:`🔗<class_FileAccess_method_close>`
|
||
|
||
Закрывает текущий открытый файл и предотвращает последующие операции чтения/записи. Используйте :ref:`flush()<class_FileAccess_method_flush>`, чтобы сохранить данные на диске без закрытия файла.
|
||
|
||
\ **Примечание:** **FileAccess** автоматически закроется при освобождении, что происходит, когда он выходит из области действия или когда ему присваивается ``null``. В C# ссылка должна быть удалена после того, как мы закончим ее использовать, это можно сделать с помощью оператора ``using`` или вызова метода ``Dispose`` напрямую.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_create_temp:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`FileAccess<class_FileAccess>` **create_temp**\ (\ mode_flags\: :ref:`int<class_int>`, prefix\: :ref:`String<class_String>` = "", extension\: :ref:`String<class_String>` = "", keep\: :ref:`bool<class_bool>` = false\ ) |static| :ref:`🔗<class_FileAccess_method_create_temp>`
|
||
|
||
Создает временный файл. Этот файл будет освобожден при освобождении возвращенного **FileAccess**.
|
||
|
||
Если ``prefix`` не пуст, он будет добавлен к имени файла, разделенному ``-``.
|
||
|
||
Если ``extension`` не пуст, он будет добавлен к имени временного файла.
|
||
|
||
Если ``keep`` равен ``true``, файл не удаляется при освобождении возвращенного **FileAccess**.
|
||
|
||
Возвращает ``null``, если открытие файла не удалось. Вы можете использовать :ref:`get_open_error()<class_FileAccess_method_get_open_error>`, чтобы проверить возникшую ошибку.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_eof_reached:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **eof_reached**\ (\ ) |const| :ref:`🔗<class_FileAccess_method_eof_reached>`
|
||
|
||
Возвращает ``true``, если файловый курсор уже прочитал за пределами конца файла.
|
||
|
||
\ **Примечание:** ``eof_reached() == false`` нельзя использовать для проверки наличия дополнительных данных. Чтобы выполнить цикл, пока есть дополнительные данные, используйте:
|
||
|
||
|
||
.. tabs::
|
||
|
||
.. code-tab:: gdscript
|
||
|
||
while file.get_position() < file.get_length():
|
||
# Read data
|
||
|
||
.. code-tab:: csharp
|
||
|
||
while (file.GetPosition() < file.GetLength())
|
||
{
|
||
// Read data
|
||
}
|
||
|
||
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_file_exists:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **file_exists**\ (\ path\: :ref:`String<class_String>`\ ) |static| :ref:`🔗<class_FileAccess_method_file_exists>`
|
||
|
||
Возвращает ``true``, если файл существует по указанному пути.
|
||
|
||
\ **Примечание:** Импортируются многие типы ресурсов (например, текстуры или звуковые файлы), и их исходный ресурс не будет включен в экспортированную игру, поскольку используется только импортированная версия. См. :ref:`ResourceLoader.exists()<class_ResourceLoader_method_exists>` для альтернативного подхода, который учитывает переназначение ресурсов.
|
||
|
||
Для нестатического, относительного эквивалента используйте :ref:`DirAccess.file_exists()<class_DirAccess_method_file_exists>`.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_flush:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
|void| **flush**\ (\ ) :ref:`🔗<class_FileAccess_method_flush>`
|
||
|
||
Записывает буфер файла на диск. Сброс выполняется автоматически при закрытии файла. Это означает, что вам не нужно вызывать :ref:`flush()<class_FileAccess_method_flush>` вручную перед закрытием файла. Тем не менее, вызов :ref:`flush()<class_FileAccess_method_flush>` может использоваться для обеспечения безопасности данных, даже если проект аварийно завершится, а не будет закрыт корректно.
|
||
|
||
\ **Примечание:** Вызывайте :ref:`flush()<class_FileAccess_method_flush>` только тогда, когда это действительно нужно. В противном случае это снизит производительность из-за постоянной записи на диск.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_8:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`int<class_int>` **get_8**\ (\ ) |const| :ref:`🔗<class_FileAccess_method_get_8>`
|
||
|
||
Возвращает следующие 8 бит из файла в виде целого числа. Это перемещает курсор файла на 1 байт. Подробнее о том, какие значения можно сохранять и извлекать таким способом, см. в :ref:`store_8()<class_FileAccess_method_store_8>`.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_16:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`int<class_int>` **get_16**\ (\ ) |const| :ref:`🔗<class_FileAccess_method_get_16>`
|
||
|
||
Возвращает следующие 16 бит из файла в виде целого числа. Это перемещает курсор файла на 2 байта вперёд. Подробнее о том, какие значения можно сохранять и извлекать таким способом, см. в :ref:`store_16()<class_FileAccess_method_store_16>`.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_32:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`int<class_int>` **get_32**\ (\ ) |const| :ref:`🔗<class_FileAccess_method_get_32>`
|
||
|
||
Возвращает следующие 32 бита из файла в виде целого числа. Это перемещает курсор файла на 4 байта вперёд. Подробнее о том, какие значения можно сохранять и извлекать таким способом, см. в :ref:`store_32()<class_FileAccess_method_store_32>`.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_64:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`int<class_int>` **get_64**\ (\ ) |const| :ref:`🔗<class_FileAccess_method_get_64>`
|
||
|
||
Возвращает следующие 64 бита из файла в виде целого числа. Это перемещает курсор файла на 8 байт. Подробнее о том, какие значения можно сохранять и извлекать таким способом, см. в :ref:`store_64()<class_FileAccess_method_store_64>`.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_access_time:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`int<class_int>` **get_access_time**\ (\ file\: :ref:`String<class_String>`\ ) |static| :ref:`🔗<class_FileAccess_method_get_access_time>`
|
||
|
||
Возвращает время последнего доступа к ``file`` в формате временной метки Unix или ``0`` при ошибке. Эту временную метку Unix можно преобразовать в другой формат с помощью синглтона :ref:`Time<class_Time>`.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_as_text:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`String<class_String>` **get_as_text**\ (\ ) |const| :ref:`🔗<class_FileAccess_method_get_as_text>`
|
||
|
||
Returns the whole file as a :ref:`String<class_String>`. Text is interpreted as being UTF-8 encoded. This ignores the file cursor and does not affect it.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_buffer:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`PackedByteArray<class_PackedByteArray>` **get_buffer**\ (\ length\: :ref:`int<class_int>`\ ) |const| :ref:`🔗<class_FileAccess_method_get_buffer>`
|
||
|
||
Возвращает следующие ``length`` байтов файла в виде :ref:`PackedByteArray<class_PackedByteArray>`. Это перемещает курсор файла на ``length`` байтов.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_csv_line:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`PackedStringArray<class_PackedStringArray>` **get_csv_line**\ (\ delim\: :ref:`String<class_String>` = ","\ ) |const| :ref:`🔗<class_FileAccess_method_get_csv_line>`
|
||
|
||
Возвращает следующее значение файла в формате CSV (значения, разделенные запятыми). Вы можете указать другой разделитель ``delim``, отличный от используемого по умолчанию ``","`` (запятая). Этот разделитель должен быть длиной в один символ и не может быть двойными кавычками.
|
||
|
||
Текст интерпретируется как текст в кодировке UTF-8. Текстовые значения должны быть заключены в двойные кавычки, если они содержат символ-разделитель. Двойные кавычки в текстовом значении можно экранировать, удваивая их вхождение. Это переместит курсор файла на позицию после символа новой строки в конце строки.
|
||
|
||
Например, следующие строки CSV-файла являются допустимыми и будут корректно обработаны как две строки каждая:
|
||
|
||
.. code:: text
|
||
|
||
Alice,"Hello, Bob!"
|
||
Bob,Alice! What a surprise!
|
||
Alice,"I thought you'd reply with ""Hello, world""."
|
||
|
||
Обратите внимание, что во второй строке можно опустить кавычки, поскольку она не содержит разделителя. Однако *можно* использовать кавычки, поскольку код был написан без них только в демонстрационных целях. В третьей строке необходимо использовать ``""`` для каждой кавычки, которая должна интерпретироваться как таковая, а не как конец текстового значения.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_double:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`float<class_float>` **get_double**\ (\ ) |const| :ref:`🔗<class_FileAccess_method_get_double>`
|
||
|
||
Возвращает следующие 64 бита файла в виде числа с плавающей запятой. Это перемещает курсор файла на 8 байт.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_error:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Error<enum_@GlobalScope_Error>` **get_error**\ (\ ) |const| :ref:`🔗<class_FileAccess_method_get_error>`
|
||
|
||
Возвращает последнюю ошибку, которая произошла при попытке выполнить операции. Сравните с константами ``ERR_FILE_*`` из :ref:`Error<enum_@GlobalScope_Error>`.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_extended_attribute:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`PackedByteArray<class_PackedByteArray>` **get_extended_attribute**\ (\ file\: :ref:`String<class_String>`, attribute_name\: :ref:`String<class_String>`\ ) |static| :ref:`🔗<class_FileAccess_method_get_extended_attribute>`
|
||
|
||
Reads the file extended attribute with name ``attribute_name`` as a byte array.
|
||
|
||
\ **Note:** This method is implemented on Linux, macOS, and Windows.
|
||
|
||
\ **Note:** Extended attributes support depends on the file system. Attributes will be lost when the file is moved between incompatible file systems.
|
||
|
||
\ **Note:** On Linux, only "user" namespace attributes are accessible, namespace prefix should not be included.
|
||
|
||
\ **Note:** On Windows, alternate data streams are used to store extended attributes.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_extended_attribute_string:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`String<class_String>` **get_extended_attribute_string**\ (\ file\: :ref:`String<class_String>`, attribute_name\: :ref:`String<class_String>`\ ) |static| :ref:`🔗<class_FileAccess_method_get_extended_attribute_string>`
|
||
|
||
Reads the file extended attribute with name ``attribute_name`` as a UTF-8 encoded string.
|
||
|
||
\ **Note:** This method is implemented on Linux, macOS, and Windows.
|
||
|
||
\ **Note:** Extended attributes support depends on the file system. Attributes will be lost when the file is moved between incompatible file systems.
|
||
|
||
\ **Note:** On Linux, only "user" namespace attributes are accessible, namespace prefix should not be included.
|
||
|
||
\ **Note:** On Windows, alternate data streams are used to store extended attributes.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_extended_attributes_list:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`PackedStringArray<class_PackedStringArray>` **get_extended_attributes_list**\ (\ file\: :ref:`String<class_String>`\ ) |static| :ref:`🔗<class_FileAccess_method_get_extended_attributes_list>`
|
||
|
||
Returns a list of file extended attributes.
|
||
|
||
\ **Note:** This method is implemented on Linux, macOS, and Windows.
|
||
|
||
\ **Note:** Extended attributes support depends on the file system. Attributes will be lost when the file is moved between incompatible file systems.
|
||
|
||
\ **Note:** On Linux, only "user" namespace attributes are accessible, namespace prefix should not be included.
|
||
|
||
\ **Note:** On Windows, alternate data streams are used to store extended attributes.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_file_as_bytes:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`PackedByteArray<class_PackedByteArray>` **get_file_as_bytes**\ (\ path\: :ref:`String<class_String>`\ ) |static| :ref:`🔗<class_FileAccess_method_get_file_as_bytes>`
|
||
|
||
Возвращает все содержимое файла ``path`` как :ref:`PackedByteArray<class_PackedByteArray>` без какого-либо декодирования.
|
||
|
||
Возвращает пустой :ref:`PackedByteArray<class_PackedByteArray>`, если при открытии файла произошла ошибка. Вы можете использовать :ref:`get_open_error()<class_FileAccess_method_get_open_error>`, чтобы проверить возникшую ошибку.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_file_as_string:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`String<class_String>` **get_file_as_string**\ (\ path\: :ref:`String<class_String>`\ ) |static| :ref:`🔗<class_FileAccess_method_get_file_as_string>`
|
||
|
||
Возвращает все содержимое файла ``path`` как :ref:`String<class_String>`. Текст интерпретируется как закодированный в UTF-8.
|
||
|
||
Возвращает пустую :ref:`String<class_String>`, если при открытии файла произошла ошибка. Вы можете использовать :ref:`get_open_error()<class_FileAccess_method_get_open_error>`, чтобы проверить произошедшую ошибку.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_float:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`float<class_float>` **get_float**\ (\ ) |const| :ref:`🔗<class_FileAccess_method_get_float>`
|
||
|
||
Возвращает следующие 32 бита файла в виде числа с плавающей запятой. Это перемещает курсор файла на 4 байта вперёд.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_half:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`float<class_float>` **get_half**\ (\ ) |const| :ref:`🔗<class_FileAccess_method_get_half>`
|
||
|
||
Возвращает следующие 16 бит из файла как число с плавающей запятой половинной точности. Это перемещает курсор файла на 2 байта вперёд.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_hidden_attribute:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **get_hidden_attribute**\ (\ file\: :ref:`String<class_String>`\ ) |static| :ref:`🔗<class_FileAccess_method_get_hidden_attribute>`
|
||
|
||
Returns ``true`` if the **hidden** attribute is set on the file at the given path.
|
||
|
||
\ **Note:** This method is implemented on iOS, BSD, macOS, and Windows.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_length:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`int<class_int>` **get_length**\ (\ ) |const| :ref:`🔗<class_FileAccess_method_get_length>`
|
||
|
||
Возвращает размер файла в байтах. Для канала возвращает количество байтов, доступных для чтения из канала.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_line:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`String<class_String>` **get_line**\ (\ ) |const| :ref:`🔗<class_FileAccess_method_get_line>`
|
||
|
||
Возвращает следующую строку файла как :ref:`String<class_String>`. Возвращаемая строка не содержит символов перевода строки (``\n``) или возврата каретки (``\r``), но содержит любые другие начальные или конечные пробелы. Это перемещает файловый курсор в положение после символа перевода строки в конце строки.
|
||
|
||
Текст интерпретируется как текст в кодировке UTF-8.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_md5:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`String<class_String>` **get_md5**\ (\ path\: :ref:`String<class_String>`\ ) |static| :ref:`🔗<class_FileAccess_method_get_md5>`
|
||
|
||
Возвращает строку MD5, представляющую файл по указанному пути, или пустую :ref:`String<class_String>` в случае возникновения ошибки.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_modified_time:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`int<class_int>` **get_modified_time**\ (\ file\: :ref:`String<class_String>`\ ) |static| :ref:`🔗<class_FileAccess_method_get_modified_time>`
|
||
|
||
Возвращает время последнего изменения ``file`` в формате временной метки Unix или ``0`` в случае ошибки. Эту временную метку Unix можно преобразовать в другой формат с помощью синглтона :ref:`Time<class_Time>`.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_open_error:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Error<enum_@GlobalScope_Error>` **get_open_error**\ (\ ) |static| :ref:`🔗<class_FileAccess_method_get_open_error>`
|
||
|
||
Возвращает результат последнего вызова :ref:`open()<class_FileAccess_method_open>` в текущем потоке.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_pascal_string:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`String<class_String>` **get_pascal_string**\ (\ ) :ref:`🔗<class_FileAccess_method_get_pascal_string>`
|
||
|
||
Возвращает :ref:`String<class_String>`, сохранённую в формате Pascal из файла. Это означает, что длина строки явно сохраняется в начале. См. :ref:`store_pascal_string()<class_FileAccess_method_store_pascal_string>`. Она может включать символы новой строки. Курсор файла перемещается после считывания байтов.
|
||
|
||
Текст интерпретируется как имеющий кодировку UTF-8.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_path:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`String<class_String>` **get_path**\ (\ ) |const| :ref:`🔗<class_FileAccess_method_get_path>`
|
||
|
||
Возвращает путь в виде :ref:`String<class_String>` для текущего открытого файла.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_path_absolute:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`String<class_String>` **get_path_absolute**\ (\ ) |const| :ref:`🔗<class_FileAccess_method_get_path_absolute>`
|
||
|
||
Возвращает абсолютный путь в виде :ref:`String<class_String>` для текущего открытого файла.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_position:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`int<class_int>` **get_position**\ (\ ) |const| :ref:`🔗<class_FileAccess_method_get_position>`
|
||
|
||
Возвращает позицию файлового курсора в байтах от начала файла. Это файловый курсор чтения/записи, установленный методом :ref:`seek()<class_FileAccess_method_seek>` или :ref:`seek_end()<class_FileAccess_method_seek_end>` и перемещаемый операциями чтения/записи.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_read_only_attribute:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **get_read_only_attribute**\ (\ file\: :ref:`String<class_String>`\ ) |static| :ref:`🔗<class_FileAccess_method_get_read_only_attribute>`
|
||
|
||
Returns ``true`` if the **read only** attribute is set on the file at the given path.
|
||
|
||
\ **Note:** This method is implemented on iOS, BSD, macOS, and Windows.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_real:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`float<class_float>` **get_real**\ (\ ) |const| :ref:`🔗<class_FileAccess_method_get_real>`
|
||
|
||
Возвращает следующие биты из файла в виде числа с плавающей точкой. Это перемещает файловый курсор на 4 или 8 байтов, в зависимости от точности, используемой сборкой Godot, сохранившей файл.
|
||
|
||
Если файл был сохранён сборкой Godot, скомпилированной с опцией ``precision=single`` (по умолчанию), количество считанных битов для этого файла равно 32. В противном случае, если файл скомпилирован с опцией ``precision=double``, количество считанных битов равно 64.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_sha256:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`String<class_String>` **get_sha256**\ (\ path\: :ref:`String<class_String>`\ ) |static| :ref:`🔗<class_FileAccess_method_get_sha256>`
|
||
|
||
Возвращает SHA-256 :ref:`String<class_String>`, представляющую файл по указанному пути, или пустую :ref:`String<class_String>` в случае возникновения ошибки.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_size:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`int<class_int>` **get_size**\ (\ file\: :ref:`String<class_String>`\ ) |static| :ref:`🔗<class_FileAccess_method_get_size>`
|
||
|
||
Returns the size of the file at the given path, in bytes, or ``-1`` on error.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_unix_permissions:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
|bitfield|\[:ref:`UnixPermissionFlags<enum_FileAccess_UnixPermissionFlags>`\] **get_unix_permissions**\ (\ file\: :ref:`String<class_String>`\ ) |static| :ref:`🔗<class_FileAccess_method_get_unix_permissions>`
|
||
|
||
Returns the UNIX permissions of the file at the given path.
|
||
|
||
\ **Note:** This method is implemented on iOS, Linux/BSD, and macOS.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_get_var:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Variant<class_Variant>` **get_var**\ (\ allow_objects\: :ref:`bool<class_bool>` = false\ ) |const| :ref:`🔗<class_FileAccess_method_get_var>`
|
||
|
||
Возвращает следующее значение :ref:`Variant<class_Variant>` из файла. Если ``allow_objects`` равен ``true``, декодирование объектов разрешено. Это перемещает файловый курсор на количество прочитанных байтов.
|
||
|
||
Внутри используется тот же механизм декодирования, что и метод :ref:`@GlobalScope.bytes_to_var()<class_@GlobalScope_method_bytes_to_var>`, описанный в документации :doc:`API двоичной сериализации <../tutorials/io/binary_serialization_api>`.
|
||
|
||
\ **Предупреждение:** Десериализованные объекты могут содержать код, который будет выполнен. Не используйте этот параметр, если сериализованный объект получен из ненадежных источников, чтобы избежать потенциальных угроз безопасности, таких как удалённое выполнение кода.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_is_open:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **is_open**\ (\ ) |const| :ref:`🔗<class_FileAccess_method_is_open>`
|
||
|
||
Возвращает ``true``, если файл в данный момент открыт.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_open:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`FileAccess<class_FileAccess>` **open**\ (\ path\: :ref:`String<class_String>`, flags\: :ref:`ModeFlags<enum_FileAccess_ModeFlags>`\ ) |static| :ref:`🔗<class_FileAccess_method_open>`
|
||
|
||
Создает новый объект **FileAccess** и открывает файл для записи или чтения в зависимости от флагов.
|
||
|
||
Возвращает ``null``, если открытие файла не удалось. Вы можете использовать :ref:`get_open_error()<class_FileAccess_method_get_open_error>`, чтобы проверить возникшую ошибку.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_open_compressed:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`FileAccess<class_FileAccess>` **open_compressed**\ (\ path\: :ref:`String<class_String>`, mode_flags\: :ref:`ModeFlags<enum_FileAccess_ModeFlags>`, compression_mode\: :ref:`CompressionMode<enum_FileAccess_CompressionMode>` = 0\ ) |static| :ref:`🔗<class_FileAccess_method_open_compressed>`
|
||
|
||
Создает новый объект **FileAccess** и открывает сжатый файл для чтения или записи.
|
||
|
||
\ **Примечание:** :ref:`open_compressed()<class_FileAccess_method_open_compressed>` может читать только файлы, сохраненные Godot, а не сторонние форматы сжатия. См. `проблему GitHub № 28999 <https://github.com/godotengine/godot/issues/28999>`__ для обходного пути.
|
||
|
||
Возвращает ``null``, если открытие файла не удалось. Вы можете использовать :ref:`get_open_error()<class_FileAccess_method_get_open_error>`, чтобы проверить возникшую ошибку.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_open_encrypted:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`FileAccess<class_FileAccess>` **open_encrypted**\ (\ path\: :ref:`String<class_String>`, mode_flags\: :ref:`ModeFlags<enum_FileAccess_ModeFlags>`, key\: :ref:`PackedByteArray<class_PackedByteArray>`, iv\: :ref:`PackedByteArray<class_PackedByteArray>` = PackedByteArray()\ ) |static| :ref:`🔗<class_FileAccess_method_open_encrypted>`
|
||
|
||
Создает новый объект **FileAccess** и открывает зашифрованный файл в режиме записи или чтения. Вам необходимо передать двоичный ключ для его шифрования/расшифровки.
|
||
|
||
\ **Примечание:** Предоставленный ключ должен быть длиной 32 байта.
|
||
|
||
Возвращает ``null``, если открытие файла не удалось. Вы можете использовать :ref:`get_open_error()<class_FileAccess_method_get_open_error>`, чтобы проверить возникшую ошибку.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_open_encrypted_with_pass:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`FileAccess<class_FileAccess>` **open_encrypted_with_pass**\ (\ path\: :ref:`String<class_String>`, mode_flags\: :ref:`ModeFlags<enum_FileAccess_ModeFlags>`, pass\: :ref:`String<class_String>`\ ) |static| :ref:`🔗<class_FileAccess_method_open_encrypted_with_pass>`
|
||
|
||
Создает новый объект **FileAccess** и открывает зашифрованный файл в режиме записи или чтения. Вам необходимо передать пароль для его шифрования/расшифровки.
|
||
|
||
Возвращает ``null``, если открытие файла не удалось. Вы можете использовать :ref:`get_open_error()<class_FileAccess_method_get_open_error>`, чтобы проверить возникшую ошибку.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_remove_extended_attribute:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Error<enum_@GlobalScope_Error>` **remove_extended_attribute**\ (\ file\: :ref:`String<class_String>`, attribute_name\: :ref:`String<class_String>`\ ) |static| :ref:`🔗<class_FileAccess_method_remove_extended_attribute>`
|
||
|
||
Removes file extended attribute with name ``attribute_name``.
|
||
|
||
\ **Note:** This method is implemented on Linux, macOS, and Windows.
|
||
|
||
\ **Note:** Extended attributes support depends on the file system. Attributes will be lost when the file is moved between incompatible file systems.
|
||
|
||
\ **Note:** On Linux, only "user" namespace attributes are accessible, namespace prefix should not be included.
|
||
|
||
\ **Note:** On Windows, alternate data streams are used to store extended attributes.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_resize:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Error<enum_@GlobalScope_Error>` **resize**\ (\ length\: :ref:`int<class_int>`\ ) :ref:`🔗<class_FileAccess_method_resize>`
|
||
|
||
Изменяет размер файла до указанной длины. Файл должен быть открыт в режиме, разрешающем запись. Если файл расширен, добавляются символы NUL. Если файл усечен, все данные от конечного файла до исходной длины файла теряются.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_seek:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
|void| **seek**\ (\ position\: :ref:`int<class_int>`\ ) :ref:`🔗<class_FileAccess_method_seek>`
|
||
|
||
Sets the file cursor to the specified position in bytes, from the beginning of the file. This changes the value returned by :ref:`get_position()<class_FileAccess_method_get_position>`.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_seek_end:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
|void| **seek_end**\ (\ position\: :ref:`int<class_int>` = 0\ ) :ref:`🔗<class_FileAccess_method_seek_end>`
|
||
|
||
Sets the file cursor to the specified position in bytes, from the end of the file. This changes the value returned by :ref:`get_position()<class_FileAccess_method_get_position>`.
|
||
|
||
\ **Note:** This is an offset, so you should use negative numbers otherwise the file cursor will be at the end of the file.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_set_extended_attribute:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Error<enum_@GlobalScope_Error>` **set_extended_attribute**\ (\ file\: :ref:`String<class_String>`, attribute_name\: :ref:`String<class_String>`, data\: :ref:`PackedByteArray<class_PackedByteArray>`\ ) |static| :ref:`🔗<class_FileAccess_method_set_extended_attribute>`
|
||
|
||
Writes file extended attribute with name ``attribute_name`` as a byte array.
|
||
|
||
\ **Note:** This method is implemented on Linux, macOS, and Windows.
|
||
|
||
\ **Note:** Extended attributes support depends on the file system. Attributes will be lost when the file is moved between incompatible file systems.
|
||
|
||
\ **Note:** On Linux, only "user" namespace attributes are accessible, namespace prefix should not be included.
|
||
|
||
\ **Note:** On Windows, alternate data streams are used to store extended attributes.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_set_extended_attribute_string:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Error<enum_@GlobalScope_Error>` **set_extended_attribute_string**\ (\ file\: :ref:`String<class_String>`, attribute_name\: :ref:`String<class_String>`, data\: :ref:`String<class_String>`\ ) |static| :ref:`🔗<class_FileAccess_method_set_extended_attribute_string>`
|
||
|
||
Writes file extended attribute with name ``attribute_name`` as a UTF-8 encoded string.
|
||
|
||
\ **Note:** This method is implemented on Linux, macOS, and Windows.
|
||
|
||
\ **Note:** Extended attributes support depends on the file system. Attributes will be lost when the file is moved between incompatible file systems.
|
||
|
||
\ **Note:** On Linux, only "user" namespace attributes are accessible, namespace prefix should not be included.
|
||
|
||
\ **Note:** On Windows, alternate data streams are used to store extended attributes.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_set_hidden_attribute:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Error<enum_@GlobalScope_Error>` **set_hidden_attribute**\ (\ file\: :ref:`String<class_String>`, hidden\: :ref:`bool<class_bool>`\ ) |static| :ref:`🔗<class_FileAccess_method_set_hidden_attribute>`
|
||
|
||
Устанавливает атрибут файла **hidden**.
|
||
|
||
\ **Примечание:** Этот метод реализован в iOS, BSD, macOS и Windows.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_set_read_only_attribute:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Error<enum_@GlobalScope_Error>` **set_read_only_attribute**\ (\ file\: :ref:`String<class_String>`, ro\: :ref:`bool<class_bool>`\ ) |static| :ref:`🔗<class_FileAccess_method_set_read_only_attribute>`
|
||
|
||
Устанавливает атрибут файла **read only**.
|
||
|
||
\ **Примечание:** Этот метод реализован в iOS, BSD, macOS и Windows.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_set_unix_permissions:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Error<enum_@GlobalScope_Error>` **set_unix_permissions**\ (\ file\: :ref:`String<class_String>`, permissions\: |bitfield|\[:ref:`UnixPermissionFlags<enum_FileAccess_UnixPermissionFlags>`\]\ ) |static| :ref:`🔗<class_FileAccess_method_set_unix_permissions>`
|
||
|
||
Устанавливает права доступа UNIX к файлам.
|
||
|
||
\ **Примечание:** Этот метод реализован в iOS, Linux/BSD и macOS.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_store_8:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **store_8**\ (\ value\: :ref:`int<class_int>`\ ) :ref:`🔗<class_FileAccess_method_store_8>`
|
||
|
||
Сохраняет целое число в файле в виде 8 бит. Это перемещает курсор файла на 1 байт. Возвращает ``true`` в случае успешного выполнения операции.
|
||
|
||
\ **Примечание:** Значение ``value`` должно находиться в интервале ``[0, 255]``. Любое другое значение приведёт к переполнению и циклическому переносу.
|
||
|
||
\ **Примечание:** В случае ошибки результирующее значение индикатора позиции файла не определено.
|
||
|
||
Чтобы сохранить знаковое целое число, используйте :ref:`store_64()<class_FileAccess_method_store_64>` или преобразуйте его вручную (см. пример в :ref:`store_16()<class_FileAccess_method_store_16>`).
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_store_16:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **store_16**\ (\ value\: :ref:`int<class_int>`\ ) :ref:`🔗<class_FileAccess_method_store_16>`
|
||
|
||
Сохраняет целое число в файле в виде 16 бит. Это перемещает файловый курсор на 2 байта вперёд. Возвращает ``true`` в случае успешного выполнения операции.
|
||
|
||
\ **Примечание:** Значение ``value`` должно находиться в интервале ``[0, 2^16 - 1]``. Любое другое значение приведёт к переполнению и циклическому переносу.
|
||
|
||
\ **Примечание:** В случае ошибки результирующее значение индикатора позиции файла не определено.
|
||
|
||
Для сохранения знакового целого числа используйте :ref:`store_64()<class_FileAccess_method_store_64>` или сохраните знаковое целое число из интервала ``[-2^15, 2^15 - 1]`` (т.е. сохранив один бит для знака) и вручную вычисляйте его знак при чтении. Например:
|
||
|
||
|
||
.. tabs::
|
||
|
||
.. code-tab:: gdscript
|
||
|
||
const MAX_15B = 1 << 15
|
||
const MAX_16B = 1 << 16
|
||
|
||
func unsigned16_to_signed(unsigned):
|
||
return (unsigned + MAX_15B) % MAX_16B - MAX_15B
|
||
|
||
func _ready():
|
||
var f = FileAccess.open("user://file.dat", FileAccess.WRITE_READ)
|
||
f.store_16(-42) # Это округляет и сохраняет 65494 (2^16 - 42).
|
||
f.store_16(121) # В пределах границ будет храниться 121.
|
||
f.seek(0) # Вернитесь в начало, чтобы прочитать сохраненное значение.
|
||
var read1 = f.get_16() # 65494
|
||
var read2 = f.get_16() # 121
|
||
var converted1 = unsigned16_to_signed(read1) # -42
|
||
var converted2 = unsigned16_to_signed(read2) # 121
|
||
|
||
.. code-tab:: csharp
|
||
|
||
public override void _Ready()
|
||
{
|
||
using var f = FileAccess.Open("user://file.dat", FileAccess.ModeFlags.WriteRead);
|
||
f.Store16(unchecked((ushort)-42)); // Это округляет и сохраняет 65494 (2^16 - 42).
|
||
f.Store16(121); // В пределах границ будет храниться 121.
|
||
f.Seek(0); // Вернитесь в начало, чтобы прочитать сохраненное значение.
|
||
ushort read1 = f.Get16(); // 65494
|
||
ushort read2 = f.Get16(); // 121
|
||
short converted1 = (short)read1; // -42
|
||
short converted2 = (short)read2; // 121
|
||
}
|
||
|
||
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_store_32:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **store_32**\ (\ value\: :ref:`int<class_int>`\ ) :ref:`🔗<class_FileAccess_method_store_32>`
|
||
|
||
Сохраняет целое число в файле в виде 32 бит. Это перемещает файловый курсор на 4 байта. Возвращает ``true`` в случае успешного выполнения операции.
|
||
|
||
\ **Примечание:** Значение ``value`` должно находиться в интервале ``[0, 2^32 - 1]``. Любое другое значение приведёт к переполнению и циклическому переносу.
|
||
|
||
\ **Примечание:** В случае ошибки результирующее значение индикатора позиции файла не определено.
|
||
|
||
Чтобы сохранить знаковое целое число, используйте :ref:`store_64()<class_FileAccess_method_store_64>` или преобразуйте его вручную (см. пример в :ref:`store_16()<class_FileAccess_method_store_16>`).
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_store_64:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **store_64**\ (\ value\: :ref:`int<class_int>`\ ) :ref:`🔗<class_FileAccess_method_store_64>`
|
||
|
||
Сохраняет целое число в файле в виде 64 бит. Это перемещает файловый курсор на 8 байт. Возвращает ``true`` в случае успешного выполнения операции.
|
||
|
||
\ **Примечание:** Значение ``value`` должно находиться в интервале ``[-2^63, 2^63 - 1]`` (т.е. быть допустимым значением :ref:`int<class_int>`).
|
||
|
||
\ **Примечание:** В случае ошибки результирующее значение индикатора позиции файла не определено.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_store_buffer:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **store_buffer**\ (\ buffer\: :ref:`PackedByteArray<class_PackedByteArray>`\ ) :ref:`🔗<class_FileAccess_method_store_buffer>`
|
||
|
||
Сохраняет заданный массив байтов в файле. Это перемещает файловый курсор на количество записанных байтов. Возвращает ``true`` в случае успешного выполнения операции.
|
||
|
||
\ **Примечание:** В случае ошибки результирующее значение индикатора позиции файла не определено.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_store_csv_line:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **store_csv_line**\ (\ values\: :ref:`PackedStringArray<class_PackedStringArray>`, delim\: :ref:`String<class_String>` = ","\ ) :ref:`🔗<class_FileAccess_method_store_csv_line>`
|
||
|
||
Stores the given :ref:`PackedStringArray<class_PackedStringArray>` in the file as a line formatted in the CSV (Comma-Separated Values) format. You can pass a different delimiter ``delim`` to use other than the default ``","`` (comma). This delimiter must be one-character long.
|
||
|
||
Text will be encoded as UTF-8. Returns ``true`` if the operation is successful.
|
||
|
||
\ **Note:** If an error occurs, the resulting value of the file position indicator is indeterminate.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_store_double:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **store_double**\ (\ value\: :ref:`float<class_float>`\ ) :ref:`🔗<class_FileAccess_method_store_double>`
|
||
|
||
Сохраняет число с плавающей запятой в файле в виде 64 бит. Это перемещает файловый курсор на 8 байт. Возвращает ``true`` в случае успешного выполнения операции.
|
||
|
||
\ **Примечание:** В случае ошибки результирующее значение индикатора позиции файла не определено.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_store_float:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **store_float**\ (\ value\: :ref:`float<class_float>`\ ) :ref:`🔗<class_FileAccess_method_store_float>`
|
||
|
||
Сохраняет число с плавающей запятой в файле в виде 32 бит. Это перемещает файловый курсор на 4 байта. Возвращает ``true`` в случае успешного выполнения операции.
|
||
|
||
\ **Примечание:** В случае ошибки результирующее значение индикатора позиции файла не определено.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_store_half:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **store_half**\ (\ value\: :ref:`float<class_float>`\ ) :ref:`🔗<class_FileAccess_method_store_half>`
|
||
|
||
Сохраняет в файле число с плавающей запятой половинной точности (half-precision) в виде 16 бит. Это перемещает файловый курсор на 2 байта. Возвращает ``true`` в случае успешного выполнения операции.
|
||
|
||
\ **Примечание:** В случае ошибки результирующее значение индикатора позиции файла не определено.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_store_line:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **store_line**\ (\ line\: :ref:`String<class_String>`\ ) :ref:`🔗<class_FileAccess_method_store_line>`
|
||
|
||
Сохраняет в файле ``line``, за которым следует символ новой строки (``\n``), кодируя текст в формате UTF-8. Это перемещает файловый курсор на длину строки после символа новой строки. Количество записанных байтов зависит от количества байтов в кодировке UTF-8, которое может отличаться от :ref:`String.length()<class_String_method_length>`, который подсчитывает количество кодовых точек UTF-32. Возвращает ``true`` в случае успешного выполнения операции.
|
||
|
||
\ **Примечание:** В случае ошибки результирующее значение индикатора позиции файла не определено.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_store_pascal_string:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **store_pascal_string**\ (\ string\: :ref:`String<class_String>`\ ) :ref:`🔗<class_FileAccess_method_store_pascal_string>`
|
||
|
||
Сохраняет заданную :ref:`String<class_String>` как строку в файле в формате Pascal (т.е. также сохраняет длину строки). Текст будет закодирован в UTF-8. Это перемещает файловый курсор на количество записанных байтов в зависимости от кодировки UTF-8, которая может отличаться от :ref:`String.length()<class_String_method_length>`, который подсчитывает количество кодовых точек UTF-32. Возвращает ``true`` в случае успешного выполнения операции.
|
||
|
||
\ **Примечание:** В случае ошибки результирующее значение индикатора позиции файла не определено.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_store_real:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **store_real**\ (\ value\: :ref:`float<class_float>`\ ) :ref:`🔗<class_FileAccess_method_store_real>`
|
||
|
||
Сохраняет число с плавающей точкой в файле. Это перемещает файловый курсор на 4 или 8 байтов, в зависимости от точности, используемой текущей сборкой Godot.
|
||
|
||
Если используется сборка Godot, скомпилированная с опцией ``precision=single`` (по умолчанию), этот метод сохранит 32-битное число с плавающей точкой. В противном случае, если скомпилировано с опцией ``precision=double``, этот метод сохранит 64-битное число с плавающей точкой. Возвращает ``true`` в случае успешного выполнения операции.
|
||
|
||
\ **Примечание:** В случае ошибки результирующее значение индикатора позиции файла не определено.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_store_string:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **store_string**\ (\ string\: :ref:`String<class_String>`\ ) :ref:`🔗<class_FileAccess_method_store_string>`
|
||
|
||
Сохраняет ``string`` в файле без символа новой строки (``\n``), кодируя текст в формате UTF-8. Это перемещает курсор файла на длину строки в байтах в кодировке UTF-8, которая может отличаться от :ref:`String.length()<class_String_method_length>`, который подсчитывает количество кодовых точек UTF-32. Возвращает ``true`` в случае успешного выполнения операции.
|
||
|
||
\ **Примечание:** Этот метод предназначен для записи текстовых файлов. Строка хранится в виде буфера в кодировке UTF-8 без указания длины строки и завершающего нуля, что затрудняет её обратную загрузку. Если вы хотите сохранить извлекаемую строку в двоичном файле, рассмотрите возможность использования :ref:`store_pascal_string()<class_FileAccess_method_store_pascal_string>`. Для извлечения строк из текстового файла можно использовать метод ``get_buffer(length).get_string_from_utf8()`` (если известна длина) или :ref:`get_as_text()<class_FileAccess_method_get_as_text>`.
|
||
|
||
\ **Примечание:** В случае ошибки результирующее значение индикатора позиции файла не определено.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_FileAccess_method_store_var:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **store_var**\ (\ value\: :ref:`Variant<class_Variant>`, full_objects\: :ref:`bool<class_bool>` = false\ ) :ref:`🔗<class_FileAccess_method_store_var>`
|
||
|
||
Сохраняет любое значение Variant в файле. Если ``full_objects`` равен ``true``, кодирование объектов разрешено (и потенциально может включать код). Это перемещает курсор файла на количество записанных байтов. Возвращает ``true`` в случае успешного выполнения операции.
|
||
|
||
Внутри используется тот же механизм кодирования, что и метод :ref:`@GlobalScope.var_to_bytes()<class_@GlobalScope_method_var_to_bytes>`, как описано в документации :doc:`API двоичной сериализации <../tutorials/io/binary_serialization_api>`.
|
||
|
||
\ **Примечание:** Включены не все свойства. Сериализуются только свойства, настроенные с установленным флагом :ref:`@GlobalScope.PROPERTY_USAGE_STORAGE<class_@GlobalScope_constant_PROPERTY_USAGE_STORAGE>`. Вы можете добавить новый флаг использования к свойству, переопределив метод :ref:`Object._get_property_list()<class_Object_private_method__get_property_list>` в вашем классе. Вы также можете проверить, как настроено использование свойств, вызвав :ref:`Object._get_property_list()<class_Object_private_method__get_property_list>`. Возможные флаги использования см. в :ref:`PropertyUsageFlags<enum_@GlobalScope_PropertyUsageFlags>`.
|
||
|
||
\ **Примечание:** В случае ошибки результирующее значение индикатора положения файла не определено.
|
||
|
||
.. |virtual| replace:: :abbr:`virtual (Этот метод обычно должен быть переопределен пользователем, чтобы иметь какой-либо эффект.)`
|
||
.. |required| replace:: :abbr:`required (This method is required to be overridden when extending its base class.)`
|
||
.. |const| replace:: :abbr:`const (Этот метод не имеет побочных эффектов. Он не изменяет ни одну из переменных-членов экземпляра.)`
|
||
.. |vararg| replace:: :abbr:`vararg (Этот метод принимает любое количество аргументов после описанных здесь.)`
|
||
.. |constructor| replace:: :abbr:`constructor (Этот метод используется для создания типа.)`
|
||
.. |static| replace:: :abbr:`static (Этот метод не нуждается в вызове экземпляра, поэтому его можно вызвать напрямую, используя имя класса.)`
|
||
.. |operator| replace:: :abbr:`operator (Этот метод описывает допустимый оператор для использования с этим типом в качестве левого операнда.)`
|
||
.. |bitfield| replace:: :abbr:`BitField (Это значение является целым числом, составленным как битовая маска следующих флагов.)`
|
||
.. |void| replace:: :abbr:`void (Нет возвращаемого значения.)`
|