I have an application that writes some data to a plain text index file. It works fine in Netbeans, but when packaged as a jar the index file is created but ends up blank. Here is the relevant code:
System.out.println("Writing Index File");
PrintWriter indexOut = new PrintWriter(new File("index.txt"));
for(int i = 0; i < index.size(); i++)
{
indexOut.println(index.get(i));
}
indexOut.flush();
indexOut.close();
System.out.println("Index complete.");
Why would the apps behavior change when I bundle it as a jar and how can I fix it?
Do you think the index collection has something?
You may want to change the first like to
System.out.println("Writing Index File " + index.size());
You can try debugging the same.
There should be no reason for the app behaviour to change, unless the input to the program changes.
I suspect you are reading some data in your program from a file which is supposed to be relative to your current directory. So you should check if you have dependency on any relative path. If yes convert them to absolute path as first step.
When you run from netbeans the default file path (where a file will land if you just write File("indexOut.txt") ) is the netbeans project folder. If you double-click the jar file, then the default path is the directory containing the jar.
Related
Although the Title isn't very understandable I do have a simple issue. So i'm trying to write some code in a Processing Sketch (https://processing.org/) which can count how many files are in a document. The problem is, is that it doesn't accept the variable type.
File folder = File("My File Path");
folder.listFiles().size;
It says the function File(String) doesn't exist. When I try to put the file path without quation marks, it still doesn't work!
If you have a solution then please use a functioning example so that I know how it works. Thanks for any help!
As Joakim Danielson says it is constructor so you need to use new keyword.
Below code will work for you.
File folder = new File("My File Path");
int fileLength = folder.listFiles().length;
It's a constructor so you need to use new
File folder = new File("My File Path");
//To get the number of files in the folder
folder.listFiles().length;
Assuming the "My File Path" folder is inside your sketch you need to provide the path to your sketch. Luckily Processing already provides a helper function: sketchPath()
Here's an example:
File folder = new File(sketchPath("My File Path"));
println("folder.exists: " + folder.exists());
if(folder.exists()){
println(folder.listFiles().length + " files and/or directories");
}else{
println("folder does not exist, double check the path");
}
Bare in mind there's also a dataPath() function which points to a folder named data in your sketch folder. The data folder is typically used for storing external data (e.g. assets (raster or vector images/Processing font files) or raw data (binary/text/csv/xml/json/etc.)). This is useful to separate your sketch source files from the data to be loaded/accessed by your sketch.
Also, Processing has a few utility functions for listing files and folders.
Be sure to check out Processing > Examples > Topics > File IO > DirectoryList
The example includes less documented functions such as listFiles() (which returns an array of java.io.File objects based on the filters set) or listPaths (which returns an array of String objects: just the paths).
The options and filters are quite handy, for example if you want to list directories only and ignore files you can simply write simply like:
println("directories: " + listFiles(sketchPath("My File Path"),"directories").length);
For example if want to list all the wav files in a data/audio directory inside the sketch you can use:
File[] files = listFiles(dataPath("audio"), "files", "extension=wav");
This will ignore directories and any other file that does not have .wav extension.
To make this answer complete, here are a few more details on the options for listFiles/listPaths from Processing's source code:
"relative" -> no effect with the Files version, but important for listPaths
"recursive"-> traverse nested directories
"extension=js" or "extensions=js|csv|txt" (no dot)
"directories" -> only directories
"files" -> only files
"hidden" -> include hidden files (prefixed with .) disabled by default
I need to read a .txt file of integers into a 2d array but when I try to read in the file I get a runetime error saying that the specified file cannot be found. This is the first time I've tried to read in a file so I just need direction on how to do it but I couldn't find an answer this basic.
I have the file of integers named "num1.txt" saved in the same folder as as my java file, so I'm wondering if I don't understand how eclipse and java decide where the file is.
public static void main(String[] args) throws FileNotFoundException
{
int i;
int j;
i=0;
j=0;
int connect4Array[][] = new int[6][7];
Scanner readFile = new Scanner(new File("num1.txt"));
while(readFile.hasNextInt())
{
for(i=0;i<connect4Array.length;i++)
{
connect4Array[i++][j]=readFile.nextInt();
for(j=0;j<connect4Array[j].length;j++)
{
connect4Array[i][j++]=readFile.nextInt();
}
}
}
First of all, it is NOT a compilation error. It is a runtime error. You need to learn the difference ... and to say the right thing, or else people won't understand what you are talking about.
I have the file of integers named "num1.txt" saved in the same folder as as my java file.
The problem is that you are trying to access the file in the running application's current directory ... but the current directory is not the place that you think / hope it is.
So where is the application's current directory? It depends on how you ran the application!
If you run the java app from a shell, then the current directory will default to the shell's current directory.
You can change it by cd-ing before you run java ... and I think you can also specify it using -Duser.dir=<pathname>.
If you run the java app from Eclipse, then the current directory will default to the project directory. That is probably different to the directory containing the source code.
You can specify a different current directory in the Eclipse settings for your application's launcher.
Alternatively, use an absolute path for the file, or put it into your application's JAR file and read it as a "resource".
move the file to where the src folder located.
because the default is project directory in your workspace.
you can use getProperty to check current directory.
String CurrentDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + CurrentDir);
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.
I would like to ask if its possible to put text files into my jar, I use them to make my map in my game, but users can get Highscores. now I want to save the Highscores with the map, so I have to save the map on the user their PC. Is there any way how I could do this? I've searched the internet for some ideas but I could not find anything that even came close to what I've wanted. I only had 3/4th of a year java so I don't know much about these things, everything that happens outside the debug of eclipse are problems for me(files are mainly one of those things, null exceptions, etc).
The main question now.
Is it possible to do? If yes, do you have any terms I could search on, or some sites/guides/tutorials? If no, is there any other way how I could save the highscores?
EDIT:
to make clear
Can I get the text file (the text inside the file) to be extracted to a different file in like the home directory of my game (where I save the settings and stuff) the basic maps are inside the jar file, so I want them to be extracted on the first start-up of the program
Greetings Carolien
"extracted to a different file in like the home directory of my game (where i save the settings and stuff) the basic maps are inside the jar file, so i want them to be extracted on the first startup of the program"
You can get the URL by using getClass().getResource()
URL url = getClass().getResource("/res/myfile.txt");
Then create a File object from the URI of the URL
File file = new File(url.toURI());
Then just perform your normal file operations.
if (file.renameTo(new File(System.getProperty("user.home") + "\\" + file.getName()))) {
System.out.println("File is moved successful!");
} else {
System.out.println("File is failed to move!");
}
Assuming your file structure is like below, it should work fine
ProjectRoot
src
res
myfile.txt
Note: the above is moving the entire file. If you want to extract just the data inside the file, then you can simple use
InputStream is = getClass().getResourceAsStream("/res/myfile.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
The just do normal IO operation with the reader. See here for help with writing the file.
This should be a really simple question but Google + my code isn't working out.
In Eclipse on Windows, I want my program to look inside a certain folder. The folder is directly inside the Project folder, on the same level as .settings, bin, src, etc. My folder is called surveys, and that's the one I want my File object to point at.
I don't want to specify the full path because I want this to run on both of my computers. Just the path immediately inside my Project.
I'm trying this code but it isn't working - names[] is coming back null. And yes I have some folders and test junk inside surveys.
File file = new File("/surveys");
String[] names = file.list();
for(String name : names)
{
if (new File("/surveys/" + name).isDirectory())
{
System.out.println(name);
}
}
I'm sure my mistake is within the String I'm passing to File, but I'm not sure what's wrong?
In your question you didn't specify what platform you are running on. On non-Windows, a leading slash signifies an absolute path. Best to remove the leading slash. Try this:
File file = new File("surveys");
System.out.println("user.dir=" + System.getProperty("user.dir"));
System.out.println("file is at: " + file.getCanonicalPath());
String[] names = file.list();
for(String name : names)
{
if (new File(file, name).isDirectory())
{
System.out.println(name);
}
}
Make sure the in your run configuration, the program is running from the projects directory (user.dir = <projects>)
Make sure that your file is a directory before using file.list() on it, otherwise you will get a nasty NullPointerException.
File file = new File("surveys");
if (file.isDirectory()){
...
}
OR
if (names!=null){
...
}
If you checked the full path of your file with
System.out.println(file.getCanonicalPath())
the picture would immediately become clear. File.getCanonicalPath gives you exactly the full path. Note that File normalizes the path, eg on Windows "c:/file" is converted to "C:\file".