archimatetool / archi-scripting-plugin

jArchi - Scripting for Archi: ArchiMate Modelling Tool
https://www.archimatetool.com
122 stars 33 forks source link

[feature request] have a $.fs.readFile() function as well #128

Open RemcoSchellekensNS opened 7 months ago

RemcoSchellekensNS commented 7 months ago

Hi there, not a bug just a small "feature request". Not sure it is the right way to ask this, so forgive me if I'm doing it wrong, should I post this in Forum instead ?

When writing scripts, I found it strange that jarchi do have functions to write to a file ($.fs.writeFile...) but for reading we have to do some Java trickery. Not a big problem but for newcomers it might be an hurdle. My suggestion is to extend "FS.java" file with functions simulair to the writefunctions (read as readable String or Base64 encoded string)

(tested it with Archi 5.2 and Jarchi 1.6 version):

    /**
     * Read text from File
     * @param path
     * @throws IOException
     * @return Content of file as String 
     */

    public String readFile(String path) throws IOException {
        return readFile(path,"UTF-8");
    }

    /**
     * Read text from File
     * @param path
     * @throws IOException
     * @param encoding use BASE64 to read a binary file
     * @return Content of file as String 
     */
    public String readFile(String path, String encoding) throws IOException {
        String ret="";
        byte[] byteContent=readBinFile(path);
        if(encoding.equals("BASE64")) {     
            ret=Base64.getEncoder().encodeToString(byteContent);
        } else {
            ret=new String(byteContent);
        }
        return ret;
    }

    /**
     * Read a binary file
     * @param path
     * @throws IOException
     * @return Content of file as a byte array
     */
    private byte[] readBinFile(String path) throws IOException {
        File file = new File(path);

        try (FileInputStream inputStream = new FileInputStream(file); ) {
            long fileSize=file.length();
            byte[] allBytes = new byte[(int) fileSize];
            inputStream.read(allBytes);
            return allBytes;
        } 
    }
jbsarrodie commented 7 months ago

Hi,

I agree, I had the same discussion with some people recently. I'll look at your code and compare iit with similar code I have.