Provides functions for input and output through data streams and the file system.

1 File

The File class gives access to java.io.File. By default, a invoking new Ax.io.File() without parameters, points to directory where server starts.

Return Method Description
File append
long append(byte[] data) Appends a byte[] to file.
void append(String text) Appends a text as UTF-8.
void append(String text, string charsetName) Appends a text in the specfied encoding.
void append(String text, string charsetName, boolean ignoreErrors) Appends a text in the specfied encoding. ignoring encoding errors between source and destination file
File read
String asBytes() Return the file as byte[].
byte[] asString() Return the file as UTF-8 String.
byte[] asText() Return the file as UTF-8 String. (same to asString)
File permissions
boolean canWrite() Whether user has write permission on the file.
boolean canRead() Whether user has read permission on the file.
boolean canExecute() Whether user has execute permission on the file.
File delete
JSFile delete() Deletes the file or directory denoted by this object.
File information
String getAbsolutePath() Returns file absolute path.
String getContentType() Returns file mimetype.
long getCreationTime() Returns file creation time in millis.
long getLastAccessTime() Returns file last access time in millis.
long getLastModified() Returns file last modified time in millis.
long getLineCount() Returns number of lines of the file.
long getFreeSpace() Returns directory free space.
String getName() Returns file name.
String getNameTo(String separator) Returns file name until the spcific separator.
JSFile getParentFile() Returns a JSFile Object parent of this object.
File information
boolean isDirectory() Returns if file is a directory.
boolean isFile() Returns if file is a file.
long lastModified() Returns the file last modified time in millis.
long length() Returns the length of the file denoted by this abstract pathname.
File listing
String[] list() If JSFile is a Folder, returns String Array containing names of files inside this folder. If this object do not represent a folder, returns null.
JSFile[] listFiles() If JSFile is a Folder, returns an Array of JSFiles pointing to files inside this folder. If this object do not represent a folder, returns null.
Directory making
JSFile mkdir() Creates the directory named by this File Object.
JSFile mkdirs() Creates the directory named by this File Object, including necessary and non-existent parent directories.
File reading
byte[] readBytes() Converts file content to a byte array object.
String readString() Converts file content to a string object.
String readString(charset) Converts file content in CharSet encoding to a string object.
String readString(charset, ignoreErrors) Converts file content in CharSet encoding to a string object. I there are some character in file not belonging to charset, error is ignored and character is getted "as is".
File renaming
JSFile renameTo(String name) Renames the file denoted by this object to the file name passed as parameter. If string passed as parameter doesn't starts with "/", is considered a relative path from current file.
JSFile renameTo(JSFile file) Renames the file denoted by this object to the file denoted by object passed as parameter.
File conversion
JDBCBlob toBlob() Converts file content to a blob object.
InputStream toInputStream() Converts file in inputStream and returns it.
Reader toReader() Returns a reader of the file
Reader toReader(String charset) Returns a reader of the file
Writer toWriter() Returns a writer of the file
Reader split(int linesPerSplit) Split file into N chunks of up to the "linesPerSplit" parameter. It only makes sense for text files (there is no binary equivalent). Output files are generated in temporary directory.Returns an array of splited temp files
File write
long write(Blob data) Write a Blob to file
long write(byte[] data) Write a byte[] to file
long write(String data, String charset) Write a string to file in the specific charset encoding
void write(String text, string encoding, boolean ignoreErrors) Write a string to file in the specific charset encoding ignoring enconding errors between source and destination file
You can also access JSFile static methods to create temporary files.

2 File information

Copy
var folder = new Ax.io.File();
console.log("NAME         =" + folder.getName());
console.log("PATH         =" + folder.getAbsolutePath());
console.log("PARENT       =" + folder.getParentFile());
console.log("LENGTH       =" + folder.length());
console.log("FREE SPACE   =" + folder.getFreeSpace());
console.log("IS FILE      =" + folder.isFile());
console.log("IS DIRECTORY =" + folder.isDirectory());
console.log("CAN READ     =" + folder.canRead());
console.log("CAN WRITE    =" + folder.canWrite());
console.log("CAN EXECUTE  =" + folder.canExecute());

if (folder.isDirectory()) {
  console.log("LIST         =" + folder.list());
  console.log("LIST FILES   =" + folder.listFiles());
}
NAME         =.
PATH         =/Users/vsc/workspace/axional-server-dbstudio/.
FREE SPACE   =845970210816
IS FILE      =false
IS DIRECTORY =true
LIST         =[.DS_Store, bin, .classpath.orig, out, .hgignore, watch.sh, install.md, .classpath, docs, TODO.md, README.md, gradle, gradlew, .project.orig, .settings, .project, build.gradle, .gradle, .hg, build, gradlew.bat, settings.gradle, conf, swt, init_npm.sh, COMPILEJS.md, .idea, src]
LIST FILES   =[./.DS_Store, ./bin, ./.classpath.orig, ./out, ./.hgignore, ./watch.sh, ./install.md, ./.classpath, ./docs, ./TODO.md, ./README.md, ./gradle, ./gradlew, ./.project.orig, ./.settings, ./.project, ./build.gradle, ./.gradle, ./.hg, ./build, ./gradlew.bat, ./settings.gradle, ./conf, ./swt, ./init_npm.sh, ./COMPILEJS.md, ./.idea, ./src]

You can iterate file list and invoke Readers from files:

Copy
var folder = new Ax.io.File("/tmp");

if (folder.isDirectory()) {
    for each(var f in folder.listFiles()) {
        if (f.isFile() && f.getName().endsWith(".txt")) {
            console.log(f);
        }
    }
}

3 Write to file

You can directly write to a file by using one of the following methods.

Return Method
long write(Blob blob)
long write(byte[] data)
void write(String text)
long write(String text, String charSet)

This method writes to file exclusively data received. User is responsible for sending end lines characters in the writing data.

Copy
var f = new Ax.io.File("/tmp/text_file.txt");

f.write("File content text\nSecond line");

4 Append to file

You can append to a file by using one of the following methods:

Return Method
long append(byte[] data)
void append(String text)
long append(String text, String charSet)

Append method creates the file if it doesn't exists. If file already exists, just appends data at the end of current content.

Also, this method writes to file exclusively data received. User is responsible for sending end lines characters in the writing data.

Copy
var f = new Ax.io.File("/tmp/text_file.txt");

f.append("File content text\n");
f.append("Second line");

5 Read from file

You can directly read from a file by using one of the following methods.

Return Method
byte[] readBytes()
String readString()
String readString(String charSet)

Copy
var tmpfile = Ax.io.File.createTempFile();
tmpfile.write("Hello World!\nHello Universe!\nHello everyone!");        

var content = tmpfile.readString();

const allLines = content.split(/\r\n|\n/);
// Reading line by line
allLines.forEach((line) => {
    console.log("Line: " + line);
});

6 Create Temporary File

Ax.io.File.createTempFile() is an static function creating a new temporary file each time is invoked. All temporary files created into an script execution are automatically removed when script ends.

Temporary file naming has the format name-number.tmp:

  • A prefix name (defaults to jsfile) is used
  • A minus (-)
  • A sequence number
  • .tmp

Copy
var tmpfile = Ax.io.File.createTempFile();
tmpfile.write("Hello World!");

// This file will be deleted automatically when script finishes.
console.log("FILE PATH   = " + tmpfile.getAbsolutePath());
console.log("FILE EXISTS = " + tmpfile.isFile());
FILE PATH   = /var/folders/_t/x9y8_wdn74jd_l8y2sv0tyvm0000gs/T/axional-15422/JSFile/jsfile-356740355785338849.tmp
FILE EXISTS = true

6.1 Create named temporary files

You may want to use an specific name for the temporary file. Numbering will still be automically added but the name provided to fucntion will be part of temporary name. Using getNameTo("-") can be used to retrieve the "original" name without temporary part.

Copy
var f = Ax.io.File.createTempFile("abc");
console.log("TEMP1:" + f);
console.log("TEMP2:" + f.getName());
console.log("TEMP3:" + f.getNameTo("-"));
TEMP1:/var/folders/h1/chsft9sj5pz64g45lmfbwdym0000gn/T/axional-863/JSFile/abc-13452678154332861398.tmp
TEMP2:abc-13452678154332861398.tmp
TEMP3:abc

6.2 Split file in temporary files

Reading huge files in memory can cause memory issues. split method allow to split text files in smaller temporary files.

Copy
var folder = new Ax.io.File("/tmp");

for (var f of folder.listFiles()) {

	if (!f.isFile() || f.getName().match(/.*\.csv$/gi) == null) {
		continue;
	}
	
	for (var fs of f.split(5000) ) {
		console.log("Load " + fs.getName() + " CSV file using Ax.rs.Reader");
	}
}

7 Traversing a directory

You can use listFiles() to get the list of files of a given path.

Copy
// Point to tmp directory
    var dir = new Ax.io.File("/tmp");
    
    // Obtain the list of files
    for (var file of dir.listFiles()) {
        if (file.isFile())
            console.log("FILE     : " + file);
        else
            console.log("DIRECTORY: " + file);
    }
DIRECTORY: /Users/jet/.aws
FILE     : /Users/jet/.gitconfig
FILE     : /Users/jet/heapdump.threads
FILE     : /Users/jet/heapdump_web1.domIn.index
FILE     : /Users/jet/heapdump.idx.index
FILE     : /Users/jet/heapdump-1558452327095.domIn.index
FILE     : /Users/jet/heapdump_web1.a2s.index
...

7.1 Using filters

You can use FilenameFilter style function for directory listing filtering.

Copy
// Point to tmp directory
var dir = new Ax.io.File("/tmp");

console.log(dir.listFiles(f => {
    return f.getName().equals(".aws");
}));
[[/Users/jet/.aws]]