This question already has answers here:
Different ways of loading a file as an InputStream
(6 answers)
Closed 7 years ago.
In my gradle java project, if I run ./gradlew run -PappArgs="['file.dat']" it is compiled and my app succesfully uses the file located in /src/main/resources/. I have integrated Eclipse with gradle and imported my project into Eclipse. When I run the app in Eclipse with filname specified in the Run Configurations argument list for the project, it fails to find the file.dat with this code:
import java.io.InputStream;
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
final String fileName = args[0];
Scanner scanner = null;
try {
InputStream f = MyClass.class.getResourceAsStream(fileName);
scanner = new Scanner(f, "UTF-8"); // fails here saying f is null
} finally {
if (scanner != null) scanner.close();
}
}
}
Project tree is classic: myproj/src/main/java/MyClass.java, myproj/src/main/resources/file.dat and myproj/src/test/java/MyTest.java.
Both a set back and a blessing from Eclipse: all of your resources (files and pictures included) must be in the Build Path of your project. Ensure that this is indeed the case. If it is still the case, consider not using your method of finding the file to read from: a good old fashion
Scanner in=new Scanner(new File("src/main/resources/file.dat"));
will usually work.I hope this helps, and best of luck to you.
Related
I have a homework and I did it on Linux, Visual Studio Code, and the command line. It was working perfectly fine until I need to debug my code. So I migrated to Windows 10 because I had IntelliJ IDEA installed there. I compiled the code and place the input file "bank.in" in the same folder as the compiled "MyClass.class"
However, when I run the program from IntelliJ, my code catches the exception that it cannot find the file "bank.in" when it is just in the same folder as "MyClass.class".
My method in creating the bank.in was, right clicking the out folder from IntelliJ and adding a new file and adding the bank.in contents from there
I've tried running it through cmd.exe using java MyClass and it works perfectly. No exceptions are caught.
But when run through IntelliJ IDEA, it shows
Cannot find bank.in...
Exiting the program...
This is the part of my code where I input my file.
public void main(String[] args)
{
String fileName = "bank.in";
FileReader bank = null;
BufferedReader bankBuffered = null;
try
{
bank = new FileReader(fileName);
bankBuffered = new BufferedReader(bank);
}
catch(FileNotFoundException f)
{
System.out.printf("%s is not found.%n%n", fileName);
System.out.printf("Exiting the program...%n");
System.exit(0);
}
}
This is my project folder structure
MyProject
-.idea
-encodings.xml
-misc.xml
-modules.xml
-workspace.xml
-out
-MyClass.class
-bank.in
-src
-MyClass.java
When I run it through cmd.exe, it works fine. Is there any workaround through this? Thank you.
This question already has answers here:
Java - mkdir() not writing directory
(2 answers)
Closed 4 years ago.
I used new File(directory).mkdir() to create a new folder.
When i setdirectory = "C:\\Users\\livw\\Desktop\New folder\\5b27233480c016706f62a30a",
it works.
But when i add one more child folder to the directory: directory = "C:\\Users\\livw\\Desktop\\New folder\\5b27233480c016706f62a30a\\Samples",it doesn't create the folder.
How can i fix it?
Short and sweet,
Use mkdirs() instead of mkdir().
Hope it helps
Please in future refer to documentation.
directory = "C:\Users\livw\Desktop\New folder\5b27233480c016706f62a30a"
kindly check the directory address as file separator is not properly given before new Folder
import java.io.File;`
public class FileCreation {
public static void main(String[] args) {
new File("C:\\Users\\Master\\Desktop\\Horse\\demo\\devil").mkdir();
new File("C:\\Users\\Master\\Desktop\\Horse\\demo\\devil"+File.separator+"a").mkdir();
}
}
I want to use matlab function in java application. I create java package from my function by deploytool in matlab. Now, how can i use this package? Can only import the jar file created by deploytool in my java project and use its function?
After a lot of googling, I used this toturial but in the final step, i get error "could not load file".
Also i read about MatlabControl, but in this solution, we should have matlab environment in our system to java code running. But i will run my final app in systems that may not have matlab at all.
So i need a solution to run matlab function in java class even in absence of matlab environment.
Finally I solve my problem. the solution step by step is as follows:
write matlab function:
function y = makesqr(x)
y = magic(x);
Use deploytool in matlab and create java package.
3.create new java application in Eclipse and add main class. import javabuilde.jar and makesqr.jar:
import com.mathworks.toolbox.javabuilder.MWArray;
import com.mathworks.toolbox.javabuilder.MWClassID;
import com.mathworks.toolbox.javabuilder.MWNumericArray;
import makesqr.Class1;
and main.java:
public class main {
public static void main(String[] args) {
MWNumericArray n = null;
Object[] result = null;
Class1 theMagic = null;
try
{
n = new MWNumericArray(Double.valueOf(5),MWClassID.DOUBLE);
theMagic = new Class1();
result = theMagic.makesqr(1, n);
System.out.println(result[0]);
}
catch (Exception e)
{
System.out.println("Exception: " + e.toString());
}
finally
{
MWArray.disposeArray(n);
MWArray.disposeArray(result);
theMagic.dispose();
}
}
}
add javabuilder.jar and makesqr.jar to java build path of your project.
run it.
the Double.valueOf(3), define the input for our function and the output is as follows:
8 1 6
3 5 7
4 9 2
I didn't get properly your problem. Did you already compile the jar file from Matlab code and you are trying to use that, or you are at the last step of the tutorial?
If your answer is the latest case, most probably you forgot the "." before the class path.
From tutorial you linked:
You must be sure to place a dot (.) in the first position of the class path. If it not, you get a message stating that Java cannot load the class.
Also check if the matlab compiler path ("c:\Program Files\MATLAB\MATLAB Compiler Runtime\v82\toolbox\javabuilder\jar\javabuilder.jar" - in the tutorial) is correct for your system.
I ran into library loading problems after creating a jar from my code via maven. I use intelliJ idea on Ubuntu. I broke the problem down to this situation:
Calling the following code from within idea it prints the path correctly.
package com.myproject;
public class Starter {
public static void main(String[] args) {
File classpathRoot = new File(Starter.class.getResource("/").getPath());
System.out.println(classpathRoot.getPath());
}
}
Output is:
/home/ted/java/myproject/target/classes
When I called mvn install and try to run it from command line using the following command I'm getting a NullPointerException since class.getResource() returns null:
cd /home/ted/java/myproject/target/
java -cp myproject-0.1-SNAPSHOT.jar com.myproject.Starter
same for calling:
cd /home/ted/java/myproject/target/
java -Djava.library.path=. -cp myproject-0.1-SNAPSHOT.jar com.myproject.Starter
It doesn't matter if I use class.getClassLoader().getRessource("") instead. Same problem when accessing single files inside of the target directory instead via class.getClassLoader().getRessource("file.txt").
I want to use this way to load native files in the same directory (not from inside the jar). What's wrong with my approach?
The classpath loading mechanism in the JVM is highly extensible, so it's often hard to guarantee a single method that would work in all cases. e.g. What works in your IDE may not work when running in a container because your IDE and your container probably have highly specialized class loaders with different requirements.
You could take a two tiered approach. If the method above fails, you could get the classpath from the system properties, and scan it for the jar file you're interested in and then extract the directory from that entry.
e.g.
public static void main(String[] args) {
File f = findJarLocation("jaxb-impl.jar");
System.out.println(f);
}
public static File findJarLocation(String entryName) {
String pathSep = System.getProperty("path.separator");
String[] pathEntries = System.getProperty("java.class.path").split(pathSep);
for(String entry : pathEntries) {
File f = new File(entry);
if(f.getName().equals(entryName)) {
return f.getParentFile();
}
}
return null;
}
I'm following along the Basic I/O Tutorial on Oracle.com, but I'm having difficulty making a Path object:
Path p1 = Paths.get("/tmp/foo");
Which gives the error:
error: The method get(URI) in the type Paths is not applicable for the arguments (String).
I'm on Linux and I'm working in Eclipse Kepler. I'm trying to access a text file in the current directory. Using Scanner and File I can work with the file, but I'd also like to fiddle around with a path to the file so I can continue with the tutorial.
edit: The entirety of the program is below. The second half is me being a rookie and confirming the file exists/works. When I comment out the Path definitions, I get the output of "Test" which is in the 'save.txt' file.:
package projectSARA;
import java.util.*;
import java.io.*;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) {
String saveFile = "save.txt";
Path p1 = Paths.get(saveFile);
Path p2 = Paths.get("save.txt");
File file = new File(saveFile);
try{
Scanner in = new Scanner(file);
String test = in.next();
System.out.println(test);
}
catch(FileNotFoundException e){
System.out.println("File not found");
}
}// end main
}
It appears to be a problem of the (default) JRE settings in Eclipse.
To solve it, in the Package Explorer, right-click the "JRE System Library" > properties.
Select "Execution environment", then select "JavaSE-1.7 (java-7-oracle)", press OK.
It happened to me when creating a new project outside the workspace.
Actually I had the same issue with Oracle Java 8 running on Eclipse. But the solution above didn't help. The solution for me was to simply:
right-click on project in Package Explorer
Select Java Compiler
Enable Project Specific Settings
Set Compiler Compliance Level to 1.7