How to load text to android from res://

Godot Version

Godot 4.6.2 custom build

Question

Hello. I decided on a simple text download from res:// on Android. As far as I understand, there is no direct way to load a text file on Android. To do this, I used JSON, which is so simple. :

[gd_resource type=“JSON” format=3]

[resource]
data = “some text 10+ kb”

we load it using the function:

func get_text_privacy(conf_path : String) -> String:
	if !ResourceLoader.exists(conf_path):
		return conf_path + " no exists"
	var js = ResourceLoader.load(conf_path)
	if js == null:
		return conf_path + " file is empty"
	return js.get_data()

Everything works in the debug version. Release date - crashes when var js = ResourceLoader.load(conf_path) . What’s wrong. Or how can I download 10+ kb text from res:// to Android?

Make sure that *.json (or the file extension) files are exported in Exporting>Sources, then just use load(“config.json”). It is that simple, no need to use custom Resources.

If that doesn’t work, try FileAccess.

But, it is weird that it crashes. It seems like you have proper error handling. Maybe try to do it in a Thread if it is really a big file?

Here is an example I use to read text files. Returns error code + content to be processed later:

static func load_txt_file(file_path : String) → Dictionary:

#var file_path = "res://my_text_file.txt" # Replace with your file's path

if FileAccess.file_exists(file_path):
	var file = FileAccess.open(file_path, FileAccess.READ)
	if file:
		var content = file.get_as_text()
		#print("File content:\n", content)
		file.close() # Important to close the file
		return {"error" : 0, "content" : content}
	else:
		print("Error opening file: ", FileAccess.get_open_error())
		return {"error" : 2}
else:
	print("File does not exist: ", file_path)
	return {"error" : 1}

The files are exported. The thing is, when I export the debug version, everything works. And when the debug export is disabled, the game crashes. Godot itself does not issue any errors. Logcat points to /data/app/ru.krocknarock.mur-ALHV9D_D-mvZPVwYE56NMA==/lib/arm64/libgodot_android.so. I do not know what to do about it. Also, when the device crashes, it is suggested to send a report stating that the problem is with rendering or an infinite loop.

The main problem is that FileAccess does not work when loading from res:// on android. FileAccess.get_open_error() returns 0.

1 Like

Just a silly question, you are trying to open an existing file or creating a new one for writing on it?

Do you use custom build templates or the Godot ones? Are you sure the problem cannot be anything else, but the file loading?