Flex - 尝试将列表中的文本文件加载到TextArea中

时间:2011-06-27 18:36:20

标签: flex file text datagrid load

我有一个TextArea和一个DataGrid。我已经在DataGrid中填充了目录中的文本文件列表。现在我正在尝试将所选文件加载到TextArea中。从列表中选择一个文件时,我得到一个空指针异常,这告诉我我没有正确访问它...我想。

    <s:TextArea id="mainTextField" x="0" y="0" width="730" height="523"
                    editable="true" enabled="true"/>
        <s:DataGrid id="list" x="730" y="0" width="294" height="523" dataProvider="{files}" gridClick="listHandler(event)">
            <s:columns>
                <s:ArrayList>
                    <s:GridColumn dataField="name" headerText="Filename"/>    
                </s:ArrayList>
                </s:columns>

        </s:DataGrid>

...

    private var files:ArrayCollection;

                public var stream:FileStream = new FileStream(); // The FileStream object used for reading and writing the currentFile
                public var currentFile:File;

    private function init():void
                {

                    // Default on start: resolve desktop directory
                    var desktop:File = File.desktopDirectory;
                    // Get desktop directory listing
                    files = new ArrayCollection(desktop.getDirectoryListing());
                }

                protected function listHandler(event:GridEvent):void
                {
                    currentFile = event.target as File;
                    trace(currentFile.nativePath.toString()); **//Error occurrs here**
                    stream = new FileStream();
                    stream.openAsync(currentFile, FileMode.READ);
                    stream.addEventListener(Event.COMPLETE, fileReadHandler);
                    stream.addEventListener(IOErrorEvent.IO_ERROR, readIOErrorHandler);
                }

                public function fileReadHandler(event:Event):void 
                {
                    var str:String = stream.readUTFBytes(stream.bytesAvailable);
                    stream.close();
                    var lineEndPattern:RegExp = new RegExp(File.lineEnding, "g");
                    str = str.replace(lineEndPattern, "\n");
                    mainTextField.text = str; 
                    stream.close();
                }

1 个答案:

答案 0 :(得分:2)

我对此并不是100%肯定,但我认为event.target不是GridClick事件中的行(即文件)。我认为GridClick事件更适合选择一个单元格。试试

currentFile = list.selectedItem as File;

如果这不起作用,请尝试:

curentFile = files.getItemAt(event.rowIndex) as File;