這個例子主要是用來測試 File.browseForOpen 的功能
缺點還很多, 包含只能讀寫 utf-8 編碼的檔案
Flash frame actions:
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
var file:File;
var fs:FileStream;
var textFilter:FileFilter = new FileFilter("Text", "*.txt");
file = new File("app-resource:/temp.txt");
filename_txt.text = file.nativePath;
function bClick(e:MouseEvent):void {
var targetName:String = e.target.name;
switch (targetName) {
case "new_btn" :
file = new File("app-resource:/temp.txt");
filename_txt.text = file.nativePath;
main_txt.text = "";
break;
case "load_btn" :
file = new File();
file.browseForOpen("Open", [textFilter]);
file.addEventListener(Event.SELECT, onSelectOpenFile);
break;
case "save_btn" :
fs = new FileStream();
fs.open(file, FileMode.WRITE);
fs.writeMultiByte(main_txt.text, "utf-8");
fs.close();
break;
case "saveas_btn" :
file = new File();
file.browseForSave("Save as");
file.addEventListener(Event.SELECT, onSelectWriteFile);
break;
}
}
new_btn.addEventListener(MouseEvent.CLICK, bClick);
load_btn.addEventListener(MouseEvent.CLICK, bClick);
save_btn.addEventListener(MouseEvent.CLICK, bClick);
saveas_btn.addEventListener(MouseEvent.CLICK, bClick);
function onSelectOpenFile(e:Event) {
filename_txt.text = file.nativePath;
fs = new FileStream();
fs.open(file, FileMode.READ);
var str:String = fs.readMultiByte(fs.bytesAvailable, "utf-8");
// 替換 換行符號
main_txt.text = str.replace( new RegExp(File.lineEnding, "g"), "\n");
fs.close();
file.removeEventListener(Event.SELECT, onSelectOpenFile);
}
function onSelectWriteFile(e:Event) {
filename_txt.text = file.nativePath;
fs = new FileStream();
fs.open(file, FileMode.WRITE);
fs.writeMultiByte(main_txt.text, "utf-8");
fs.close();
file.removeEventListener(Event.SELECT, onSelectWriteFile);
}
原始檔: test_browseForOpen.fla
沒有留言:
張貼留言