| (!*******************************************************
   file handleerror.mos
   ````````````````````
   a model that demonstrates handling exceptions thrown by Java code
   (c) 2016 Fair Isaac Corporation
       author: J. Farmer, 2016
  *******************************************************!)
model myModel
  uses 'mosjvm','mmsystem'
  
  declarations
    classAndMethodName = "FileUtils.readFileToString"
    fileToRead = "input.txt"
    result: text
  end-declarations
 
  ! Tell Java to look for classes in work directory
  setparam('jvmclasspath',getparam('workdir'))
 
  ! Call into Java to read file
  ! (note that the given filename does not exist, so the Java class will throw a FileNotFoundException)
  result := jvmcalltext( classAndMethodName, fileToRead )
  if jvmstatus=false then
    writeln('ERROR from Java: ',jvmgetexceptionclass,': ',jvmgetexceptionmsg)
    exit(8)
  else
    writeln('Read data from ',fileToRead,' as follows:')
    writeln(result)
  end-if
end-model
 | 
| /**
 * Example Java class, defining file-related utility functions
 *
 * @author  J.Farmer, (c) Fair Isaac Corporation, 2016
 **/
import java.io.*;
public class FileUtils {
	/**
	 * Given a file path, read the file content into a string
	 **/
	public static String readFileToString(String path) throws IOException {
		StringWriter result = new StringWriter();
		try (Reader in = new BufferedReader(new FileReader(path))) {
			int c;
			while ((c=in.read())!=-1) {
				result.write(c);
			}
		}
		return result.toString();
	}
} |