How to create executable file in Java using Netbeans - java

I made a cache simulator program for a homework, I decided to use java. I want to create an executable jar file that will work on any system, but the problem is that my program gathers data from an external text file. How can I include that text file inside the jar so that there won't be any problem when executing file? By the way, I am using NetBeans IDE.

If you don't need to write to the file, copy into the src directory. You will no longer be able to access like a File, but instead will need to use Class#getResource, passing it the path from the top of the source tree to where the file is stored.
For example, if you put it in src/data, then you'd need to use getClass().getResource("/data/..."), passing it what ever name the file is...
Clean and build...

Yes and I said Yes. To really make your jarfiles along with the text files. Please ensure that links to the folder on which the text files is where properly coded and well linked.
The three Examplary Method below should get you working irrespective of any IDEs. Please rate this and give me a shout if you still need further help.......Sectona
Method 1
Step 1:- Locate your folder that contain your java file by using cd command.
Step 2:- Once your enter your folder location then view your java file by dir
command.
Step 3:- Compile your java file using
javac file.java
Step 4:- view class file by type dir command.
Step 5:- Now you want to create a manifest file.
I)Go to folder<br>
II)Right-click->New->Text Document
III)open text document. Type main class name ,
Main-Class: main-class-name
IV)Save this file your wish like MyManifest.txt
Step 6:- To create executable jar file type
jar cfm JarFileName.jar MyManifest.txt JavaFike1.class JavaFile2.class
Step 7:- Now you see the Executable jar file on your folder. Click the file to
Run.
Step 8:- To run this file via command prompt then type
java -jar JarFileName.jar
Step 9:- You done this..........Sectona
Method 2
The basic format of the command for creating a JAR file is:
jar cf jar-file input-file(s)
The options and arguments used in this command are:
The c option indicates that you want to create a JAR file.
The f option indicates that you want the output to go to a file rather than to stdout.
jar-file is the name that you want the resulting JAR file to have. You can use any filename for a JAR file. By convention, JAR filenames are given a .jar extension, though this is not required.
The input-file(s) argument is a space-separated list of one or more files that you want to include in your JAR file. The input-file(s) argument can contain the wildcard * symbol. If any of the "input-files" are directories, the contents of those directories are added to the JAR archive recursively.
Method 3
import java.io.*;
import java.util.jar.*;
public class CreateJar {
public static int buffer = 10240;
protected void createJarArchive(File jarFile, File[] listFiles) {
try {
byte b[] = new byte[buffer];
FileOutputStream fout = new FileOutputStream(jarFile);
JarOutputStream out = new JarOutputStream(fout, new Manifest());
for (int i = 0; i < listFiles.length; i++) {
if (listFiles[i] == null || !listFiles[i].exists()|| listFiles[i].isDirectory())
System.out.println();
JarEntry addFiles = new JarEntry(listFiles[i].getName());
addFiles.setTime(listFiles[i].lastModified());
out.putNextEntry(addFiles);
FileInputStream fin = new FileInputStream(listFiles[i]);
while (true) {
int len = fin.read(b, 0, b.length);
if (len <= 0)
break;
out.write(b, 0, len);
}
fin.close();
}
out.close();
fout.close();
System.out.println("Jar File is created successfully.");
} catch (Exception ex) {}
}
public static void main(String[]args){
CreateJar jar=new CreateJar();
File folder = new File("C://Answers//Examples.txt");
File[] files = folder.listFiles();
File file=new File("C://Answers//Examples//Examples.jar");
jar.createJarArchive(file, files);
}
}

You can keep any file in classpath and read as class path resource. Sample code is given below.
InputStream in = this.getClass().getClassLoader().getResourceAsStream("yourinputFile.txt");
Your jar will be class path, that means you can keep your file in root folder of java source which will get added to jar file while building it.

Related

java - reading config file in same directory as jar file

I have a simple program in Intellij that I made just to test out reading file path of config file.
I created a simple test case where I would use a timer to print "Hello world" periodically in N intervals where N is in milliseconds and N is configurable.
This is the code:
public void schedule() throws Exception {
Properties props=new Properties();
String path ="./config.properties";
FileInputStream fis=new FileInputStream(path);
BufferedReader in1=new BufferedReader(new InputStreamReader(fis));
// InputStream in = getClass().getResourceAsStream("/config.properties");
props.load(in1);
in1.close();
int value=Integer.parseInt(props.getProperty("value"));
Timer t=new Timer();
t.scheduleAtFixedRate(
new TimerTask() {
#Override
public void run() {
// System.out.println("HELEOELE");
try {
// test.index();
System.out.println("hello ");
} catch (Exception e) {
e.printStackTrace();
}
}
},
0,
value);
}
What I did was I set value as N in a config file where it can be changed by anyone without touching the actual code. So I compiled the jar file, and I placed both config.properties and jar file in same folder or directory. I want to be able to change make N changeable so I don't need to re-compile the jar again and again everytime.
Note: the config properties file is created manually and placed in same directory as the jar. And I am executing the jar in command prompt.
However, it seems when I try to run it, it doesn't recognize the file path.
"main" java.io.FileNotFoundException: .\config.properties (The system cannot find the file specified)
I've looked into many issues regarding reading config files outside of jar file and none of them worked for me. Am I doing any mistake here?
./config.properties is a relative path that points to a config.properties file in the current working directory.
The current working directory, unless changed by System.setProperty("user.dir", newPath), will be the directory from which you launched the JVM currently handling your code.
To get your jar to work as it currently is, you have two ways available :
copy the config.properties file to the directory you are executing java from
change the directory you are running java from to the one that contains the config.properties
You may also consider letting the user specify where to get the properties file from :
String path = System.getProperty("propertiesLocation", "config.properties");
You would then be able to specify a location for the property file when calling your jar :
java -jar /path/to/your.jar -DpropertiesLocation=/path/to/your.properties
Or call it as you did before to search for the properties at its default location of config.properties in the current working directory.

Inputting file name through main function argument (args[0])

EDIT: to run my code i am using "java filename.java input1.txt" is this correct?
I am creating a program where i have to tokenize a string into separate words and that string is in a text file. I have to specify the text file name in the terminal through command line arguments (args[0], etc). I am able to scan and print the content of the text file if i specify through paths but when i try to do it using args[0] it doesn't seem to work. I am using net beans. I will attach my section of code here:
public static void main(String[] args) {
try {
File f = new File(args[0]);
//using this commented out section using paths works File f = new
//File("NetBeansProjects/SentenceUtils/src/input1.txt");
Scanner input = new Scanner(new FileInputStream(f));
while(input.hasNext()) {
String s = input.next();
System.out.println(s);
}
} catch(FileNotFoundException fnfe) {
System.out.println("File not found");
}
SentenceUtils s = new SentenceUtils();
}
java filename.java input1.txt
is not correct for running a java program, you need to compile the *.java file to get a *.class file which you can then run like:
java filename input1.txt
assuming your class is in the default package and you are running the command in the output directory of your compile command, or using the fully qualified class name of the class, i.e. including the package name. For example if your class is in the package foo/bar/baz (sub folders in your source folder) and has the package declaration package foo.bar.baz;, then you need to specify your class like this:
java [-cp your-classpath] foo.bar.baz.filename input1.txt
for input1.txt to be found it has to be in the same directory where you run the command.
your-classpath is a list of directories separated by a system dependent delimiter (; for windows, : for linux, ...) or archives which the java command uses to look up the class to run specified and its dependencies.
NetBeansProjects/SentenceUtils/src/input1.txt is a relative path.
File f = new File("NetBeansProjects/SentenceUtils/src/input1.txt");
if this works then it means that the current working directory (i.e. the directory from which all relative paths are calculated) is the the rectory named NetBeansProjects.
You get FileNotFoundException because your file is expected to be in
NetBeansProjects/input1.txt
To find out which is the current working directory for your running program you can add the following statement:
System.out.println(new File("").getAbsolutePath());
Place input.txt in that directory and it will be found.
Alternatively you can pass the absolute path of your input file. an absolute path is a path that can be used to locate your file from whatever location your program is running from on your local filesystem. For example:
java -cp <your-classpath> <fully-qualified-name-of-class> /home/john/myfiles/myprogects/...../input1.txt
To sum up, what you need to know/do is the following:
the location of your program class and its package (filename)
the location of your input file (input.txt)
pass the correct argument accordingly

Runnable JAR file not found exception

I would like to know how to create a runnable JAR with resources (pictures, pdfs) in a resource folder either inside or outside the source package (ie /src/resources/images/ or /resources/images/) in Eclipse. Currently, i have my resources inside the source folder of my eclipse project, but I've also tried it inside its own folder in the package. The program builds and executes fine in eclipse, but when I go to export as a runnable jar, I keep getting a file not found exception when I run it on the desktop. I'm declaring my files with a string like this
private String file = "src/resources/orderForm.pdf";
I understand that I should user getResourceAsStream(), but due to some constraints, I can't (has to do with how files are saved, I'm reading in whole pdf files, not as streams) so I'm wondering how to get my files into the correct location in the jar. If i unpack it after I've made it they always show up in the top level, outside of the folders. Here is a screen shot of my current project structure. For the sake of saying it, this project works fine in eclipse, also in the java build properties, the source folder is in the build path along with all subfolders, I also tried doing the same with the empty resources folder in an earlier test.
You will need to do the getResourceAsStream, and make sure that the pdfs get built into the jar. Since you have them in the source folder, they should.
Assuming you have the pdf under src/resources/orderForm.pdf, it will end up in the jar file as /resources/orderForm.pdf. You would open a resource stream for /resources/orderForm.pdf.
If you must have a honest to goodness file, then you would need code that reads the PDF as a resource stream, FileOutputStreams it out to a temp file, then uses the file. Or, you simply cannot package the pdfs in the jar.
public class PDFWriter {
public static final String testDir = "C:\\pdftest\\";
public static final String adobePath = "\"C:\\Program Files\\Adobe\\Reader 10.0\\Reader\\AcroRd32.exe\"";
public static void main(String[] args){
try {
new PDFWriter().run();
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() throws Exception {
InputStream in = this.getClass().getResourceAsStream("/resources/test.pdf");
new File(testDir).mkdirs();
String pdfFilePath = testDir + "test.pdf";
FileOutputStream out = new FileOutputStream (pdfFilePath);
byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
out.write(buffer, 0, len);
len = in.read(buffer);
}
out.close();
Runtime rt = Runtime.getRuntime();
String command = adobePath + " " + pdfFilePath;
rt.exec(command);
}
}
The only reason the file way works at all in eclipse is because the bin folder is a real folder, but when you build the thing, it all gets zipped up into a jar.
Maybe a bit of confusion over source folders. If you have a source folder called 'src', the package structure under it does not contain "src". src/net/whatever/Class.java will turn into net/whatever/Class.class when build.
So, you could create a second source folder called 'rsrc' (resources), and under this put your resources/order.pdf. rsrc/resources/order.pdf will become resources.order.pdf when you build the jar.
For the sake of easy exporting from Eclipse without constantly thinking about it, I recommend putting the resources folder under the src folder. Long story short, if you don't put it in your src folder, every time you create a jar, you will need to check the box next to the resources folder. So just put it in the src folder and save yourself some problems.
As for referrencing the files, I would try
private String file = "resources/finished.pdf";
This allows you to access the file under src/resources/finished.pdf.

java.io.FileNotFoundException (File not found) using Scanner. What's wrong in my code?

I've a .txt file ("file.txt") in my netbeans "/build/classes" directory.
In the same directory there is the .class file compiled for the following code:
try {
File f = new File("file.txt");
Scanner sc = new Scanner(f);
}
catch (IOException e) {
System.out.println(e);
}
Debugging the code (breakpoint in "Scanner sc ..") an exception is launched and the following is printed:
java.io.FileNotFoundException: file.txt (the system can't find the
specified file)
I also tried using "/file.txt" and "//file.txt" but same result.
Thank you in advance for any hint
If you just use new File("pathtofile") that path is relative to your current working directory, which is not at all necessarily where your class files are.
If you are sure that the file is somewhere on your classpath, you could use the following pattern instead:
URL path = ClassLoader.getSystemResource("file.txt");
if(path==null) {
//The file was not found, insert error handling here
}
File f = new File(path.toURI());
The JVM will look for the file in the current working directory.
Where this is depends on your IDE settings (how your program is executed).
To figure out where it expects file.txt to be located, you could do
System.out.println(new File("."));
If it for instance outputs
/some/path/project/build
you should place file.txt in the build directory (or specify the proper path relative to the build directory).
Try:
File f = new File("./build/classes/file.txt");
Use "." to denote the current directory
String path = "./build/classes/file.txt";
File f = new File(path);
File Object loads, looking for match in its current directory.... which is Directly in Your project folder where your class files are loaded not in your source ..... put the file directly in the project folder

Reading .txt file from another directory

The code I am running is in /Test1/Example. If I need to read a .txt file in /Test1 how do I get Java to go back 1 level in the directory tree, and then read my .txt file
I have searched/googled and have not been able to find a way to read files in a different location.
I am running a java script in an .htm file located at /Test1/Test2/testing.htm. Where it says script src=" ". What would I put in the quotations to have it read from my file located at /Test1/example.txt.
In Java you can use getParentFile() to traverse up the tree. So you started your program in /Test1/Example directory. And you want to write your new file as /Test1/Example.txt
File currentDir = new File(".");
File parentDir = currentDir.getParentFile();
File newFile = new File(parentDir,"Example.txt");;
Obviously there are multiple ways to do this.
You should be able to use the parent directory reference of "../"
You may need to do checks on the OS to determine which directory separation you should be using ['\' compared to '/']
When you create a File object in Java, you can give it a pathname. You can either use an absolute pathname or a relative one. Using absolutes to do what you want would require:
File file = new File("/Test1/myFile.txt");
if(file.canRead())
{
// read file here
}
Using relatives paths if you want to run from the location /Test1/Example:
File file = new File("../myFile.txt");
if(file.canRead())
{
// read file here
}
I had a similar experience.
My requirement is: I have a file named "sample.json" under a directory "input", I have my java file named "JsonRead.java" under a directory "testcase". So, the entire folder structure will be like untitled/splunkAutomation/src and under this I have folders input, testcase.
once after you compile your program, you can see a input file copy named "sample.json" under a folder named "out/production/yourparentfolderabovesrc/input" and class file named "JsonRead.class" under a folder named "out/production/yourparentfolderabovesrc/testcase". So, during run time, Java will actually refer these files and NOT our actual .java file under "src".
So, my JsonRead.java looked like this,
package testcase;
import java.io.*;
import org.json.simple.JSONObject;
public class JsonRead{
public static void main(String[] args){
java.net.URL fileURL=JsonRead.class.getClass().getResource("/input/sample.json");
System.out.println("fileURL: "+fileURL);
File f = new File(fileURL.toURI());
System.out.println("fileIs: "+f);
}
}
This will give you the output like,
fileURL: file:/C:/Users/asanthal/untitled/out/production/splunkAutomation/input/sample.json
fileIs: C:\Users\asanthal\untitled\out\production\splunkAutomation\input\sample.json
It worked for me. I was saving all my classes on a folder but I needed to read an input file from the parent directory of my classes folder. This did the job.
String FileName = "Example.txt";
File parentDir = new File(".."); // New file (parent file ..)
File newFile = new File(parentDir,fileName); //open the file

Categories

Resources