Java creating a test file from a jar - java

I want to have a java app, where after starting the jar I get a file for example a test.txt within the same folder as the jar.
For example I click on the jar and in the same folder I get a test.txt file.
The below code works in eclipse and creates the file, but after an export to jar, no file is produced.
Would be very happy if you could help.
public class FileWriterTest {
public static void main(String[] args) {
String fileName = "test.txt";
try(
FileWriter fileWriter = new FileWriter(fileName);
BufferedWriter writer = new BufferedWriter(fileWriter);
) {
writer.write("Hello");
} catch(IOException e) {
e.printStackTrace();
}
}
}

With System.getProperty("user.dir") you can get the current "working directory".
If you want to create a file in that specific directory you could use the following code:
String workingDirectory = System.getProperty("user.dir");
File file = new File(working directory + File.separator + "filename.txt");
file.createNewFile();

If you are running as java -jar yourjar.jar, it will not take the additional classpath.
You need to add your jar and location where file resided in classpath and call java command for Main class
example
Linux
java -classpath .:path_dir_with_jar/*:path_to_file MainClass
Windows
java -classpath .;path_dir_with_jar/*;path_to_file MainClas
Finally can read as
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("SomeTextFile.txt")
;

Related

URI not hierarchical need to use File class for a method

I need to open a video file with my code, and it works perfectly fine in Eclipse but when I export into a runnable JAR, i get an error "URI not hierarchical".
I have seen people suggest using getResourceAsStream(), but i need to have a file object as i am using Desktop.getDesktop.open(File). Can anyone help me out?
Here is the code:
try {
URI path1 = getClass().getResource("/videos/tutorialVid1.mp4").toURI();
File f = new File(path1);
Desktop.getDesktop().open(f);
} catch (Exception e) {
e.printStackTrace();
}
if it helps my folder list is like
Src
videos
videoFile.mp4
EDIT:
I plan to run this on windows only, and use launch4j to create an exe.
You can copy the file from the jar to a temporary file and open that.
Here's a method to create a temporary file for a given jar resource:
public static File createTempFile(String path) {
String[] parts = path.split("/");
File f = File.createTempFile(parts[parts.length - 1], ".tmp");
f.deleteOnExit();
try (Inputstream in = getClass().getResourceAsStream(path)) {
Files.copy(in, f.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
return f;
}
And here's an example of how you'd use it:
Desktop.getDesktop().open(createTempFile("/videos/tutorialVid1.mp4"));

Why can't I find my File?

I'm trying to open a CSV file name "logger.csv" which I have saved in the source folder itself.
public static void main(String[] args) {
String filename = "logger.csv";
File motor_readings = new File(filename);
try {
Scanner inputStream = new Scanner(motor_readings);
while (inputStream.hasNext()){
System.out.println(inputStream.next());
}
inputStream.close();
} catch (FileNotFoundException e) {
System.out.println("Error: File not found!");
}
}
However, this keeps on giving me a "File not found" error.
If you use relative pathing as you are right now - the file needs to exist in the project root, not in the directory of the java file.
Consider this hierarchy:
project/
src/main/java
file.java
logger.csv
new File("logger.csv") will not work.
project/
logger.csv
src/main/java
file.java
new File("logger.csv") will now work. (notice, the file is adjacent to the src directory.)
Put the file on level up. In the main folder of the project.
To see where the file is expected update the code in your catch clause to:
System.out.println("Error: File not found: " + motor_readings.getAbsolutePath());
Put it there and be sure to refresh your workspace in Eclipse so that the file can be seen.

Where to put a file to read from a class under a package in java?

I have a properties file contains the file name only say file=fileName.dat. I've put the properties file under the class path and could read the file name(file.dat) properly from it in the mainClass. After reading the file name I passed the file name(just name not the path) to another class under a package say pack.myClass to read that file. But the problem is pack.myClass could not get the file path properly. I've put the file fileName.dat both inside and outside the packagepack but couldn't make it work.
Can anybody suggest me that where to put the file fileName.dat so I can read it properly and the whole application would be portable too.
Thanks!
The code I'm using to read the config file and getting the file name:
Properties prop = new Properties();
InputStream in = mainClass.class.getResourceAsStream("config.properties");
prop.load(in);
in.close();
myClass mc = new myClass();
mc.readTheFile(prop.getProperty("file"));
/*until this code is working good*/
Then in myClass which is under package named pack I am doing:
public void readTheFile(String filename) throws IOException {
FileReader fileReader = new FileReader(filename); /*this couldn't get the file whether i'm putting the file inside or outside the package folder */
/*after reading the file I've to do the BufferReader for further operation*/
BufferedReader bufferedReader = new BufferedReader(fileReader);
I assume that you are trying to read properties file using getResource method of class. If you put properties file on root of the classpath you should prefix file name with '/' to indicate root of classpath, for example getResource("/file.dat"). If properties file is under the same folder with the class you on which you invoke getResource method, than you should not use '/' prefix.
When you use a relative file name such as fileName.dat, you're asking for a file with this name in the current directory. The current directory has nothing to do with packages. It's the directory from which the JVM is started.
So if you're in the directory c:\foo\bar when you launch your application (using java -cp ... pack.MyClass), it will look for the file c:\foo\bar\fileName.dat.
Try..
myClass mc = new myClass();
InputStream in = mc.getClass().getResourceAsStream("/pack/config.properties");
..or simply
InputStream in = mc.getClass().getResourceAsStream("config.properties");
..for the last line if the main is in myClass The class loader available in the main() will often be the bootstrap class-loader, as opposed to the class-loader intended for application resources.
Class.getResource will look in your package directory for a file of the specified name.
JavaDocs here
Or getResourceAsStream is sometimes more convenient as you probably want to read the contents of the resource.
Most of the time it would be best to look for the "fileName.dat" somewhere in the "user.home" folder, which is a system property. First create a File path from the "user.home" and then try to find the file there. This is a bit of a guess as you don't provide the exact user of the application, but this would be the most common place.
You are currently reading from the current folder which is determined by
String currentDir = new File(".").getAbsolutePath();
or
System.getProperty("user.dir")
To read a file, even from within a jar archive:
readTheFile(String package, String filename) throws MalformedURLException, IOException
{
String filepath = package+"/"+filename;
// like "pack/fileName.dat" or "fileName.dat"
String s = (new SourceBase()).getSourceBase() + filepath;
URL url = new URL(s);
InputStream ins = url.openStream();
BufferedReader rdr = new BufferedReader(new InputStreamReader(ins, "utf8"));
do {
s = rdr.readLine();
if(s!= null) System.out.println(s);
}
while(s!=null);
rdr.close();
}
with
class SourceBase
{
public String getSourceBase()
{
String cn = this.getClass().getName().replace('.', '/') + ".class";
// like "packagex/SourceBase.class"
String s = this.getClass().getResource('/' + cn).toExternalForm();
// like "file:/javadir/Projects/projectX/build/classes/packagex/SourceBase.class"
// or "jar:file:/opt/java/PROJECTS/testProject/dist/
// testProject.jar!/px/SourceBase.class"
return s.substring(0, s.lastIndexOf(cn));
// like "file:/javadir/Projects/projectX/build/classes/"
// or "jar:file:/opt/java/PROJECTS/testProject/dist/testProject.jar!/"
}
}

how do you execute .JAR files within java

How do you execute a JAR file within your source code?
I know that for an exe, you use
try
{
Runtime rt = Rintime.getRuntime() ;
Process p = rt.exec("Program.exe") ;
InputStream in = p.getInputStream() ;
OutputStream out = p.getOutputStream ();
InputSream err = p,getErrorStram() ;
//do whatever you want
//some more code
p.destroy() ;
}catch(Exception exc){/*handle exception*/}
Is it the same only:
rt.exec("program.exe") changes to rt.jar("program.jar") or is it something different?
In order to extract a jar file instead of exec("program.exe") you need to say
exec("<path to jar command> -xf program.jar")
Usually the jar command is available in your bin directory and if the env variables are properly set , you can even say
exec("jar -xf program.jar")
For running the jar file you can say "java -jar program.jar"
You can use java.util.jar.JarFile API to read the content of jar file.
Following is the code sample of how to use it to extract a file from a jar file:
File jar = new File("Your_Jar_File_Path")
final JarFile jarFile = new JarFile(jar);
for (final Enumeration<JarEntry> files = jarFile.entries(); files.hasMoreElements();)
{
final JarEntry file = files.nextElement();
final String fileName = file.getName();
final InputStream inputStream = jarFile.getInputStream(file);
........
while (inputStream.available() > 0)
{
yourFileOutputStream.write(inputStream.read());
}
}

Java, reading a file from current directory?

I want a java program that reads a user specified filename from the current directory (the same directory where the .class file is run).
In other words, if the user specifies the file name to be "myFile.txt", and that file is already in the current directory:
reader = new BufferedReader(new FileReader("myFile.txt"));
does not work. Why?
I'm running it in windows.
Try
System.getProperty("user.dir")
It returns the current working directory.
The current directory is not (necessarily) the directory the .class file is in. It's working directory of the process. (ie: the directory you were in when you started the JVM)
You can load files from the same directory* as the .class file with getResourceAsStream(). That'll give you an InputStream which you can convert to a Reader with InputStreamReader.
*Note that this "directory" may actually be a jar file, depending on where the class was loaded from.
None of the above answer works for me. Here is what works for me.
Let's say your class name is Foo.java, to access to the myFile.txt in the same folder as Foo.java, use this code:
URL path = Foo.class.getResource("myFile.txt");
File f = new File(path.getFile());
reader = new BufferedReader(new FileReader(f));
Files in your project are available to you relative to your src folder. if you know which package or folder myfile.txt will be in, say it is in
----src
--------package1
------------myfile.txt
------------Prog.java
you can specify its path as "src/package1/myfile.txt" from Prog.java
If you know your file will live where your classes are, that directory will be on your classpath. In that case, you can be sure that this solution will solve your problem:
URL path = ClassLoader.getSystemResource("myFile.txt");
if(path==null) {
//The file was not found, insert error handling here
}
File f = new File(path.toURI());
reader = new BufferedReader(new FileReader(f));
Thanks #Laurence Gonsalves your answer helped me a lot.
your current directory will working directory of proccess so you have to give full path start from your src directory like mentioned below:
public class Run {
public static void main(String[] args) {
File inputFile = new File("./src/main/java/input.txt");
try {
Scanner reader = new Scanner(inputFile);
while (reader.hasNextLine()) {
String data = reader.nextLine();
System.out.println(data);
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("scanner error");
e.printStackTrace();
}
}
}
While my input.txt file is in same directory.
Try this:
BufferedReader br = new BufferedReader(new FileReader("java_module_name/src/file_name.txt"));
try using "."
E.g.
File currentDirectory = new File(".");
This worked for me

Categories