Skip to content

Instantly share code, notes, and snippets.

@joonaspaakko
Created October 11, 2021 07:54
Show Gist options
  • Save joonaspaakko/052cd9eaa42fe1272ff9c0bf5ee0e2d8 to your computer and use it in GitHub Desktop.
Save joonaspaakko/052cd9eaa42fe1272ff9c0bf5ee0e2d8 to your computer and use it in GitHub Desktop.
Read and write text example in Adobe extendscript
// In this demo:
// 1. I first prep the output file path
// 2. Then write the text file: "current date and time + some placeholder text"
// - As long as you don't change the path, it gets written next to this script file.
// 3. Then read the text file
// 4. And finally trigger alert() to show the text that was written.
// - At the top it shows each line as an array
// - And below that it just shows the full text as it was written.
// Preparing output path
var scriptFolder = File.decode( File($.fileName).parent );
var file = scriptFolder + "/Read and write text.txt";
// Writing
var date = new Date();
writeTextFile( file, date + ' Suspendisse ut tortor sapien. \r\n\r\nAenean vitae magna tempus, fermentum.' );
// Reading
var textLines = [];
var fullText = readTextFile( file, function( line, i ) {
textLines.push( line );
});
alert( textLines.toSource() + '\n\n' + fullText );
// ↑↑↑ USAGE EXAMPLES ↑↑↑
// Returns all of the text as is
// Returns false if the file doesn't exist
// Callback is triggered for each line of text
function readTextFile( filePath, callback ) {
var file = new File( filePath );
if ( file.exists ) {
file.open('r');
file.encoding = 'UTF8';
var text = file.read();
file.close();
var lines = text.match(/\\r\\n/) ? text.split('\r\n') : text.match(/\\r/) ? text.split('\r') : text.split('\n');
if ( typeof callback == 'function' ) {
for ( var i=0; i < lines.length; i++ ) {
callback( lines[i], i );
}
}
return text;
}
else {
return false;
}
}
// Set the third parameter to true if you don't want this to create the file if it doesn't already exist.
// Returns false if file was not created. Doesn't account for write errors...
function writeTextFile( filePath, textContent, dontCreateFile ) {
var file = new File( filePath );
var fileExists = file.exists;
if ( fileExists || !fileExists && dontCreateFile !== true ) {
file.open('w'); // Opens a file for writing. If the file exists, its contents are destroyed. If the file does not exist, creates a new, empty file.
file.encoding = 'UTF8';
file.write( textContent );
file.close();
}
else {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment