Displaying text from a text file - how to make "\n" work?


Building to an openfl windows/mac target:

I want to read in text from a file so I can create different localizations. However, when I try to do this, text formatting does not work as I expected. I provide a simplified example below:


import openfl.display.Sprite;
import openfl.Lib;

//for display
import openfl.text.TextField;
import openfl.text.TextFieldType;
import openfl.text.TextFormat;
import openfl.text.TextFormatAlign;

//for file system operations (read/write files)
import sys.io.File;
import sys.FileSystem;

class Main extends Sprite 
	public var messageFieldHardCoded:	 TextField = null;
	public var messageFieldFromTextFile: TextField = null;
	public function new() 
		//set up a quick on screen display
		messageFieldHardCoded = new TextField();
		messageFieldFromTextFile = new TextField();
		var messageFormat = new TextFormat("assets/helvetica.ttf",30, 0xFFFFFF, true);
		messageFormat.align = TextFormatAlign.CENTER;
		messageFieldHardCoded.defaultTextFormat = messageFormat;
		messageFieldFromTextFile.defaultTextFormat = messageFormat;
		//hard code text for first message field
		messageFieldHardCoded.text = "This text is hard coded\nand appears over two lines";
		//import text from .txt file for second message field
		var localeFile = File.read("test.txt", false); 
		var str = localeFile.readLine();
		messageFieldFromTextFile.text = str;
		//display the message fields...
		messageFieldHardCoded.x = 0;
		messageFieldHardCoded.y = 0;
		messageFieldHardCoded.width = stage.stageWidth;
		messageFieldFromTextFile.x = 0;
		messageFieldFromTextFile.y = 100;
		messageFieldFromTextFile.width = stage.stageWidth;

This gives:

What am I missing that will allow the \n to be interpreted correctly and create a new line?



Are you using literal \n in your text file? If so, you currently have two characters \ and n, and you have to replace it with a single newline character, for example like this:

using StringTools;
messageFieldFromTextFile.text = str.replace('\\n', '\n');
1 Like


Yes, that’s quite right, and your solution has worked perfectly, thanks!

For future reference:
StringTools.replace(messageFieldFromTextFile.text,'\\n', '\n');



I used the static extension access method, but yours is correct as well.