问题
I'm developing an application and because of certain design restrictions I have to do it in Flash. This application communicates with another one done in c++, but just because I need a couple strings, so I thought it would be easy to write them to a .txt file and parse it. But the only way I've found so far is adding a browse event handler and select the file manually. That's no good for me, I need the file to be read automatically given a path, something like:
var data:ByteArray = fileRef['C:\whateverPath'];
var loader:Loader = new Loader();
loader.loadBytes(data);
Can this even be done?
回答1:
Assuming since this runs on the desktop you are using AIR. If so, you can use the standard AIR file APIs like so (this assumes the file lives in the user directory):
var file:File = File.userDirectory.resolvePath("myfilename.txt");
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.READ);
var str:String = fileStream.readUTFBytes(file.size);
fileStream.close();
The above also assumes the text file is UTF-8 encoded. If not, there are other read methods in the FileStream class.
AIR also has access to other directories, of course. For instance, to get a file in the root of the C: drive on windows:
var file:File = new File("C:/mytextfile.txt");
回答2:
If you are not using AIR, you can compile your SWF with "local-with-filesystem" permissions. You can then use URLLoader to load local files. (You can also designate a SWF as trusted, and then you can access both the filesystem and the network.)
来源:https://stackoverflow.com/questions/7450888/is-there-a-way-to-read-local-files-in-actionscript-3-silently