im Working on a project that can compile/run existing java files in PC.
most of code works pretty well, but im having a problem at getting the path of java files.
here are the problematic codes
void uploadJ() {
System.out.print("Insert File name : "); //ex)HelloWorld.java
FileName = sc.next();
}
void Compile(){
String s = null;
File file = new File(FileName);
String path = file.getAbsolutePath();
try {
Process oProcess = new ProcessBuilder("javac", path).start();
BufferedReader stdError = new BufferedReader(
new InputStreamReader(oProcess.getErrorStream()));
while ((s = stdError.readLine()) != null) {
FileWriter fw = new FileWriter(E_file, true);
fw.write(s);
fw.flush();
fw.close();
}
} catch...
}
For instance, when i put HelloWorld.java as a file name,
the absolute path of the HelloWorld.java should be C:\Users\user\eclipse-
workspace\TermProject\src\HelloWorld.java,
but instead, the result is C:\Users\user\eclipse-
workspace\TermProject\HelloWorld.java.
it misses /src/ so it always ends up with javac: file not found error.
When your application has been compiled, there will be no src directory. This working directory could also be set to anything.
You also can't guarantee that the file you are looking for is an actual file, in the context of a jar file, it isn't.
However, you can load files from the classpath. You can make use of Class#getResourceAsStream(String):
Finds a resource with a given name. The rules for searching resources associated with a given class are implemented by the defining class loader of the class.`.
Finding the file can be accomplished by calling this.getClass().getResourceAsStream("/" + FileName), with the / causing the search to occur from the resource root.
To use this with javac, you'll have to create a temporary file and populate it with the data stream you get from getResourceAsStream.
Related
This is the path I'm using now:
C:\Users\Sabrina\Documents\NetBeansProjects\TriangleSumRecursion\lab4Data.txt
I tried just using the following:
C:\TriangleSumRecursion\lab4Data.txt
and
TriangleSumRecursion\lab4Data.txt
If I use either of those two Java will say "(The system cannot find the file specified)"...
TriangleSumRecursion is the java package that I'll turn in.
You can import the particular file into the project, and then try using TriangleSumRecursion\lab4Data.txt
You can import the file by right clicking on your project folder from your IDE, and then click on import. Follow the instructions and give the path of your file in it.
i hope it works for you.
First of all, use Slashes ('/'), not Backslashes ('\') in Javacode.
But besides of that, Java can handle absolute and relative paths.
I tried just using the following: C:\TriangleSumRecursion\lab4Data.txt
This is not the right absolute path, if there is no folder 'TriangleSumRecursion' in C:\. Your working path example is the only right one.
and TriangleSumRecursion\lab4Data.txt
Here you try this as a relative path. Java starts its search in the folder your file, running the code, is located. So this would work, if your java file was in 'C:\Users\Sabrina\Documents\NetBeansProjects'.
But since I think your file is in 'TriangleSumRecursion', the path you are looking for is simply 'lab4Data.txt'.
You could try the following reading your file line by line, by first reading the file through a file reader, that is then fed to the buffered reader. Then you can create a string buffer, and as the program reads each line of the file it will append it to the string buffer. To check if it was successful just simply close the file reader and use the toString() method to display the contents of the file.
`public static void main(String[] args) {
try {
File file = new File("lab4Data.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("File is:");
System.out.println(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}`
C:\TriangleSumRecursion\lab4Data.txt is an absolute path, so this will not identify your file which is not at this location.
You are more than probably in directory C:\Users\Sabrina\Documents\NetBeansProjects\TriangleSumRecursion, therefore a simple:
Paths.get("lab4Data.txt")
will give you a Path to your file (this is 2015; use java.nio.file and drop File).
But this is Windows and there are some strange things with Windows... Another way to access your file would be:
Paths.get("c:lab4data.txt")
Which is a path which has a root (c:) but which is not absolute (since such a path cannot be used to uniquely identify a resource on the FileSystem.
See the Files class on how to open, for instance, an InputStream or a BufferedReader from this file. And note that if the file does not exist the matching methods will throw a NoSuchFileException.
Last but not least, use a try-with-resources statement:
try (
final BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
) {
// use the reader here
}
I have a program that uses a file named list.txt to populate an ArrayList with its contents and then get a random line.
Here's the part that loads the file:
public class ReadList {
private Scanner f;
public void openFile(){
try{
f = new Scanner(new File("list.txt"));
}catch(Exception e){
System.out.println("File not found!");
}
}
However, it doesn't work when running it from a .jar file. I put the txt in the same directory and used f = new Scanner(new File("./list.txt")); yet it didn't work. I also tried some stuff I have found online but all I could manage to do is a) get a full path of the .jar with .jar included(/home/user/java/program.jar), and b) get a full path of the directory but without the / at the end(/home/user/java), which is a problem since I want this program to work on both Windows and Linux, therefore I can't simply do ("/home/user/java" + "/list.txt"), since Windows uses backslashes in paths.
So what's the simple way to just target the specific file(which will always be called list.txt) no matter which directory the file's in, as long as it's in the same place as the .jar?
Use this:
String filePath = System.getProperty("user.dir") + File.separator + "file.txt";
filePath will now contain the full path of file.txt which will be in the same dir as your jar.
I am trying to read a .json file I am packaging with my .jar.
The problem - finding the file so that I can parse it in.
The strange bit is that this code works in NetBeans, likely due to the way these methods work and the way NetBeans handles the dev workspace. When I build the jar and run it, however, it throws an ugly error: Exception in thread "main" java.lang.IllegalArgumentException: URI is not hierarchical.
My code for getting the file is as such:
//get json file
File jsonFile = new File(AndensMountain.class.getResource("/Anden.json").toURI());
FileReader jsonFileReader;
jsonFileReader = new FileReader(jsonFile);
//load json file
String json = "";
BufferedReader br = new BufferedReader(jsonFileReader);
while (br.ready()) {
json += br.readLine() + "\n";
}
I have gotten it to work if I allow it to read from the same directory as the jar, but this is not what I want - the .json is in the jar and I want to read it from in the jar.
I've looked around and as far as I can see this should work but it isn't.
If you are interested, this is the code before trying to get it to read out of the jar (which works as long as Anden.json is in the same directory as AndensMountain.jar):
//get json file
String path = AndensMountain.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
File jsonFileBuilt = new File(new File(path).getParentFile(), "Anden.json");
File jsonFileDev = new File(new File(path), "Anden.json");
FileReader jsonFileReader;
try {
jsonFileReader = new FileReader(jsonFileBuilt);
} catch (FileNotFoundException e) {
jsonFileReader = new FileReader(jsonFileDev);
}
Try
Reader reader = new InputStreamReader(AndensMountain.class.getResourceAsStream("/Anden.json"), "UTF-8");
AndensMountain.class.getResource("/Anden.json") URL when ran outside a jar (for example, when the classes are compiled to a "classes/" directory) is a "file://" URL.
That is not the case when ran from inside a jar: it then becomes a "jar://" URL.
The java.io.File doesn't know how to handle this type of URL. It handles only "file://".
Anyway you don't really need to treat it as a File. You can manipulate the URL itself (either to navigate to a parent directory, for example) or to get its contents (via openStream(), or if you need to add headers, via openConnection()).
java.lang.Class#getResourceAsStream() as I suggested is just shorthand to Class#getResource() followed by openStream() on its result.
I'm trying to use a local file in which I've specified my db connection properties which is named dao.properties. And I'm proceeding this way:
InputStream fichierProperties = classLoader.getResourceAsStream( "/src/dao/dao.properties" );
However, when using this path, I'm getting an exception stating that the debugger wasn't able to find that file.
Here are some packages in my project:
The dao.properties is just under the dao package.
How do I resolve this, please?
If you put the file inside the src folder, the IDE probably is packaging, when instructed to compile and build, the file into the bundled generated jar. So you can reach with the method GetResourceAsStream.
So if you put the file (dao.properties) in root folder of your sources files (generally the src folder), just simple referring to dao.properties will refer to the resource.
If you put the file inside a subfolder of src, the correct way to reference it would be subfolder/dao.properties.
The first "/" is not necessary as the getResourceAsStream always search in the classpath, that for default is the root of the sources folder, inside the jar. (where are not talking about external files!)
Updated:
Assuming you place a file name notes.txt inside a folder(package) named ´sub´, this is valid example, only for purporses of how to get a bundled file that is in jar.
public class Main {
public static void main (String[] args) throws IOException {
InputStream is = Main.class.getResourceAsStream("sub/notes.txt");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
while (s != null) {
System.out.println (s);
s = br.readLine();
}
is.close();
}
}
I add more information about this, by referring to this post
I am making a program that opens and reads a file.
This is my code:
import java.io.*;
public class FileRead{
public static void main(String[] args){
try{
File file = new File("hello.txt");
System.out.println(file.getCanonicalPath());
FileInputStream ft = new FileInputStream(file);
DataInputStream in = new DataInputStream(ft);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strline;
while((strline = br.readLine()) != null){
System.out.println(strline);
}
in.close();
}catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
but when I run, I get this error:
C:\Users\User\Documents\Workspace\FileRead\hello.txt
Error: hello.txt (The system cannot find the file specified)
my FileRead.java and hello.txt where in the same directory that can be found in:
C:\Users\User\Documents\Workspace\FileRead
I'm wondering what I am doing wrong?
Try to list all files' names in the directory by calling:
File file = new File(".");
for(String fileNames : file.list()) System.out.println(fileNames);
and see if you will find your files in the list.
I have copied your code and it runs fine.
I suspect you are simply having some problem in the actual file name of hello.txt, or you are running in a wrong directory. Consider verifying by the method suggested by #Eng.Fouad
You need to give the absolute pathname to where the file exists.
File file = new File("C:\\Users\\User\\Documents\\Workspace\\FileRead\\hello.txt");
In your IDE right click on the file you want to read and choose "copy path"
then paste it into your code.
Note that windows hides the file extension so if you create a text file "myfile.txt" it might be actually saved as "myfile.txt.txt"
Generally, just stating the name of file inside the File constructor means that the file is located in the same directory as the java file. However, when using IDEs like NetBeans and Eclipse i.e. not the case you have to save the file in the project folder directory. So I think checking that will solve your problem.
How are you running the program?
It's not the java file that is being ran but rather the .class file that is created by compiling the java code. You will either need to specify the absolute path like user1420750 says or a relative path to your System.getProperty("user.dir") directory. This should be the working directory or the directory you ran the java command from.
First Create folder same as path which you Specified. after then create File
File dir = new File("C:\\USER\\Semple_file\\");
File file = new File("C:\\USER\\Semple_file\\abc.txt");
if(!file.exists())
{
dir.mkdir();
file.createNewFile();
System.out.println("File,Folder Created.);
}
When you run a jar, your Main class itself becomes args[0] and your filename comes immediately after.
I had the same issue: I could locate my file when provided the absolute path from eclipse (because I was referring to the file as args[0]). Yet when I run the same from jar, it was trying to locate my main class - which is when I got the idea that I should be reading my file from args[1].