file.js
Summary
General File I/O Class
Class Summary
|
File |
Class implementing basic support for files
|
function File(name) {
this.name = name;
}
File.prototype.getAbsolutePath = function(mode) {
if (typeof(mode) == "undefined") {
mode = GPSystem.CWD;
}
if (typeof(this.abspath) == "undefined") {
this.abspath = GPSystem.mapFilename(this.name, mode);
}
return this.abspath;
}
File.prototype.getFile = function() {
if (typeof(this.file) == "undefined") {
this.file = new java.io.File(this.getAbsolutePath(GPSystem.AUTO));
}
return this.file;
}
File.prototype.close = function() {
if (typeof(this.os) != "undefined") {
this.os.close();
delete(this.os);
}
if (typeof(this.is) != "undefined") {
this.is.close();
delete(this.is);
}
}
File.prototype.getInputStream = function() {
if (typeof(this.is) == "undefined") {
this.is = new java.io.FileInputStream(this.getAbsolutePath(GPSystem.AUTO));
}
return this.is;
}
File.prototype.getOutputStream = function() {
if (typeof(this.os) == "undefined") {
this.os = new java.io.FileOutputStream(this.getAbsolutePath(GPSystem.CWD));
}
return this.os;
}
File.prototype.readAllAsBinary = function() {
var is = this.getInputStream();
var flen = is.available();
var bs = java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, flen);
var len = is.read(bs);
this.close();
var bb = new ByteBuffer(bs);
var data = bb.toByteString();
return data;
}
File.prototype.readAllAsString = function(encoding) {
if (typeof(encoding) == "undefined") {
encoding = UTF8;
}
return this.readAllAsBinary().toString(encoding);
}
File.prototype.writeAll = function(obj, encoding) {
if ((typeof(obj) != "string") && !(obj instanceof ByteString)) {
obj = obj.toString();
}
if (typeof(obj) == "string") {
if (typeof(encoding) == "undefined") {
encoding = UTF8;
}
obj = new ByteString(obj, encoding);
}
var os = this.getOutputStream();
os.write(obj);
this.close();
}
File.prototype.list = function() {
var list = this.getFile().list();
var jslist = [];
for (var i = 0; i < list.length; i++) {
jslist.push(new String(list[i]));
}
return jslist;
}
File.prototype.getParentFile = function() {
var file = this.getFile();
var parent = file.getParent();
if (parent == null) {
return null;
}
return new File(parent);
}
File.test = function() {
var file = new File("test.bin");
var b = new ByteString("Hello World", ASCII);
file.writeAll(b);
var file = new File("test.bin");
var c = file.readAllAsBinary();
print(c.toString(ASCII));
var file = new File("test.txt");
var s = "Hello World";
file.writeAll(s);
var file = new File("test.txt");
var c = file.readAllAsString();
print(c);
var dir = file.getParentFile();
print(dir.getAbsolutePath());
print(dir.list());
}
Documentation generated by
JSDoc on Tue Apr 15 22:10:49 2025