Issue with loading csv with ejml - java

I'm encountering some problems by using the MatrixIO.loadcsv() function in ejml. In fact, I need to load a file into a matrix; i'm following this official example:
public static void main( String args[] ) {
DMatrixRMaj A = new DMatrixRMaj(2,3,true,new double[]{1,2,3,4,5,6});
try {
MatrixIO.saveCSV(A, "matrix_file.csv");
DMatrixRMaj B = MatrixIO.loadCSV("matrix_file.csv");
B.print();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
But when I try my code
DMatrixRMaj B = MatrixIO.loadCSV("sets.csv");
B.print();
I always obtain a FileNotFoundException... but the name of the file is correct and in the same folder of the source code. Where can be the problem?

The solution for me (I'm using Windows 10) is to use absolute path, because it seems not to recognize relative ones on my system, despite of the official examples.

Related

Is it possible to get a number of folder in a jar file?

I have a (maybe simple) question. In my code I want to know whether there are one or more folder in a classpath or not. First things first: my code is working when using IDE, but not when it runs in a jar file. I understood that there is the way with - especially in Spring Boot - the class PathMatchingPatternResolver to get the resources. I have done this, but I can't get my code working under *.jar. The situation is as follows:
I want to look at a certain path if there are certain folder to get their names. If there are such folder, the names of them will be saved in a List. I need this List in further action. But how to get the folder from *.jar?
Here is what I have done so far:
public List<String> loadSupportedRecords(Meta metaFromTaxCase) {
List<String> vastRecordTypes = new ArrayList<>();
Map<String, String> values = new HashMap<>();
values.put(TAX_TYPE, metaFromTaxCase.getTaxonomie().getKey());
values.put(FISCAL_YEAR, metaFromTaxCase.getVeranlagungszeitraum());
values.put(TAXONOMIE_VERSION, metaFromTaxCase.getVersionDerTaxonomie());
var path = replaceVariablesInPathWithMapValues(vastConfigTemplatePath, values);
var indexOfRepo = path.lastIndexOf("{record-type}/");
var lengthOfVar = "{record-type}".length();
var subPath = path.substring(0, indexOfRepo + lengthOfVar);
try {
for (Resource resource : resourcePatternResolver.getResources(subPath)) {
vastRecordTypes.add(resource.getFilename()); // <-- This does not work
// I know that this does not work, but this is my newest commit.
// I tried with File Object and used the "listFiles()" method,
// but also failed.
}
return vastRecordTypes;
} catch (IOException e) {
throw new ResourceNotFoundException(
String.format(CLASSPATH_ERROR_MESSAGE, path, e.getMessage()));
}
}
Is there any way to get the folder names in IDE AND in *.jar running?
Thank you all for helping me as good as you can.
Finally I got things work. My code runs as follows:
public Set<String> loadSupportedRecords(Meta metaFromTaxCase) {
Set<String> vastRecordTypes = new HashSet<>();
Map<String, String> values = new HashMap<>();
values.put(TAX_TYPE, metaFromTaxCase.getTaxonomie().getKey());
values.put(FISCAL_YEAR, metaFromTaxCase.getVeranlagungszeitraum());
values.put(TAXONOMIE_VERSION,metaFromTaxCase.getVersionDerTaxonomie());
var path = replaceVariablesInPathWithMapValues(vastConfigTemplatePath, values);
try {
for (Resource resource : resourcePatternResolver.getResources(path)) {
vastRecordTypes.add(((ClassPathResource) resource).getPath().split("/")[8]);
}
return vastRecordTypes;
} catch (IOException e) {
throw new ResourceNotFoundException(
String.format(CLASSPATH_ERROR_MESSAGE, path, e.getMessage()));
}
}
As I learned, it is not possible to get "folder" in jar environment. It seems that all is treated as a file. So I searched the file-tree and used the above split method to get the individual folder name. In my code I can be sure, that the first 8 elements of the Array are always the same, so it can be hard coded. I also used a Set now instead of a List, to avoid double inserts (because there are a lot of files underneath the folder). Thanks to all.

How do I resolve this error using Paths.of?

I have been trying many of the examples provided and have yet to be successful. Here is the code I am currently trying, but getting an error in Eclipse on Paths.of (the of is underlined in red) that says: "rename in file".
String content;
try {
content = Files.readAllLines(Paths.of("C:", "Calcs.txt"));
} catch (IOException e1) {
e1.printStackTrace ();
}
System.out.println (content);
First it is not possible, if you get a list as return type, to assign this to a string. So you must write:
List<String> content;
Second regarding to the Java 8 documentation there is no method of available for this class. You can use the method get like this:
List<String> content = Files.readAllLines(Paths.get("C:", "Calcs.txt"));
Otherwise there exists a method of in the Path class since Java 11. Therefore you can write something like that:
List<String> content = Files.readAllLines(Path.of("C:", "Calcs.txt"));
You're probably looking for Paths.get:
String content;
try {
content = String.join("\n", Files.readAllLines(Paths.get("/home/hassan", "Foo.java")));
} catch (IOException e1) {
e1.printStackTrace ();
}

ini4j INI key length > 80 chars

I need to communicate with a 3th party software through INI files, and I'm using the ini4j library for this.
All was going well, until I need to be able to use a key length of >80 chars.
The library is returning :
Exception in thread "main" java.lang.IllegalArgumentException: Key too
long:
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
at
java.util.prefs.AbstractPreferences.put(AbstractPreferences.java:243)
The library has set this in Preferences.java:
public static final int MAX_KEY_LENGTH = 80;
Is there any clean way around this?
I found something related here, but I'm not sure how to use it:
http://ini4j.sourceforge.net/apidocs/index.html?org/ini4j/addon/StrictPreferences.html
This is the sample code:
try {
Wini ini = new Wini(new File("test.ini"));
ini.getConfig().setStrictOperator(true);
ini.getConfig().setEscape(false);
java.util.prefs.Preferences prefs = new IniPreferences(ini);
prefs.node("Section").put("0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789", "Test");
ini.store();
} catch (IOException e) {
e.printStackTrace();
}
I was able to fix my problem by using the JIniFile library (https://github.com/SubZane/JIniFile) instead of the Ini4j library.
All working fine now.

Get content of a file inside a directory

I want to get the content of a file inside a directory:
/sys/block/sda/device/model
I use this code to get the content:
String content = new String(Files.readAllBytes(Paths.get("/sys/block/sda/device/model")));
But in some scenarios, I have cases like this:
/sys/block/sda/device/model
/sys/block/sdb/device/model
/sys/block/sdc/device/model
How I can iterate all the directories starting with
sd* and print the file model?
Can you show me some example for Java 8 with filter?
Here is an example of how to do this using Java 8 features:
Function<Path,byte[]> uncheckedRead = p -> {
try { return Files.readAllBytes(p); }
catch(IOException ex) { throw new UncheckedIOException(ex); }
};
try(Stream<Path> s=Files.find(Paths.get("/sys/block"), 1,
(p,a)->p.getName(p.getNameCount()-1).toString().startsWith("sd"))) {
s.map(p->p.resolve("device/model")).map(uncheckedRead).map(String::new)
.forEach(System.out::println);
}
This is an example that strives for compactness and working stand-alone. For real applications, it’s likely that you would do it a bit differently. The task of using an IO operation as a Function which doesn’t allow checked exception is quite common so you might have a wrapper function like:
interface IOFunction<T,R> {
R apply(T in) throws IOException;
}
static <T,R> Function<T,R> wrap(IOFunction<T,R> f) {
return t-> { try { return f.apply(t); }
catch(IOException ex) { throw new UncheckedIOException(ex); }
};
}
Then you can use
try(Stream<Path> s=Files.find(Paths.get("/sys/block"), 1,
(p,a)->p.getName(p.getNameCount()-1).toString().startsWith("sd"))) {
s.map(p->p.resolve("device/model")).map(wrap(Files::readAllBytes))
.map(String::new).forEach(System.out::println);
}
But maybe you’d use newDirectoryStream instead even if the returned DirectoryStream is not a Stream and hence requires a manual Stream creation as this method allows passing a glob pattern like "sd*":
try(DirectoryStream<Path> ds
=Files.newDirectoryStream(Paths.get("/sys/block"), "sd*")) {
StreamSupport.stream(ds.spliterator(), false)
.map(p->p.resolve("device/model")).map(wrap(Files::readAllBytes))
.map(String::new).forEach(System.out::println);
}
Finally, the option to process the files as stream of lines should be mentioned:
try(DirectoryStream<Path> ds
=Files.newDirectoryStream(Paths.get("/sys/block"), "sd*")) {
StreamSupport.stream(ds.spliterator(), false)
.map(p->p.resolve("device/model")).flatMap(wrap(Files::lines))
.forEach(System.out::println);
}
Rather using st* it's better if you can first search the existing folder inside the path /sys/block by using below code.
Please find working example :-
String dirNames[] = new File("E://block").list();
for(String name : dirNames)
{
if (new File("E://block//" + name).isDirectory())
{
if(name.contains("sd")){
String content = new String(Files.readAllBytes(Paths.get("E://block//"+name+"//device//model")));
System.out.println(content);
}
}
}

Execute a Java program from our Java program

I used
Runtime.getRuntime().exec("_____")
but it throws a IOException as below:
java.io.IOException: CreateProcess: c:/ error=5
at java.lang.Win32Process.create(Native Method)
at java.lang.Win32Process.<init>(Win32Process.java:63)
at java.lang.Runtime.execInternal(Native Method
I don't know whether I have the problem with specifying the path or something else. Can anyone please help me with the code.
You're trying to execute "C:/". You'll want to execute something like:
"javaw.exe d:\\somejavaprogram\\program.jar"
Notice the path separators.
I'm assuming this is for an ad-hoc project, rather than something large. However, for best practice running external programs from code:
Don't hardcode the executable location, unless you're certain it will never change
Look up directories like %windir% using System.getenv
Don't assume programs like javaw.exe are in the search path: check them first, or allow the user to specify a location
Make sure you're taking spaces into account: "cmd /c start " + myProg will not work if myProg is "my program.jar".
You can either launch another JVM (as described in detail in other answers).
But that is not a solution i would prefer.
Reasons are:
calling a native program from java is "dirty" (and sometimes crashes your own VM)
you need to know the path to the external JVM (modern JVMs don't set JAVA_HOME anymore)
you have no control on the other program
Main reason to do it anyway is, that the other application has no control over your part of the program either. And more importantly there's no trouble with unresponsive system threads like the AWT-Thread if the other application doesn't know its threading 101.
But! You can achieve more control and similar behaviour by using an elementary plugin technique. I.e. just call "a known interface method" the other application has to implement. (in this case the "main" method).
Only it's not quite as easy as it sounds to pull this off.
you have to dynamically include required jars at runtime (or include them in the classpath for your application)
you have to put the plugin in a sandbox that prevents compromising critical classes to the other application
And this calls for a customized classloader. But be warned - there are some well hidden pitfalls in implementing that. On the other hand it's a great exercise.
So, take your pick: either quick and dirty or hard but rewarding.
java.io.IOException: CreateProcess: c:/ error=5
at java.lang.Win32Process.create(Native Method)
at java.lang.Win32Process.<init>(Win32Process.java:63)
at java.lang.Runtime.execInternal(Native Method)
If I recall correctly, error code 5 means access denied. This could be because your path is incorrect (trying to execute "c:/") or you are bumping against your OS security (in which case, look at the permissions).
If you are having trouble locating the Java executable, you can usually find it using system properties:
public class LaunchJre {
private static boolean isWindows() {
String os = System.getProperty("os.name");
if (os == null) {
throw new IllegalStateException("os.name");
}
os = os.toLowerCase();
return os.startsWith("windows");
}
public static File getJreExecutable() throws FileNotFoundException {
String jreDirectory = System.getProperty("java.home");
if (jreDirectory == null) {
throw new IllegalStateException("java.home");
}
File exe;
if (isWindows()) {
exe = new File(jreDirectory, "bin/java.exe");
} else {
exe = new File(jreDirectory, "bin/java");
}
if (!exe.isFile()) {
throw new FileNotFoundException(exe.toString());
}
return exe;
}
public static int launch(List<String> cmdarray) throws IOException,
InterruptedException {
byte[] buffer = new byte[1024];
ProcessBuilder processBuilder = new ProcessBuilder(cmdarray);
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
InputStream in = process.getInputStream();
while (true) {
int r = in.read(buffer);
if (r <= 0) {
break;
}
System.out.write(buffer, 0, r);
}
return process.waitFor();
}
public static void main(String[] args) {
try {
Runtime.getRuntime().exec("c:/");
List<String> cmdarray = new ArrayList<String>();
cmdarray.add(getJreExecutable().toString());
cmdarray.add("-version");
int retValue = launch(cmdarray);
if (retValue != 0) {
System.err.println("Error code " + retValue);
}
System.out.println("OK");
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
(Tested Windows XP, Sun JRE 1.6; Ubuntu 8.04, OpenJDK JRE 1.6)
This is the equivalent of running:
java -version
You may also want to look at the "java.library.path" system property (and "path.separator") when trying to locate the executable.
How about just calling the main from your java program?
Test.main(null);
This worked fine for me
Is there any reason you can't just call it directly in your Java code?
If there is a reason I've not tried it for executing a Java Program but you could try Jakarta Commons Exec works well for executing most programs.
I had to do this recently.
Here is how I did it, picking up only the relevant parts:
private static final String[] straJavaArgs =
{
"?i/j2re/bin/java",
"-ms64m",
"-mx64m",
"-Djava.ext.dirs=?i/lib;?i/jar/lib;?i/jar"
};
// ...
// AppDesc appToRun;
List<String> params = new ArrayList<String>();
// Java exe and parameters
params.addAll(ExpandStrings(straJavaArgs));
// Common VM arguments
params.addAll(Arrays.asList(AppDesc.GetCommonVMArgs()));
// Specific VM arguments
params.addAll(ExpandStrings(appToRun.GetVMArgs()));
// The program to run
params.add(appToRun.GetClass());
// Its arguments
params.addAll(ExpandStrings(appToRun.GetProgramArgs()));
// The common arguments
params.addAll(ExpandStrings(AppDesc.GetCommonProgramArgs()));
ProcessBuilder processBuilder = new ProcessBuilder(params);
process = processBuilder.start();
return CaptureProcessOutput(); // Uses a StreamGobbler class
protected ArrayList<String> ExpandStrings(String[] stra)
{
ArrayList<String> alResult = new ArrayList<String>();
for (int i = 0; i < stra.length; i++)
{
// Super flexible, eh? Ad hoc for the current task, at least...
alResult.add(stra[i]
.replaceAll("\\?i", strInstallDir)
.replaceAll("\\?c", strConfigDir)
);
}
return alResult;
}
public enum AppDesc
{
// Enumerate the applications to run, with their parameters
}
Incomplete, if you need more details, just ask.
public class Test {
public static void main(String[] args) throws Exception {
Process p = Runtime.getRuntime().exec("\"c:/program files/windows/notepad.exe\"");
p.waitFor();
}
}
The above works quite well, instead of passing \"c:/program files/windows/notepad.exe\" as the arguments for the executable, use the path to your program, I'm not sure if this solution is JVM version dependent, or if it can use relative paths.
You must pass the path of your executable at the exec method. Are you really trying to execute the "-" process?
Also, have a look at this for some useful tips.
Put ant lib in you classpath ( project lib ) and run this code :
import org.apache.tools.ant.taskdefs.Execute;
Execute exe = new Execute();
exe.setCommandline(new String[]{"java", "-version"});
exe.execute();
I can't remember the exact code that I used to get this to work, but you have to pass "java.exe" (or the equivalent) as the executable, and then the class or jar to run as the parameter, with the correct working directory. So it's not as simple as just calling one method.
I had a similiar problem. I needed to run a section of Java code in a seperate VM as it invoked native code via JNI that occasionally blew up taking out the entire VM.
I cheated a little though. I initially used Runtime to invoke a simple batch command file and put the work-in-progress java command in there. This enabled me to tweak it as needed and to run the command in a DOS prompt for easy testing. Once it was finished I simply copied the result into the Runtime invocation.
First you compile the prog-A code and convert to jar file(ie:In NetBeans Shift-F11)and the path is of netbeans(NetBeansProjects/prog-A/dist/prog-A.jar)
public class ProgA {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Helllo print thr ProgA");
}
}
}
Second open the new project in prog-B and add the libraries, and select the jar and give to the prog-A.jar file and write the two line in your program
public class ProgB {
public static void main(String[] args) {
ProgA progA = new ProgA();
String arg[] = null;
progA.main(arg);
}
}
I agree with Ushsa Varghese, if you just want to run your jar file instead of compiling the .java file that is in the same directory you are executing your application from try the code below. This is the same as executing your java application from the command line so you have to invoke the jvm in order to run your application. Also make sure you have the complete path to your jar file the example below assumes that the jar file is in the same directory as the application that is executing the code below. keep in mind this is system dependent code.
try {
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec("java -jar deleteDriveC.jar");
} catch (IOException ex) {
//jar file doesnt exist
//Logger.getLogger(this.class.getName()).log(Level.SEVERE, null, ex);
}
The answer is simple all you have to do is put the code -
$ process p = Runtime.getRuntime().exec("javac factorial.java"); in the try catch block
The code would look like this -
try
{
process p = Runtime.getRuntime().exec("javac factorial.java");
}
catch(IOException e)
{
e.printStackTrace();
}
Hey I think this should work. Atleast for me it did work

Categories