Copy link to clipboard
Copied
My question is about the local file system object `File`. I am writing a function that reads the contents of a text file. The function is passed a `File` object as an argument and then reads the content before some other logic.
Before you can read a `File` object it needs to be open. The Adobe JavaScript documentation has the following warning around opening files:
NOTE: Be careful about opening a file more than once. The operating system usually permits you to do so, but if you start writing to the file using two different File objects, you can destroy your data.
So my question is... How do I tell if a File object is already open? There doesn't appear to be a property or method that simply tells me this.
Hi,
Suggest to use method file.tell() ==> which returns "-1" if current position cant be retrieved.
If file is opened it returns number >=0 .
Jarek
Copy link to clipboard
Copied
Just a thought: Perhaps you can try reading from the file first without opening it. If this fails, it's closed. If it succeeds, that would mean it's already open.
I do not know if this approach works though -- haven't tested it.
Copy link to clipboard
Copied
Well something like this seems to work. But it seems a little hacky:
function fileIsOpen(fl) {
fl.error = '';
fl.readch();
if(fl.error) {
return false;
} else {
return true;
}
}
Copy link to clipboard
Copied
Hi,
Suggest to use method file.tell() ==> which returns "-1" if current position cant be retrieved.
If file is opened it returns number >=0 .
Jarek
Copy link to clipboard
Copied
Great! Thanks for that!
Copy link to clipboard
Copied
Hi
I am not sure that the answers here are correct.
A file could be opened by an external process and show that it's closed using the described methods.
The snippet below demonstrates this.
var fName, aFile, theSameFile;
fName = Folder.temp + "/" + +(new Date) + ".txt";
aFile = new File(fName);
aFile.open("w");
aFile.write('hello');
theSameFile = new File(fName);
// Shows the theSameFile as not open even though the actual file is open with a different reference
// The warning "NOTE: Be careful about opening a file more than once.
// The operating system usually permits you to do so,
// but if you start writing to the file using two different File objects,
// you can destroy your data."
// Still applies
alert("aFile.tell(): " + aFile.tell() + "\ntheSameFile.tell(): " + theSameFile.tell());
aFile.close();
Sorry to be a party pooper.
Trevor
Copy link to clipboard
Copied
HiTrevorׅ‌,
I have to agree and have to cancel pyrotechnic on my party.
Mentioned method tells only about THIS - created by javascript - object, which in fact can be multiplied with the same path.
So the same OS file can be accessed by many file-objects created by javascript or even other processes.
However opening objects with "a" (instead of "w") mode should protect file contents applied by other processes.
...or I am completely wrong...
Jarek