9 Replies Latest reply on May 22, 2007 2:35 AM by shasanji

    Reading local files... how hard can it be?

    BoyTheo
      Hi flex developers,

      I am totally exasperated with flex right now. I've spent the last 2 hours trying to figure out how to do something so trivial, that it should have only taken 2 minutes.

      I want to READ data from a file, into a string variable.

      So, I look on the internet, and everyone is saying "use loadvars".

      I didn't find any nice easy simple way to JUST READ A FILE. But I can't find any. All I want to do is read a file, not have to care about events or call backs oranything like this. In other languages I can do this:

      MyData = Read(FIlePath);

      Why can't I do that in Flex? It turns out, after a lot of looking around, that I need to use this stupid event callback based system instead. This means I must set up a busy while loop after calling loadvars!

      Like this:

      static private function LoadVarsSucks(Data_:String):void {
      ReadData = Data_;
      ReadCompleted = true;
      }

      static public function LoadProperly(url:String):String {
      ReadCompleted = false;
      var myVars:LoadVars = new LoadVars;
      myVars.onData = LoadVarsSucks;
      myVars.load(url);
      while (!ReadCompleted) {
      ;
      }
      return ReadData;
      }

      So I try LoadVars anyhow. And it doesn't work!!!! After all that effort of having to work around Flex's awkward annoying pointless manner of reading files, what with it returning before the file is actually loaded, and it using event callbacks, it STILL doesn't work!

      So I try a few different solutions to getting loadvars to work. Checking if there's something I Need to import. Or if I spelt it wrong or maybe there's invisible letters in my text screwing up the name detection. No, it just doesn't work.

      Then I have a hunch, that it's been deprecated, after I remembered a different way of reading that I came across, which is through URLLoader. It turns out that LoadVars IS deprecated :( No thanks to the documentation inbuilt into Flex.

      So, after about 30 minutes of struggling through the overcomplicated documentation on URLLoader, what with it's multiple events and auto-parsing of text files into URL based symbols and automatically stuffing each into properties with values into an object... Giving me 9 different events, but NONE of which tells me where the data as one big block of data ends up in... I give up.

      I don't get it.

      I just want to read a file.

      No funny business. No fancy stuff.

      Just a file, read, into a variable.

      No automatic parsing of URL components inside a file when the file isn't even a URL, it's a file. I want the whole file read, as one block, just like every other file reader does in the Universe.

      No events.

      No need for while loops.

      Just give me a way to read a file, for god's sake will you?

      var data:String = ReadTheFreakingFile(URL:String);

      something like that, please.
        • 1. Re: Reading local files... how hard can it be?
          BoyTheo Level 1
          I made this class:

          package
          {
          import flash.net.*;
          import flash.events.Event;
          import flash.events.IOErrorEvent;

          public class FileLoader {
          static private var ReadCompleted:Boolean;

          static private function LoadVarsSucks(event:Event):void {
          ReadCompleted = true;
          }

          static public function LoadProperly(url:String):String {
          ReadCompleted = false;
          var loader:URLLoader = new URLLoader();
          loader.dataFormat = URLLoaderDataFormat.TEXT;
          loader.addEventListener(Event.COMPLETE, LoadVarsSucks);
          loader.addEventListener(IOErrorEvent.IO_ERROR, LoadVarsSucks);

          try {
          loader.load(new URLRequest(url));
          } catch (error:ArgumentError) {
          trace("An ArgumentError has occurred.");
          } catch (error:SecurityError) {
          trace("A SecurityError has occurred.");
          }

          while (!ReadCompleted) {
          ;
          }
          return loader.data;
          }
          }
          }

          But it's STILL not working :(

          the problem now, is that the loop just continues infinitely.

          No error.

          No success.

          Just forever hovering inbetween success and failiure.

          Why?
          • 2. Re: Reading local files... how hard can it be?
            JKohn99 Level 1
            You need to get the data from the event handler.
            Here is a working example that gets some xml data via a url:
            Note that any one who then wants the data must listen for the appParms event
            dispatched in the complete handler.

            In this example the caller (my main flex application) invokes the load parms.
            The even handler when invoked proceeds with initialization using the parms loaded.
            Remember that Flex is asynchronous so your try/catch will not work
            and you really don't know when the response will come back to the event handler. You will find that in genearl linear style programming will not work in flex since actionscript just trundles along and does not wait.

            doLoadRequest(appUrl:String):void
            {
            var request:URLRequest = new URLRequest(appUrl);
            var variables:URLLoader = new URLLoader();
            variables.dataFormat = URLLoaderDataFormat.TEXT;
            // completeHandler get invoked.
            variables.addEventListener(Event.COMPLETE, completeHandler);
            variables.addEventListener(IOErrorEvent.IO_ERROR,errorHandler);
            variables.load(request);
            }

            private function completeHandler(event:Event):void
            {

            if(event.currentTarget.data == null)
            {
            ExceptionManager.getInstance().getHandlerResponse("default","The Application Parms Handler is empty");
            return;
            }
            parms = new XML(event.currentTarget.data);
            logAPH.info("Inside completeHandler(event:Event) :"+parms);
            dispatchEvent(new SimpleEvent("appParms","1"));
            }
            • 3. Re: Reading local files... how hard can it be?
              JKohn99 Level 1
              One more point. My example loads data from the web server. Be wary of sandbox security when trying to access files on the local workstations when the Flex application is loaded from a url. Lots of rules around this.

              In flex builder when doing testing the security sandbox is basically turned off.
              • 4. Re: Reading local files... how hard can it be?
                BoyTheo Level 1
                Thanks JKohn.

                Only this solution doesn't help me. I need syncronous reading.

                Or at least some explanation of how do I modify code that was ported from another platform that assumes syncronous reading?

                I have absolutely NO CLUE how to restructure code to deal with non-syncronous reading.

                Are there any computer OOP theory design patterns written for flex developers who are porting apps from other languages and can't use syncronous reading?

                Surely it can't be that hard? There must be some way.

                Actually, it's not true that there is no way, there is some way in flash, which is to do some trick with frames, so that the next frame won't load until all files are loaded.

                But does flex even have the concept of frames??
                • 5. Re: Reading local files... how hard can it be?
                  peterent Level 2
                  Why don't you try Apollo (on Adobe Labs)? That lets you read and write files locally since it appears you want a desktop app, not a web app.

                  Apollo has a File class which allows you to read directories and files pretty easily, I used it a number of times. It is also operating system independent.
                  • 6. Re: Reading local files... how hard can it be?
                    shasanji
                    hi all
                    if it is web application use this script it works well,

                    <mx:Script>
                    <![CDATA[
                    private function loadText():void {
                    var l:URLLoader = new URLLoader(new URLRequest('2.txt'))
                    l.addEventListener(Event.COMPLETE, finishLoading);
                    }
                    public function finishLoading(evt:Event):void {
                    var myData:String =new String(evt.target.data)
                    txtBox.text=myData;
                    }

                    ]]>
                    </mx:Script>
                    • 7. Re: Reading local files... how hard can it be?
                      peterent Level 2
                      new URLLoader(new URLRequest("2.txt")) will not read the local file, 2.txt. If you have launched your SWF using a local reference, such as from Flex Builder, then the read would be local, but only deceptively.

                      If you serve the SWF from a web server, the URLRequest will be formed such that 2.txt will have to come from the same server where the SWF is located - on the server. As specified 2.txt is a path relative the context root of the server.
                      • 8. Re: Reading local files... how hard can it be?
                        shasanji Level 1
                        hi yes u right i place all my component in the webroot i call it through the web browser (ex- http://localhost/flex//bin/testFlex.html) then it works like calling from server.Tto work in local i read one article saying that have copile with this compile command use-network=true|false Specifies that the current application uses network services.

                        The default value is true.

                        When the use-network property is set to false, the application can access the local filesystem (for example, use the XML.load() method with file: URLs) but not network services. In most circumstances, the value of this property should be true.

                        For more information about the use-network property

                        but i haven't test it yet
                        • 9. Re: Reading local files... how hard can it be?
                          shasanji Level 1
                          hi all
                          i test that compile command it works if u compile as i said u can access local file system but u cant connect to other computers.