Unable to locate and load file in Eclipse IDE, File not found - java

I'm new to Java, and I am facing this issue in Eclipse. Even after pointing it to the correct file, it shows a file not Found Error.
I am trying to compile code from a Java file using the Java Compiler API.
The code words fine in Visual Studio with setting everything in root, But gives this error in Eclipse with all these directories.
Also, why are there three different src folders in the image?
My project structure
package com.example.app;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.IOException;
public class compilier {
public static void main(String[] args) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int result = compiler.run(null, null, null, new File("com/example/app/Code.java").getAbsolutePath());
if (result == 0)
{
System.out.println("File Compiled");
}
try {
String package_dir = "/demo/src/main/java/com/example/app";
try{
ProcessBuilder builder = new ProcessBuilder("java", package_dir.concat("/Code"));
builder.redirectErrorStream(true);
File outfile = new File((package_dir.concat("/output.txt")));
builder.redirectOutput();
builder.start();
if (outfile.length() > 3000)
{
System.out.println("Exceeded buffer limit");
System.exit(1);
}
} catch(IOException e) {
e.printStackTrace();
}
} catch (Exception err) {
System.out.println("Error!");
err.printStackTrace();
}
}
}
Error Message

Your path looks wrong. The /demo directory would need to be in the root of your current drive.
Also, the output of a Maven build is found in the target directory. The Java class files are generated there, and the resource files are copied over from src/main/res hierarchy. The .Java files are lost. You could add a Maven task to copy the .Java files but this would be very nonstandard.
Finally you need to load resource files using the classpath. There are lots of examples on the Internet. Otherwise you may end up with a project that finds the file in Eclipse but not when deployed in a .jar or .war file.
Happy hunting.

Related

Project Stops working after compiling to jar

I currently want to try to create a .jar file that pinpoints to a .bat file to start a gaming server,
the Forge Modloader for the current version switched from a server startup via jar file to .bat file, and my server provider currently has no solution for it. -Small disclaimer, I haven't touched java for 6 years, which is why I may not see the obvious
For this, I found some code from Pavan.
Though, there are two problems, where I hope you may have a solution or some other workaround.
First of all, while in Intellij, "everything" works fine. main() is running, and the "Hallo World" Test .bat is opening. After compiling it to a jar, nothing happens, even with a set File Path.
Second Problem. I've tried several spots, but System.exit(0) does not work, after
int returnCode = CommandLineUtils.executeCommandLine(commandLine, systemOut, systemErr);
The code basically stops, and the process stays inactive, which could end up bad for a gaming server where I have 0 access to the needed tools to clean this up by myself... and I don't want to explain to Customer Support why there are 1000 instances of java running in the background ;)
But regardless, Thanks for your time and hopefully help as well
import java.io.File;
import java.io.OutputStreamWriter;
import org.codehaus.plexus.util.cli.CommandLineException;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import org.codehaus.plexus.util.cli.Commandline;
import org.codehaus.plexus.util.cli.WriterStreamConsumer;
public class BatRunner {
public BatRunner() {
String batfile = "run.bat";
String directory = "C:\\Users\\User\\IdeaProjects";
try {
runProcess(batfile, directory);
} catch (CommandLineException e) {
e.printStackTrace();
}
}
public void runProcess(String batfile, String directory) throws CommandLineException {
Commandline commandLine = new Commandline();
File executable = new File(directory + "/" +batfile);
commandLine.setExecutable(executable.getAbsolutePath());
WriterStreamConsumer systemOut = new WriterStreamConsumer(
new OutputStreamWriter(System.out));
WriterStreamConsumer systemErr = new WriterStreamConsumer(
new OutputStreamWriter(System.out));
int returnCode = CommandLineUtils.executeCommandLine(commandLine, systemOut, systemErr);
System.exit(0);
if (returnCode != 0) {
System.out.println("Something Bad Happened!");
} else {
System.out.println("Taaa!! ddaaaaa!!");
}
}
public static void main(String[] args) {
new BatRunner();
}
}
Source: https://www.opencodez.com/java/how-to-execute-bat-file-from-java.htm/

Text and image files not included when exporting jar

I've created a project which utilizes image files as well as a text file when executed. Both the text and image files are in my project folder before I exported the project into a runnable jar, but when I ran the jar from the command line, I got a filenotfound exception caused by the program typing to read from the text file. I unzipped the jar to double check and the image and text files weren't there.
package application;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import javafx.collections.FXCollections;
public class Data {
private static Data instance=new Data();
private Map<String,String> saveEntries = new HashMap<>();
private static String fileName = "ResponseData";
public static Data getInstance() {
return instance;
}
public void exitSave() throws IOException {
Path path = Paths.get("ResponseData");
Iterator<Map.Entry<String, String>> iter = saveEntries.entrySet().iterator();
BufferedWriter bw = Files.newBufferedWriter(path);
try {
while(iter.hasNext()) {
Map.Entry<String, String> entry = iter.next();
bw.write(String.format("%s\t%s", entry.getKey(),entry.getValue()));
bw.newLine();
}
} catch (IOException e) {
new FileNotFoundException("Error when saving data");
}finally {
if(bw!=null)
bw.close();
}
}
public void updatedSaveEntry(String input, String response) {
saveEntries.put(input, response);
}
public Map<String,String> getSaveEntries(){
return this.saveEntries;
}
public void setEntry(Map<String,String> map) {
Iterator<Map.Entry<String, String>> iter = map.entrySet().iterator();
while(iter.hasNext()) {
Map.Entry<String, String> entry = iter.next();
saveEntries.put(entry.getKey(), entry.getValue());
}
}
public void loadEntries() throws IOException{
saveEntries = FXCollections.observableHashMap();
Path path = Paths.get(fileName);
BufferedReader br = Files.newBufferedReader(path);
String line;
try {
while((line=br.readLine())!=null&&!line.trim().isEmpty()) {
String[] parts = line.split("\t");
saveEntries.put(parts[0], parts[1]);
}
}finally {
if(br!=null) {
br.close();
}
}
}
}
Eclipse Runnable Jar Export
Project Folder
If you are both reading and writing to a file, then locating this file in the application jar is not appropriate as mentioned in the other answer: you should persist your data at an external location.
However, it is usual to keep the read-only resources files (such as images) in the jar. If you want to keep this approach for the images and possibly other resources, you are facing two problems:
Getting Eclipse to include the file in the jar using the Export Runnable Jar feature.
Finding the file in the jar
Including the file
The simplest is probably just to place the file in a source folder. In your project, do New -> Source Folder, give it a name (e.g., "resources"), and move your file there. Normally, if you re-run the export, the file should be in the jar.
Finding the file
Files in jar are accessed differently. See the accepted answer to Reading a resource file from within jar. Note that you don't need to include the name of your resource folder in the path, as this file will be placed at the root of your jar (you can verify this by unpacking it).
Your program is trying to read the file from your local file system and not from the jar file. So it should indeed not be included in the jar file. The program is expecting the file in the current working directory where you execute your program and that can be different if you run your project within Eclipse or if you execute the exported jar file.

Java- Load file from same package in NB platform application

I have the following piece of code,
public void vbsCalled() {
try {
String file = "src\\com\\first\\hello\\hello.vbs";
Runtime.getRuntime().exec("wscript " + file + " ");
} catch (IOException ex) {
Logger.getLogger(RunVBS.class.getName()).log(Level.SEVERE, null, ex);
}
}
I am using netbeans IDE,
Scenario 1:
I create a new java project (New Project -> Java -> Java Application)
The project Structure looks like below,
--Java Application1
-Source Packages
-com.first.hello //Package
-ClassWhichHaveVbsCalledMethod.java
-hello.vbs
with this am able to call the hello.vbs from same package and no error.
Scenario 2:
I create a netbeans platform application (New project - > Netbeans Modules ->NetBeans platform Application)
The project Structure looks like below,
RunVBS.java has the vbsCalled() Method and with the hello.vbs in same package as scenario 1,
Now, it looks for the file in
"C:\application1\src\com\first\hello\hello.vbs"
and shows no such file found error.
How can i load the file in netbeans platform application as like scenario1.
Create a folder in your project's root directory called release
Move hello.vbs to the release/ folder
Use the InstalledFileLocator class to get the runtime path of your file.
Here is what your vbsCalled() method would then look like.
public void vbsCalled() {
try {
File file = InstalledFileLocator.getDefault().locate(
"hello.vbs", // filename relative to the release/ directory
"com.first.hello", // Your module's code name base __not package!__
false);
Runtime.getRuntime().exec("wscript " + file.getAbsolutePath() + " ");
} catch (IOException ex) {
Logger.getLogger(RunVBS.class.getName()).log(Level.SEVERE, null, ex);
}
}
See DevFaqInstalledFileLocator for more details

How to get the unzipped file directory by using TrueZip

public class unzipAll {
public static void main(final java.lang.String[] args) throws Exception{
TFile src = new TFile("C:/1/BULK.tar.gz");
File dest = new File("C:/Test/");
dest.mkdirs();
try {
src.cp_rp(dest);
TVFS.umount();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I can use this code to unzip BULK.tar.gz. But I want to know the directory of the unzipped files.
Right now, all the files unzipped to C:/Test/. But it has a sub folder "AAAAA".
I want to get this sub folder name "AAAAA" How can I get it?
Try dest.listFiles(). It should give you an array of all files and directories in dest. There are also versions of listFiles that can filter out different kinds of files and/or directories which can be handy at times.
See java api for details: http://docs.oracle.com/javase/7/docs/api/java/io/File.html

Reading a Txt-File in a jar-File in Java

I've write a Java programm and packaged it the usual way in a jar-File - unfortunately is needs to read in a txt-File. Thats way the programm failed to start on other computer machines because it could not find the txt-file.
At the same time Im using many images in my programm but here there is no such problem: I "copy" the images to the eclipse home directory, so that they are packaged in the jar-File and usable through following command:
BufferedImage buffImage=ImageIO.read(ClassName.class.getClassLoader()
.getResourceAsStream("your/class/pathName/));
There is something similar for simple textfiles which then can be use as a normal new File()?
Edit
Ive try to solve my problem with this solution:
package footballQuestioner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.security.auth.login.Configuration;
public class attempter {
public static void main(String[] args) {
example ex = new example();
}
}
class example {
public example() {
String line = null;
BufferedReader buff = new BufferedReader(new InputStreamReader(
Configuration.class
.getResourceAsStream("footballQuestioner/BackUpFile")));
do {
try {
line = buff.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} while (line != null);
}
}
But it gives always an NullPointerException...do I have forgotten something?
Here is as required my file structure of my jar-File:
You can load the file from the ClassPath by doing something like this:
ClassLoader cl = getClass().getClassLoader()
cl.getResourceAsStream("TextFile.txt");
this should also work:
getClass().getResourceAsStream(fileName);
File always points to a file in the filesystem, so I think you will have to deal with a stream.
There are no "files" in a jar but you can get your text file as a resource (URL) or as an InputStream. An InputStream can be passed into a Scanner which can help you read your file.
You state:
But it gives always an NullPointerException...do I have forgotten something?
It means that likely your resource path, "footballQuestioner/BackUpFile" is wrong. You need to start looking for the resource relative to your class files. You need to make sure to spell your file name and its extension correctly. Are you missing a .txt extension here?
Edit
What if you try simply:
BufferedReader buff = new BufferedReader(new InputStreamReader(
Configuration.class.getResourceAsStream("BackUpFile")));

Categories