我正在尝试将外部 txt 文件中的变量放入闪存中。文本文件如下所示:
[Settings]
AllowSetConflicts=1
[Hotkeys]
Music=F2
Sound=F6
PTT=
ChatAllies=Tab
等有没有办法让闪光灯识别换行符并过滤掉 [Settings] 之类的文本?
我正在尝试将外部 txt 文件中的变量放入闪存中。文本文件如下所示:
[Settings]
AllowSetConflicts=1
[Hotkeys]
Music=F2
Sound=F6
PTT=
ChatAllies=Tab
等有没有办法让闪光灯识别换行符并过滤掉 [Settings] 之类的文本?
如果可能的话,我建议您使用 XML 或 JSON 而不是您自己的格式,因为它更安全并且您不需要编写解析器。
动作脚本:
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.events.Event;
var textLoader:URLLoader = new URLLoader();
textLoader.addEventListener(Event.COMPLETE, textHandler);
textLoader.load(new URLRequest('txt.txt'));
function textHandler(e:Event):void{
var s:String = e.target.data;
var params:Array = s.split('\r');
trace(params[0].replace('\n',''));
trace(params[1].replace('\n',''));
}
var xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, xmlHandler);
xmlLoader.load(new URLRequest('xml.txt'));
function xmlHandler(e:Event):void{
var xml:XML = new XML(e.target.data);
trace(xml.settings.AllowSetConflicts);
}
txt.txt:
[Settings]
AllowSetConflicts=1
[Hotkeys]
Music=F2
Sound=F6
xml.txt:
<root>
<settings>
<AllowSetConflicts>
1
</AllowSetConflicts>
</settings>
</root>
我同意福克斯穿袜子的观点。事实上,有多少应用程序正在保存其设置(以 xml 格式)。
但是,如果您没有机会更改文件,这就是我要做的。
package {
import flash.display.Sprite;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.events.Event;
import flash.events.IOErrorEvent;
public class Main extends Sprite {
private var urlL:URLLoader;
private var props:Object = {};
// props will be assigned all the data from the txt file
private var file:String = 'file.txt';
public function Main() {
urlL = new URLLoader(new URLRequest(file));
urlL.addEventListener(Event.COMPLETE,processFile);
}
private function fileNotLoaded(e:IOErrorEvent):void {
trace(file, 'could not be loaded');
}
private function processFile(e:Event):void {
var str:String = urlL.data.toString();
var ref:Object, prop:String, val:*;
var lines:Array = str.split(/\r\n?|\n/g);
for (var i:int = 0; i < lines.length; i++) {
// if it's an empty line...
if (/^\s*$/.test(lines[i])) continue;
// if it's a category line...
if (/^\[.+?\]$/.test(lines[i])) {
ref = props[lines[i].replace(/^.(.+?).$/,'$1')] = {};
// if it's a variable-value pair line...
} else if (/^[^\r\n]+=[^\r\n]*$/.test(lines[i])) {
prop = lines[i].split('=')[0];
val = detectType(lines[i].substr(prop.length+1));
ref[prop] = val;
}
}
}
private function detectType(s:String):* {
// this is an optional function to convert strings
// with basic data types into appropriate class instances
if (s == 'null') return null;
if (/^(\d+|(\d+)?\.\d+)$/.test(s)) return Number(s);
if (/^true$/.test(s)) return true;
if (/^false$/.test(s)) return false;
return s;
}
}
}