Skip to content

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

@RemcoSchellekensNS

Description

@RemcoSchellekensNS

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;
    	} 
    }

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions