ファイルのオープン/クローズ
前回はFileオブジェクトを使ってファイルのコピーや削除といった操作を行いました。AIRアプリケーションは、
読み書きの対象となるファイルは、
open()メソッドとopenAsync()メソッドは、
FileMode. | 読み込み専用。 |
FileMode. | 書き込み専用。ファイルは常に上書きされる。ファイルが存在しなければオープン時に作成される。 |
FileMode. | 書き込み専用。データは常にファイル末尾に追記される。ファイルが存在しなければオープン時に作成される。 |
FileMode. | 読み書き両用。ファイルの任意の位置から読み書き可能。ファイルが存在しなければオープン時に作成される。 |
open()メソッドもopenAsync()メソッドも、
ファイルの読み込み
では、
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="340" height="300">
<mx:Script>
<![CDATA[
import flash.filesystem.*;
private function readData():void {
var file:File = File.desktopDirectory.resolve("sample.txt");
var stream:FileStream = new FileStream();
try {
stream.open(file, FileMode.READ);
var str:String = stream.readUTFBytes(stream.bytesAvailable);
output.text = str.replace(/\r\n/g, "\n");
} catch (error:IOError) {
trace(error.message);
} finally {
stream.close();
}
}
]]>
</mx:Script>
<mx:TextArea x="20" y="20" id="output" width="300" height="200" fontSize="16"/>
<mx:Button x="136" y="246" label="読み込み" click="readData()"/>
</mx:WindowedApplication>
![外部ファイルからデータを読み込む 外部ファイルからデータを読み込む](/assets/images/book/serial/2007/apollo-desktop-app/0008/thumb/TH400_fig001.jpg)
ここでは読み込みのみを行うので、 readUTFBytes()メソッドには引数として読み込むデータの長さを指定します。ここで指定しているFileStream. 次は上記のサンプルを非同期処理に変更してみましょう。 非同期処理の場合、 openAsync()メソッドでファイルをオープンするとバッファへのデータ入力が開始されるので、 書き出しの手順も読み込みの場合とそれほど変わりません。同期処理の場合、 FileMode. 次は非同期処理のサンプルです。 非同期処理で書き出す場合、 FileStreamクラスにはreadUTFBytes()やwriteUTFBytes()以外にも、 readMultiByte()、 また、 readObject()、 これをアプリケーション起動時にreadObject()で読み込み、 FileStream. ファイルへランダムアクセスができると、 positionプロパティは読み書き処理を実行した分だけ自動的に移動します。上記の例で言うと、 ファイルやファイルの保存先をユーザに選択させたい場合があります。Fileクラスにはそのためのメソッドが用意されており、 ※Beta 1 リリースで筆者が確認した範囲では、 次のサンプルは、 ダイアログの選択ボタンやキャンセルボタンが押された時の処理は、<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="340" height="300">
<mx:Script>
<![CDATA[
import flash.filesystem.*;
private var stream:FileStream;
private function readData():void {
var file:File = File.desktopDirectory.resolve("sample.txt");
stream = new FileStream();
stream.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
stream.addEventListener(ProgressEvent.PROGRESS, onInputProgress);
stream.addEventListener(Event.COMPLETE, onInputComplete);
stream.addEventListener(Event.CLOSE, onCloseFile);
stream.openAsync(file, FileMode.READ);
}
private function onIOError(event:IOErrorEvent):void {
trace("I/Oエラー");
stream.close();
}
private function onInputProgress(event:ProgressEvent):void {
trace(stream.bytesAvailable + "バイト読み込み済み");
}
private function onInputComplete(event:Event):void {
try {
var str:String = stream.readUTFBytes(stream.bytesAvailable);
output.text = str.replace(/\r\n/g, "\n");
} catch (error:IOError) {
trace(error.message);
} finally {
stream.close();
}
}
private function onCloseFile(event:Event):void {
trace("ファイルをクローズしました");
}
]]>
</mx:Script>
<mx:TextArea x="20" y="20" id="output" width="300" height="200" fontSize="16"/>
<mx:Button x="136" y="246" label="読み込み" click="readData()"/>
</mx:WindowedApplication>
ファイルの書き出し
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="340" height="300">
<mx:Script>
<![CDATA[
import flash.filesystem.*;
private function writeData():void {
var file:File = File.desktopDirectory.resolve("sample.txt");
var stream:FileStream = new FileStream();
try {
stream.open(file, FileMode.WRITE);
stream.writeUTFBytes(input.text);
} catch (error:IOError) {
trace(error.message);
} finally {
stream.close();
}
}
]]>
</mx:Script>
<mx:TextArea x="20" y="20" width="300" height="200" fontSize="16" editable="true" id="input"/>
<mx:Button x="136" y="246" label="書き出し" click="writeData()"/>
</mx:WindowedApplication>
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="340" height="300">
<mx:Script>
<![CDATA[
import flash.filesystem.*;
private var stream:FileStream;
private function writeData():void {
var file:File = File.desktopDirectory.resolve("sample.txt");
stream = new FileStream();
stream.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
stream.addEventListener(OutputProgressEvent.OUTPUT_PROGRESS, onOutputProgress);
stream.addEventListener(Event.CLOSE, onCloseFile);
stream.openAsync(file, FileMode.WRITE);
try {
stream.writeUTFBytes(input.text);
} catch (error:IOError) {
trace(error.message);
} finally {
stream.close();
}
}
private function onIOError(event:IOErrorEvent):void {
trace("I/Oエラー");
stream.close();
}
private function onOutputProgress(event:OutputProgressEvent):void {
trace("残り" + event.bytesPending + "バイト");
}
private function onCloseFile(event:Event):void {
trace("ファイルをクローズしました");
}
]]>
</mx:Script>
<mx:TextArea x="20" y="20" width="300" height="200" fontSize="16" editable="true" id="input"/>
<mx:Button x="136" y="246" label="書き出し" click="writeData()"/>
</mx:WindowedApplication>
様々な読み書き用メソッド
var file:File = File.desktopDirectory.resolve("shift_jis.txt");
var stream:FileStream = new FileStream();
stream.open(file, FileMode.READ);
var str:String = stream.readMultiByte(stream.bytesAvailable, "shift_jis");
stream.close();
var str:String = stream.readMultiByte(stream.bytesAvailable, File.systemCharset);
registerClassAlias("flash.geom.Rectangle", Rectangle);
registerClassAlias("flash.geom.Point", Point);
var file:File = File.applicationStorageDirectory.resolve("prefs");
var stream:FileStream = new FileStream();
stream.open(file, FileMode.WRITE);
stream.writeObject(stage.window.bounds);
stream.close();
ランダムアクセス
var file:File = File.desktopDirectory.resolve("sample.mp3");
var stream:FileStream = new FileStream();
stream.open(file, FileMode.READ);
stream.position = file.size - 128 + 3; //"TAG"をスキップ
var title:String = stream.readMultiByte(30, "shift_jis");
trace(title);
stream.close();
ファイルピッカー
browseForDirectory() フォルダ選択ダイアログを表示 browseForOpen() ファイル選択ダイアログを表示 browseForOpenMultiple() 複数ファイル選択ダイアログを表示 browseForSave() ファイル保存ダイアログを表示 <?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import flash.filesystem.File;
import flash.events.Event;
import flash.net.FileFilter;
private var file:File = new File();
private function selectFile():void {
try {
var filter:FileFilter = new FileFilter("画像ファイル", "*.jpg;*.png;*.bmp");
file.addEventListener(Event.SELECT, onSelecte);
file.addEventListener(Event.CANCEL, onCancel);
file.browseForOpen("ファイルの選択", [filter]);
} catch (error:Error) {
trace(error.message);
}
}
private function onSelecte(event:Event):void {
trace(event.target.nativePath);
}
private function onCancel(event:Event):void {
trace("キャンセルされました");
}
]]>
</mx:Script>
<mx:Button x="10" y="10" label="ファイル選択" click="selectFile()"/>
</mx:WindowedApplication>