I have a java project this project has a text file to read from. i want to export a excuteable jar file .
i did it but when i run the program on cmd window it says that the file couldnt be found.
How to export the whole project inclusive the text file ? or should i place the file in another place
scn = new Scanner(new File("src/test.txt"));
while(scn.hasNext())
{
String instructionLine = scn.next();
li.add(instructionLine) ;
}
scn.close();
}
catch(Exception e)
{
System.out.print("File couldnt found !");
}
You need to use getResourceAsStream() to get data from within your jar file.
See this "prior answer on StackOverflow".
Related
So, my I have a method that saves some data in a properties file but something weird happens. See, lets say I have the JAR file on desktop. If I open it directly from there (double click, etc) the properties file is saved in the desktop, as should be. However, if you drag the JAR to the Windows start list and open it from there, the properties file will be saved in the System32 folder.
Here is the method:
private void saveAncientsData() {
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream("ancients.data");
File file = new File("ancients.data");
// set the properties value
for (int x = 0; x < currentLvlSpinnerFields.size(); x++) {
prop.setProperty(ancientNames[x], currentLvlSpinnerFields.get(ancientNames[x]).getValue().toString());
}
// save properties to project root folder
prop.store(output, null);
JOptionPane.showMessageDialog(this, "Data successfully saved in \n\n" + file.getCanonicalPath(), "Saved", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Would appreciate any help, since I am clueless.
Thanks in advance!
according to your code you haven't give path of property file to create in desktop.
output = new FileOutputStream("ancients.data");
so your property file will be created in same directory where your jar file exists .
but if you run this .jar file from a parent process your jar file created in the directory where that parent process exists.
i guess when windows starts a specific process exist in win32 directory execute start-up programs .i think it's userinit.exe . so your prop file will be created in System32 directory .
if you want property file to create in desktop you can put your jar file in desktop and add a shortcut to .jar or you can give full-path to your desktop like
output = new FileOutputStream(System.getProperty("user.home") + "/Desktop/"+"ancients.data");
edit
to understand this problem
1) create a folder named example in desktop.and then create 2 folders path1 and path2 .then add .jar to path1 folder
2) double click jar in path1 .and a property file will be created in path1 as you expected .
3) delete property file.open command prompt in path2 . To run Prop.jar file in path1 . type call "pathtodesktop/example/path1/Prop.jar" hit enter.
.property file will be created in path2 instead of path1 that's what happening in your case.
This may be a stupid question, but I have to ask because I couldn't find any proper solution.
I am new to Eclipse. I created a Dynamic Web project in Eclipse, In this, I write a simple code to create a text file, Only file name is specified Not the path that where to create, After successful execution, i could not find my text file in my project folder.
If path is specified in the code, I can find the text file in specified directory, My Question is where i can find my text file if i am not specify a path ?
And my code is
try {
FileWriter outFile = new FileWriter("user_details.txt", true);
PrintWriter out1 = new PrintWriter(outFile);
out1.append(request.getParameter("un"));
out1.println();
out1.append(request.getParameter("pw"));
out1.close();
outFile.close();
System.out.println("file created");
} catch(Exception e) {
System.out.println("error in writing a file"+e);
}
I edited my code with following lines,
String path = new File("user_details.txt").getAbsolutePath();
System.out.println(path);
The path that i got is below
D:\Android\eclipse_JE\eclipse\user_details.txt
Why i got it in the eclipse folder ?
Then,
How can i create a text file in my web app, if this is not the right way to create a textfile ?
The file is located in the actual working directory of your application server. Do a
System.out.println(new File("").getAbsolutPath());
and you'll find the location.
However this is not a good idea to write files in web application like this, because first you never know where it is and second you never know whether you write privilege on it.
You need to specify some filesystem root for your application by passing it as init-parameter and use it as parent for everything you need to do on the filesystem. Check this answer to a similar Question.
You could then create your file like this:
String fsroot = getServletContext().getInitParameter("fsroot")
File ud = new File(fsroot, "user_details.txt");
FileWriter outFile = new FileWriter(ud, true);
You may try the getAbsolutePath() method.
String newFile = new File("Demo.txt").getAbsolutePath();
It will show the location where the files will be created.
I have a simple parsing program that takes a few files and combines them. It then generates a few output files to the working directory. When I run this program in eclipse it generates all the required output files. However, when I run it using a jar generated in eclipse it only creates two of the three output files. It makes me think something is wrong in how the jar file is generated but can't seem to find any answers to this.
I've tried updating some of the java, it was written using java 5 I believe. I just changed the Vectors to ArrayLists and the FileOutputStream to FileWriter.
I had to download javax.mail to get the required libraries and added those jar files to the java6 library I was using in Eclipse. I've tried deleting the classes and generating new classes. I tried to check the permissions on the jar file to make sure that I had access with it. I guess I am just not sure where to start.
I've also tried packing this as a jar file and not as a runnable jar file because it gave me more options on what to include. However, I could not run this type of jar file even though it was an executable. I've recreated the jar file numerous times without any luck.
There were quite a few problems people had with UTF-8 not displaying properly in a jar file but being fine in eclipse. However their jar files were generating the text files where as mine just does not generate one.
Update: Interestingly if I move the block of code to its own class and run it as a separate jar it will work. So the solution for now is to have two jar files.
This is the code for the ungenerated file:
private static void parseCRNOnly() {
try {
//file to write to
File new_file = new File("CRNOnlyClean.txt");
FileWriter out = new FileWriter(new_file);
//file to read from
File file = new File("CRNOnly.txt");
FileReader reader = new FileReader(file);
BufferedReader buf = new BufferedReader(reader);
try{
String str;
String temp = "\r";
String nl = "\r\n";
String tab = "\t";
str = buf.readLine();
while (str != null && !str.isEmpty()) {
StringTokenizer tokenizer = new StringTokenizer(str," \t");
int column = 0;
while(tokenizer.hasMoreTokens()) {
column++;
temp = tokenizer.nextToken();
if(column == 8){
break;
}
out.write(temp);
out.write(tab);
}
out.write(nl);
str = buf.readLine();
}
out.close();
} catch(IOException e0){
System.out.println("Error Reading From CRNOnly.txt");
JOptionPane.showMessageDialog(null, "Error Reading From CRNOnly.txt");
}
} catch(FileNotFoundException e1){
System.out.println("File CRNOnly.txt Not Found");
JOptionPane.showMessageDialog(null, "File CRNOnly.txt Not Found");
} catch (IOException e) {
System.out.println("Error Reading from FileWriter");
JOptionPane.showMessageDialog(null, "Error Reading from FileWriter");
}
For some reason the jar file was not including some old libraries that I had to add from javax.mail, so I tried making a jar file using netbeans instead and it worked. Netbeans didn't pack the javax.mail libraries into the jar file either but included them in a file with the jar file. Therefore to use the jar file this file must be in the directory as well.
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].
I have made a Swing application and will include a file, help.pdf in the .jar file. When the user selects Help->User Guide from a JMenuItem, it should load the file in the default PDF viewer on the system.
I have the code to load the PDF,
private void openHelp() {
try {
java.net.URL helpFile = getClass().getClassLoader().getResource("help.pdf");
File pdfFile = new File(helpFile.getPath());
if (pdfFile.exists()) {
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(pdfFile);
} else {
System.out.println("Awt Desktop is not supported!");
}
} else {
System.out.println("File does not exist!");
}
System.out.println("Done");
} catch (Exception ex) {
ex.printStackTrace();
}
}
This works in the eclipse IDE, however, when I pack it into a jar for other people it no longer works.
How do I fix this problem?
The problem is that a File cannot name a component of a JAR file. What you need to do is to copy the resource from the JAR file into a temporary file in the filesystem, and open using the File for the temporary file.
File names in a .jar file are case sensitive. In your text you write Help.pdf but in the code you use help.pdf. The upper/lowercase in the Java code must match the case of the file, even if you are using a system where the filesystem is not case sensitive.
Try
getResource("Help.pdf");
instead (assuming the filename in your posting text is correct)
I think you have to retrieve the location of the jar, open it and load the pdf file from within your application. The .jar file is just a zipped archive, which can be read with java easily...