How to access folders in a JAR file - java

My program has a folder called data - which stores text files- when i click save in my JAR application though nothing happens. How can i make it so i can access and save new files? Here is some of the code
public void saveAs() {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Save Routine"); fileChooser.setInitialDirectory(new File("data/routines"));
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("txt", "*.txt"));
if (fileName != null) {
fileChooser.setInitialFileName(fileName);
}
save(fileChooser.showSaveDialog(stage));
}
I also did it with a absolute path and that did not work either

Without seeing your save(java.io.File) method, I can't say. FileChooser.showSaveDialog just shows the dialog and tells you what file they chose (if any). You then have to write it whether it's a JAR or txt.
Try this:
private void save(File where){
if(where==null){ //they canceled.
return;
}
try(OutputStream out = Files.newOutputStream(where.toPath())){
//Write to out.
}
}
You can write things into JAR files with the plain JarFile constructor, but it looks like you want plain text files. Although you may be able to update your application's JAR files while it's running, most programs don't do that because it's odd.

Related

How to have my java project to use some files without using their absolute path?

I have written a project where some images are used for the application's appearance and some text files will get created and deleted along the process. I only used the absolute path of all used files in order to see how the project would work, and now that it is finished I want to send it to someone else. so what I'm asking for is that how I can link those files to the project so that the other person doesn't have to set those absolute paths relative to their computer. something like, turning the final jar file with necessary files into a zip file and then that the person extracts the zip file and imports jar file, when runs it, the program work without any problems.
by the way, I add the images using ImageIcon class.
I'm using eclipse.
For files that you just want to read, such as images used in your app's icons:
Ship them the same way you ship your class files: In your jar or jmod file.
Use YourClassName.class.getResource or .getResourceAsStream to read these. They are not files, any APIs that need a File object can't work. Don't use those APIs (they are bad) - good APIs take a URI, URL, or InputStream, which works fine with this.
Example:
package com.foo;
public class MyMainApp {
public void example() {
Image image = new Image(MyMainApp.class.getResource("img/send.png");
}
public void example2() throws IOException {
try (var raw = MyMainApp.class.getResourceAsStream("/data/countries.txt")) {
BufferedReader in = new BufferedReader(
new InputStreamReader(raw, StandardCharsets.UTF_8));
for (String line = in.readLine(); line != null; line = in.readLine()) {
// do something with each country
}
}
}
}
This class file will end up in your jar as /com/foo/MyMainApp.class. That same jar file should also contain /com/foo/img/send.png and /data/countries.txt. (Note how starting the string argument you pass to getResource(AsStream) can start with a slash or not, which controls whether it's relative to the location of the class or to the root of the jar. Your choice as to what you find nicer).
For files that your app will create / update:
This shouldn't be anywhere near where your jar file is. That's late 80s/silly windows thinking. Applications are (or should be!) in places that you that that app cannot write to. In general the installation directory of an application is a read-only affair, and most certainly should not be containing a user's documents. These should be in the 'user home' or possibly in e.g. `My Documents'.
Example:
public void save() throws IOException {
Path p = Paths.get(System.getProperty("user.home"), "navids-app.save");
// save to that file.
}

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.

Java - How can I more effectively "scan" a portion of my file system with this program?

I am working on part of a proof of concept program in Java for an antivirus idea I had. Right now I'm still just kicking the idea around and the details aren't important, but I want the program I'm writing to get the file paths of every file within a certain range of each other(say 5 levels apart) in the directory and write them to a text file.
What I have right now(I will include my code below) can do this to a limited extent by checking if there are files in a given folder in the directory and writing their file paths to a text file, and then going down another level and doing it again. I have it set up to do 2 levels in the directory currently and it sort of works. But it only works if there is only one item in the given level of the directory. If there is one text file it will write that filepath to another text file and then terminate. But if there's a text file and folder, it ignores the text file and goes down to the next level of directory and records the file path of whatever text file it finds there. If there are two or more folders it will always choose one in particular over the other or others.
I realize now that it's doing that because I used the wrong conditional. I used if else and should have done something else, but I'm not sure which one I should have used. However I have to do it, I want to fix it so that it branches out with each level. For example, I start the program and give it starting directory C:/Users/"Name"/Desktop/test/. Test has 2 folders and a text file in it. Working the way I want it to, it would then record the file path of the .txt, go down a level into both folders, record any .txts or other files it found there, and then go down another level into each folder it found in those two folders, record what it found there, and so on until it finished the pre-determined number of levels to go through.
EDIT: To clarify confusion over what the problem is, I'll sum it up. I want the program to write the file paths of any files it finds in each level of the directory it goes through in another text file. It will do this, but only if there is one file in a given level of directory. If there is just one .txt for example, it will write the file path of that .txt to the other text file. But if there are multiple files in that level of directory(for example, two .txts) it will only write the file path of one of them and ignore the other. If there's a .txt and a folder, it ignores the .txt and enters the folder to go to the next level of directory. I want it to record all files in a given location and then branch into all the folders in that same location.
EDIT 2: I got the part of my code that gets the file path from this question( Read all files in a folder ) and the section that writes to my other text file from this one( How do I create a file and write to it in Java? )
EDIT 3: How can I edit my code to have recursion, as #horatius pointed out that I need?
EDIT 4: How can I edit my code so that it doesn't need a hard coded starting file path to work, and can instead detect the location of the executable .jar and use that as its starting directory?
Here is my code:
public class ScanFolder {
private static final int LEVELS = 5;
private static final String START_DIR = "C:/Users/Joe/Desktop/Test-Level1/";
private static final String REPORT_FILE = "C:/Users/Joe/Desktop/reports.txt";
public static void main(String[] args) throws IOException {
try (PrintWriter writer = new PrintWriter(REPORT_FILE, "UTF-8");
Stream<Path> pathStream = Files.walk(Paths.get(START_DIR), LEVELS)) {
pathStream.filter(Files::isRegularFile).forEach(writer::println);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
Thanks in advance
If you are using Files.walk(...) it does all the recursion for you.
Opening and writing to the PrintWriter will truncate your output file each time it is opened/written to, leaving just the last filename written.
I think something like the below is what you are after. As you progress, rather than writing to a file, you may want to put the found Path objects into an ArrayList<Path> or similar for easier later processing, but not clear from your question what requirements you have here.
public class Walk
{
public static void main(String[] args) throws IOException {
try (PrintWriter writer = new PrintWriter("C:/Users/Joe/Desktop/reports.txt", "UTF-8")) {
Files.walk(Paths.get("C:/Users/Joe/Desktop/test")).forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
writer.println(filePath);
}
});
}
}
}
Here is an improved example that you can use to limit depth. It also deals with properly closing the Stream returned by Files.walk(...) that the previous example did not, and is a little more streams/lambda idiomatic:
public class Walk
{
// Can use Integer.MAX_VALUE for all
private static final int LEVELS = 2;
private static final String START_DIR = "C:/Users/Joe/Desktop/test";
private static final String REPORT_FILE = "C:/Users/Joe/Desktop/reports.txt";
public static void main(String[] args) {
try (PrintWriter writer = new PrintWriter(REPORT_FILE, "UTF-8");
Stream<Path> pathStream = Files.walk(Paths.get(START_DIR), LEVELS)) {
pathStream.filter(Files::isRegularFile).forEach(writer::println);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}

HTML file not opening in executable jar

I have a program I have written in Eclipse and it runs fine -- the HTML file opens when I run the program through Eclipse. But when I create a jar file of the program, everything else runs fine except this HTML file won't open in the browser (or anywhere):
operation.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
File htmlFile = new File("help/operation.html");
Desktop.getDesktop().browse(htmlFile.toURI());
} catch (MalformedURLException MURLe) {
MURLe.printStackTrace();
} catch (IOException ioE) {
ioE.printStackTrace();
}
}
});
The rest of the program runs fine, and my images and sounds work fine and are opened, but this HTML file will not open in the menu or with the Ctrl+key shortcut. Your help is appreciated. Thanks.
When you have a file inside your jar, you cannot access it like you are doing now.
You need to read it as a stream, that's the only way.
Suppose your project is foo. Then help/operation.html will refer to
..\abc\help\operation.html
But the deployed jar file will not contain it.
You have include this operation.html file in your source code (where you write code).
Then eclipse (or any IDE) will add it into your jar file when you deploy it.
And now you can use your file as follows.
Suppose your file is present in as shown in figure.
Now you can refer your html file from any class. In this example referring it from
Accesser class.
File resFile = new File(Accesser.class.getResource("operation.html").toURI());
If you want to open your file in browser you will have to copy this file into the
user's System.
File htmlFile = new File("operation.html");
if(!htmlFile.exists) {
Files.copy(resFile.toPath(), htmlFile.toPath());
}
Desktop.getDesktop().browse(htmlFile.toURI());
Files is present in java.nio.file package

How to pass a text file as a argument?

Im trying to write a program to read a text file through args but when i run it, it always says the file can't be found even though i placed it inside the same folder as the main.java that im running.
Does anyone know the solution to my problem or a better way of reading a text file?
Do not use relative paths in java.io.File.
It will become relative to the current working directory which is dependent on the way how you run the application which in turn is not controllable from inside your application. It will only lead to portability trouble. If you run it from inside Eclipse, the path will be relative to /path/to/eclipse/workspace/projectname. If you run it from inside command console, it will be relative to currently opened folder (even though when you run the code by absolute path!). If you run it by doubleclicking the JAR, it will be relative to the root folder of the JAR. If you run it in a webserver, it will be relative to the /path/to/webserver/binaries. Etcetera.
Always use absolute paths in java.io.File, no excuses.
For best portability and less headache with absolute paths, just place the file in a path covered by the runtime classpath (or add its path to the runtime classpath). This way you can get the file by Class#getResource() or its content by Class#getResourceAsStream(). If it's in the same folder (package) as your current class, then it's already in the classpath. To access it, just do:
public MyClass() {
URL url = getClass().getResource("filename.txt");
File file = new File(url.getPath());
InputStream input = new FileInputStream(file);
// ...
}
or
public MyClass() {
InputStream input = getClass().getResourceAsStream("filename.txt");
// ...
}
Try giving an absolute path to the filename.
Also, post the code so that we can see what exactly you're trying.
When you are opening a file with a relative file name in Java (and in general) it opens it relative to the working directory.
you can find the current working directory of your process using
String workindDir = new File(".").getAbsoultePath()
Make sure you are running your program from the correct directory (or change the file name so that it will be relative to where you are running it from).
If you're using Eclipse (or a similar IDE), the problem arises from the fact that your program is run from a few directories above where the actual source is located. Try moving your file up a level or two in the project tree.
Check out this question for more detail.
The simplest solution is to create a new file, then see where the output file is. That is the correct place to put your input file into.
If you put the file and the class working with it under same package can you use this:
Class A {
void readFile (String fileName) {
Url tmp = A.class.getResource (fileName);
// Or Url tmp = this.getClass().getResource (fileName);
File tmpFile = File (tmp);
if (tmpFile.exists())
System.out.print("I found the file.")
}
}
It will help if you read about classloaders.
say I have a text file input.txt which is located on the desktop
and input.txt has the following content
i came
i saw
i left
and below is the java code for reading that text file
public class ReadInputFromTextFile {
public static void main(String[] args) throws Exception
{
File file = new File(
"/Users/viveksingh/desktop/input.txt");
BufferedReader br
= new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null)
System.out.println(st);
}
}
output on the console:
i came
i saw
i left

Categories

Resources