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
Related
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.
My folder structure is as follows:
>test
>src
>org.mypackage
>myclass
>resources
>config.properties
The java class is as follows:
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public myclass {
private String path = "config.properties";
public myclass() {
Properties prop = new Properties();
InputStream input = null;
try {
input = getClass().getClassLoader().getResourceAsStream(path);
prop.load(input)
}
catch(Exception ex) {
ex.printStackTrace();
}
}
}
But I get null as the value for input during debug.
In the debug mode I checked the value for getClass(), I get the class value, the value is also available for getClass().getClassLoader() but for getClass().getClassLoader().getResourceAsStream(path) it is null.
I am not sure what the issue could be.
Thanks for the help!
It seems that resources is not a source folder in your Eclipse project. Try setting resources as a source folder:
Right click > Build Path > Use as Source Folder
You should check this question right here, which should help you in answering your problem: How to add a Java Properties file to my Java Project in Eclipse
Moreover, it seems to me that your project isn't 100% Maven compliant. You should have something more like:
>src
>main
>java
>resources
>test
>java
>resources
Then Eclipse should be less lost when handling and loading your properties.
If you have any questions, feel free message me
I have a macbook and our school told us to use TextMate if we don't have a pc. I can do this in a pc, but I'm having trouble with the syntax in a mac OS since they are different. This is what I'm using and even though I created a file named Data.txt, the prompt that pops up says it doesn't exist.
import java.io.File;
class FileClassTutorial
{
public static void main(String[]args)
{
File x= new File("MacintoshHD/Users/Alexis/Desktop/Data.txt");
if(x.exists())
System.out.println(x.getName() + " exists!!!");
else
System.out.println("This file doesn't exist");
}
}
new File("something/other") is assumed to be "./something/other" where '.' is the current working directory where jvm is started. It's what you need ?
Otherwise, you can start a path by '/' to have an absolute path from super-root of your file disk
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.
So my 2009 new years resolution is to learn Java. I recently acquired "Java for Dummies" and have been following along with the demo code in the book by re-writing it using Eclipse. Anyway, every example in the book that uses a relative path does not seem to read the .txt file it's supposed to read from.
Here is the sample code:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.GridLayout;
class TeamFrame extends JFrame {
public TeamFrame() throws IOException {
PlayerPlus player;
Scanner myScanner = new Scanner(new File("Hankees.txt"));
for (int num = 1; num <= 9; num++) {
player = new PlayerPlus(myScanner.nextLine(), myScanner.nextDouble());
myScanner.nextLine();
addPlayerInfo(player);
}
add(new JLabel());
add(new JLabel(" ------"));
add(new JLabel("Team Batting Aberage:"));
add(new JLabel(PlayerPlus.findTeamAverageString()));
setTitle("The Hankees");
setLayout(new GridLayout(11,2));
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
void addPlayerInfo(PlayerPlus player) {
add(new JLabel(player.getName()));
add(new JLabel(player.getAverageString()));
}
}
And you can see in the below screen shot I have included this file.
image no longer available
Also, I have verified that when I build the application that a copy of Hankees.txt is placed in the bin folder with the compiled .class files.
Lastly, if I change line 12 to the following and place Hankees.txt in the root of my C:\ drive the program compiles and runs fine.
Scanner myScanner = new Scanner(new File("C:\\Hankees.txt"));
So basically, my question is what am I doing wrong? Or is Eclipse responsible for this in some way?
Thanks for any and all help!
You need "src/Hankees.txt"
Your file is in the source folder which is not counted as the working directory.\
Or you can move the file up to the root directory of your project and just use "Hankees.txt"
A project's build path defines which resources from your source folders are copied to your output folders. Usually this is set to Include all files.
New run configurations default to using the project directory for the working directory, though this can also be changed.
This code shows the difference between the working directory, and the location of where the class was loaded from:
public class TellMeMyWorkingDirectory {
public static void main(String[] args) {
System.out.println(new java.io.File("").getAbsolutePath());
System.out.println(TellMeMyWorkingDirectory.class.getClassLoader().getResource("").getPath());
}
}
The output is likely to be something like:
C:\your\project\directory
/C:/your/project/directory/bin/
This is really similar to another question.
How should I load files into my Java application?
How should I load my files into my Java Application?
You do not want to load your files in by:
C:\your\project\file.txt
this is bad!
You should use getResourceAsStream.
InputStream inputStream = YourClass.class.getResourceAsStream(“file.txt”);
And also you should use File.separator; which is the system-dependent name-separator character, represented as a string for convenience.
Yeah, eclipse sees the top directory as the working/root directory, for the purposes of paths.
...just thought I'd add some extra info. I'm new here! I'd like to help.
You can always get your runtime path by using:
String path = new File(".").getCanonicalPath();
This provides valuable information about where to put files and resources.
Paraphrasing from http://java.sun.com/javase/6/docs/api/java/io/File.html:
The classes under java.io resolve relative pathnames against the current user directory, which is typically the directory in which the virtual machine was started.
Eclipse sets the working directory to the top-level project folder.