Reputation: 1298
I have a very simple .java
file in Eclipse Java Project that creates a .txt
file.
package mproject.assgn.q12;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class ColumnPattern {
public static void main(String[] args) {
System.out.println(getInputFile().getAbsolutePath());
}
private static File getInputFile() {
String content = "110\t100\t255\t122\n"
+ "100\t109\t180\t111\n"
+ "22\t101\t122\t110\n"
+ "211\t122\t177\t101";
File file = new File("file2.txt");
try {
if(!file.exists()){
System.out.println("Creating Input File since it does'nt exist");
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.flush();
bw.close();
return file;
}
catch(IOException e){
e.printStackTrace();
System.err.println("Error during File I/O");
}
return null;
}
}
What I want to know is why the file that is created is found under /projectFolder/
, while the .java resides in /projectName/src
and the class file resides in /projectFolder/bin
. Shouldn't the text file be created under the /bin folder where the .class file resides ?
How does eclipse execute the .java file when we select "Run As Java Application
" ?
Does it compile it to a jar and then execute it ?
Upvotes: 3
Views: 107
Reputation: 32984
When you create a file with the java.io.File
with the String
constructor like that, the path is relative to the current working directory from which the application is run. When you select Run As > Java Application in Eclipse, the default working directory is the project root, which explains why your file is created there.
You can easily change the working directory for an application you launch from Eclipse: open the Run Configurations (or Debug Configurations) dialog (from either the toolbar buttons for Run/Debug or the Run menu), select the launch configuration for your application, then go to the Arguments tab. Near the bottom you'll see the section to select a Working directory.
Upvotes: 2
Reputation: 145
Why the text file is not under /bin
Eclipse creates hidden by default project files - .project. The directory where this file is created is considered the root directory for the project. When using relative file paths, they are always resolved against the project root.
How does Eclipse run the application
Eclipse compiles the classes under /bin (unless specified otherwise) and executes the class with main
method. Considering you have more than one class with a main method, you have to choose after selecting Run As Java Application
.
Also, a side note regarding the jar files - those are just archives containing classes and other files. When executing a jar file, you are basically executing the main method of the main class, declared in the META-INF/Manifest.mf
file.
Upvotes: 2