Read and write data to file through rules

Hi all! I propose two simple functions to save and read data to a file. I use these functions to save state of items with type string and date (RRD4j doesn’t save them). However, you can use them as you wish.

//Tested ECMAS 262 11. openHAB 4.0.2 

/**
 * write data to file
 * 
 * @param {String} file — full file name 
 * @param {String} data — data
 * @param {Boolean} append — true for append. False for erase old data and write new.
 *
 */		
const fileWrite = function(file,data,append = false) {
	const FileWriter = Java.type('java.io.FileWriter');
	try {
		const output = new FileWriter(file,append);
		output.write(data);
		output.close();
	} catch (e) {
		console.error(e);      
	}
}


/**
 * read data from file
 * 
 * @param {String} file — full file name 
 * @returns {String}
 *
 */		
const fileRead = function(file) {
	const FileReader = Java.type('java.io.FileReader');
	var data = '';
	try {
		const input = new FileReader(file);
		var char;
		while((char = input.read()) !== -1) {
			data += String.fromCharCode(char);
		}
		input.close();
		return data;
	}  catch(e) {
		console.error(e);      
	}
}

2 Likes