我正在尝试从R调用一些Java代码, 我已经编译了Java类,并且可以手动执行代码-很好!
但是,当从R调用相同的代码位时,会引发此错误:
4.
stop(structure(list(message = "java.lang.ArrayIndexOutOfBoundsException",
call = .jcall(obj, "[[Ljava/lang/String;", "findPattern", location),
jobj = new("jobjRef", jobj = <pointer: 0x00000000195abf30>,
jclass = "java/lang/ArrayIndexOutOfBoundsException")), class =
c("ArrayIndexOutOfBoundsException", ...
3.
.jcheck()
2.
.jcall(obj, "[[Ljava/lang/String;", "findPattern", location)
1.
findPattern()
由于手动运行Java可以正常运行,因此问题似乎出在我从r执行Java上。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class PatternFinder
{
private static final Pattern pattern = Pattern.compile("([1-9])(4-5)([asuy])");
public static void main(String[] args)
{
if (args.length == 1)
{
findPattern(args[0]);
}
else
{
System.err.println("No arguments specified");
System.exit(1);
}
}
public static String[][] findPattern(String filePath)
{
String[][] df = null;
List<String> g1 = new ArrayList<>();
List<String> g2 = new ArrayList<>();
List<String> g3 = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(filePath)))
{
String line;
while ((line = br.readLine()) != null)
{
Matcher matcher = pattern.matcher(line);
while (matcher.find())
{
g1.add(matcher.group(1).trim());
g2.add(matcher.group(2).trim());
g3.add(matcher.group(3).trim());
}
}
df = new String[g1.size()][3];
for (int i = 0; i < g1.size(); i++)
{
df[i][0] = g1.get(i);
df[i][1] = g2.get(i);
df[i][2] = g3.get(i);
}
}
catch (IOException e)
{
e.printStackTrace();
}
return df;
}
}
这是R代码:
library(rJava)
.jinit("C:\\Program Files\\Java\\jdk1.8.0_45", "C:\\PatternFinder")
obj=.jnew("PatternFinder")
patternFinder <-function(location = "C:\\largeFile.txt")
{
result = .jcall(obj,"[[Ljava/lang/String;", "findPattern", location)
df = sapply(result,.jevalArray)
df
}
patternFinder()