Java - Get file from jar - java

I need to catch some directory within the application. For that I have a small demonstration:
String pkgName = TestClass.class.getPackage().getName();
String relPath = pkgName.replace(".", "/");
URL resource = ClassLoader.getSystemClassLoader().getResource(relPath);
File file = new File(resource.getPath());
System.out.println("Dir exists:" + file.exists());
While running application from IDE I receive my goal and I can find my directory. But running application as JAR file, does not return a valid "file" (from Javas perspective) and my sout gives me back File exists:false. Is there some way to get this file? In this case, the file is a directory.

Java ClassPath is an abstraction that differs from a filesystem abstraction.
A classpath element may exist in two physical ways:
exploded with classpath pointing to the root directory
packed in a JAR archive
Unfortunatelly, the file.getPath does return a File object if classpath is pointing to file system but it does not if you refer to a JAR file.
In 99% of all cases you should read the contents of a resource using InputStream.
Here is a snippet, that uses IOUtils from apache commons-io to load the whole file content into a String.
public static String readResource(final String classpathResource) {
try {
final InputStream is = TestClass.class.getResourceAsStream(classpathResource);
// TODO verify is != null
final String content = IOUtils.toString(
is, StandardCharsets.UTF_8);
return content;
} catch (final IOException e) {
throw new UncheckedIOException(e);
}
}

Related

store file in spring boot resource folder after deployment

I have deployed a spring-boot application JAR file. Now, I want to upload the image from android and store it in the myfolder of resource directory. But unable to get the path of resource directory.
Error is:
java.io.FileNotFoundException: src/main/resources/static/myfolder/myimage.png
(No such file or directory)
This is the code for storing the file in the resource folder
private final String RESOURCE_PATH = "src/main/resources";
String filepath = "/myfolder/";
public String saveFile(byte[] bytes, String filepath, String filename) throws MalformedURLException, IOException {
File file = new File(RESOURCE_PATH + filepath + filename);
OutputStream out = new FileOutputStream(file);
try {
out.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}
return file.getName();
}
UPDATED:
This is what I have tried
private final String RESOURCE_PATH = "config/";
controller class:
String filepath = "myfolder/";
String filename = "newfile.png"
public String saveFile(byte[] bytes, String filepath, String filename) throws MalformedURLException, IOException {
//reading old file
System.out.println(Files.readAllBytes(Paths.get("config","myfolder","oldfile.png"))); //gives noSuchFileException
//writing new file
File file = new File(RESOURCE_PATH + filepath + filename);
OutputStream out = new FileOutputStream(file); //FileNotFoundException
try {
out.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}
return file.getName();
}
Project structure:
+springdemo-0.0.1-application.zip
+config
+myfolder
-oldfile.png
-application.properties
+lib
+springdemo-0.0.1.jar
+start.sh
-springdemo-0.0.1.jar //running this jar file
Usually when you deploy an application (or start it using Java), you start a JAR file. You don't have a resource folder. You can have one and access it, too, but it certainly won't be src/main/resources.
When you build your final artifact (your application), it creates a JAR (or EAR or WAR) file and your resources, which you had in your src/main/resources-folder, are copied over to the output directory and included in the final artifact. That folder simply does not exist when the application is run (assuming you are trying to run it standalone).
During the build process target/ is created and contains the classes, resources, test-resources and the likes (assuming you are building with Maven; it is a little different if you build using Gradle or Ant or by hand).
What you can do is create a folder e.g. docs next to your final artifact, give it the appropriate permissions (chmod/chown) and have your application output files into that folder. This folder is then expected to exist on the target machine running your artifact, too, so if it doesn't, it would mean the folder does not exist or the application lacks the proper permissions to read from / write to that folder.
If you need more details, don't hesitate to ask.
Update:
To access a resource, which is bundled and hence inside your artifact (e.g. final.jar), you should be able to retrieve it by using e.g. the following:
testText = new String(ControllerClass.class.getResourceAsStream("/test.txt").readAllBytes());
This is assuming your test.txt file is right under src/main/resources and was bundled to be directly in the root of your JAR-file (or target folder where your application is run from). ControllerClass is the controller, which is accessing the file. readAllBytes just does exactly this: read all the bytes from a text file. For accessing images inside your artifact, you might want to use ImageIO.
IF you however want to access an external file, which is not bundled and hence not inside your artifact, you may use File image = new File(...) where ... would be something like "docs/image.png". This would require you to create a folder called docs next to your JAR-artifact and put a file image.png inside of it.
You of course also may work with streams and there are various helpful libraries for working with input- and output streams.
The following was meant for AWT, but it works in case you really want to access the bytes of your image: ImageIO. In a controller you usually wouldn't want to do that, but rather have your users access (and thus download) it from a given available folder.
I hope this helps :).

JAVA - Read configuration file from Eclipse and JAR

I need to properly set the path (or the tree structure in Eclipse) to read a configuration file both in a development environment (Eclipse) and production environment (by running a jar file).
Currently, I read the file in two ways:
- public String getProperty(String parameter) {
String property = null;
try {
//prop.load(getClass().getClassLoader().getResourceAsStream("configuration.properties"));
prop.load(getClass().getClassLoader().getResourceAsStream("src/configuration.properties"));
property = prop.getProperty(parameter);
}
catch (IOException e) {
e.getMessage();
}
return property;
}
- try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
...
}
The problem is with the first method: in Eclipse I have to set
getResourceAsStream("configuration.properties"));
while for jar I have to add src
getResourceAsStream("src/configuration.properties"));
since the jar file is located at the same level of a src folder containing the configuration file.
For the FileReader method the src/configuration.properties path works fine in both cases.
In Eclipse I have the following tree structure:
ProjectName
+ src/
+ filePackage/
FileLoader.java
+ config_file
How could I manage both cases using a common approach/path?
Thanks

folder is created in eclipse home not in web application

I have create folder (i.e uploads ) in web application. I want to create one more folder inside "uploads" folder at runtime depends one the username of user. for this i have write below code. This code is creating folder and file but the location is different that i expected.
the location that i am getting is in eclipse location not web application location
D:\PAST\RequiredPlugins\JUNO\eclipse\uploads\datto\adhar.PNG
then i am getting error in FileOutStream that "system can't find the location specified."
public String getFolderName(String folderName, MultipartFile uploadPhoto)
throws ShareMeException {
File uploadfFile = null;
try {
File file = new File("uploads\\" + folderName);
if (!file.exists()) {
file.mkdir();
}
uploadfFile = new File(file.getAbsoluteFile()
+ "\\"+uploadPhoto.getOriginalFilename());
if (uploadfFile.exists()) {
throw new ShareMeException(
"file already exist please rename it");
} else {
uploadfFile.createNewFile();
FileOutputStream fout = new FileOutputStream(uploadfFile);
fout.write(uploadPhoto.getBytes());
fout.flush();
fout.close();
}
} catch (IOException e) {
throw new ShareMeException(e.getMessage());
}
return uploadfFile.getAbsolutePath();
}
i want to save uploaded file in web app "uploads" folder
Your filename is not absolute: uploads\folderName is resolved against the current directory, which the Eclipse launcher sets to JUNO\eclipse.
You should introduce an application variable like APP_HOME and resolve any data directory (including upload) against this variable.
Also, I suggest not to name anything (neither files nor directories) on your filesystem after user-entered input: you are asking for troubles (unicode characters in the user name) and especially security holes (even in combination with the unicode thing). If you really want to use the filesystem, keep the filename anonymous (1.data, 2.data, ...) and keep metadata inside some database.
You can do something on below lines in your webapp:-
String folderPath= request.getServletContext().getRealPath("/");
File file = new File (folderPath+"upload");
file.mkdir();

Write a file in resources in a java maven project

I have to implement a temporary "persistence" solution for retrieving some definitions ( simple json strings). I have a rest endpoint which creates an instance of my object and then I want to write the json definition inside a file.
I currently have a class loader which loads files from the resources folder inside my module, I use these to grab the query results. Now I want to save a new definition, and write it to a file inside the resources folder.
However, I am unsuccessful in doing so. I grab the path from the existing file with the classloader and when I try to create a new file using FileUtils, it either throws some errors, or creates the file in D:.
Is there a way to use the resources folder to add/edit files at runtime ? Here is some code also with one of the many ways i've tried it.
public String writeDocument(String path, String content) throws IOException {
\\Example call: writeDocument("/definitions/somedefinition.txt",jsonStringHere);
\\where /definitions/somedefinition.txt is placed in /resources
ClassLoader classLoader = getClass().getClassLoader();
final URL url = classLoader.getResource(path);
final File file;
String finalPath = null;
try {
file = Paths.get(url.toURI()).toFile();
FileUtils.writeStringToFile(file, content);
finalPath = file.getAbsolutePath();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return finalPath;
}

How to read file from relative path in Java project? java.io.File cannot find the path specified

I have a project with 2 packages:
tkorg.idrs.core.searchengines
tkorg.idrs.core.searchengines
In package (2) I have a text file ListStopWords.txt, in package (1) I have a class FileLoadder. Here is code in FileLoader:
File file = new File("properties\\files\\ListStopWords.txt");
But I have this error:
The system cannot find the path specified
Can you give a solution to fix it?
If it's already in the classpath, then just obtain it from the classpath instead of from the disk file system. Don't fiddle with relative paths in java.io.File. They are dependent on the current working directory over which you have totally no control from inside the Java code.
Assuming that ListStopWords.txt is in the same package as your FileLoader class, then do:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.getPath());
Or if all you're ultimately after is actually an InputStream of it:
InputStream input = getClass().getResourceAsStream("ListStopWords.txt");
This is certainly preferred over creating a new File() because the url may not necessarily represent a disk file system path, but it could also represent virtual file system path (which may happen when the JAR is expanded into memory instead of into a temp folder on disk file system) or even a network path which are both not per definition digestable by File constructor.
If the file is -as the package name hints- is actually a fullworthy properties file (containing key=value lines) with just the "wrong" extension, then you could feed the InputStream immediately to the load() method.
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("ListStopWords.txt"));
Note: when you're trying to access it from inside static context, then use FileLoader.class (or whatever YourClass.class) instead of getClass() in above examples.
The relative path works in Java using the . specifier.
. means same folder as the currently running context.
.. means the parent folder of the currently running context.
So the question is how do you know the path where the Java is currently looking?
Do a small experiment
File directory = new File("./");
System.out.println(directory.getAbsolutePath());
Observe the output, you will come to know the current directory where Java is looking. From there, simply use the ./ specifier to locate your file.
For example if the output is
G:\JAVA8Ws\MyProject\content.
and your file is present in the folder "MyProject" simply use
File resourceFile = new File("../myFile.txt");
Hope this helps.
The following line can be used if we want to specify the relative path of the file.
File file = new File("./properties/files/ListStopWords.txt");
InputStream in = FileLoader.class.getResourceAsStream("<relative path from this class to the file to be read>");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
try .\properties\files\ListStopWords.txt
I could have commented but I have less rep for that.
Samrat's answer did the job for me. It's better to see the current directory path through the following code.
File directory = new File("./");
System.out.println(directory.getAbsolutePath());
I simply used it to rectify an issue I was facing in my project. Be sure to use ./ to back to the parent directory of the current directory.
./test/conf/appProperties/keystore
While the answer provided by BalusC works for this case, it will break when the file path contains spaces because in a URL, these are being converted to %20 which is not a valid file name. If you construct the File object using a URI rather than a String, whitespaces will be handled correctly:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.toURI());
Assuming you want to read from resources directory in FileSystem class.
String file = "dummy.txt";
var path = Paths.get("src/com/company/fs/resources/", file);
System.out.println(path);
System.out.println(Files.readString(path));
Note: Leading . is not needed.
I wanted to parse 'command.json' inside src/main//js/Simulator.java. For that I copied json file in src folder and gave the absolute path like this :
Object obj = parser.parse(new FileReader("./src/command.json"));
For me actually the problem is the File object's class path is from <project folder path> or ./src, so use File file = new File("./src/xxx.txt"); solved my problem
For me it worked with -
String token = "";
File fileName = new File("filename.txt").getAbsoluteFile();
Scanner inFile = null;
try {
inFile = new Scanner(fileName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while( inFile.hasNext() )
{
String temp = inFile.next( );
token = token + temp;
}
inFile.close();
System.out.println("file contents" +token);
If text file is not being read, try using a more closer absolute path (if you wish
you could use complete absolute path,) like this:
FileInputStream fin=new FileInputStream("\\Dash\\src\\RS\\Test.txt");
assume that the absolute path is:
C:\\Folder1\\Folder2\\Dash\\src\\RS\\Test.txt
String basePath = new File("myFile.txt").getAbsolutePath();
this basepath you can use as the correct path of your file
if you want to load property file from resources folder which is available inside src folder, use this
String resourceFile = "resources/db.properties";
InputStream resourceStream = ClassLoader.getSystemClassLoader().getResourceAsStream(resourceFile);
Properties p=new Properties();
p.load(resourceStream);
System.out.println(p.getProperty("db"));
db.properties files contains key and value db=sybase
If you are trying to call getClass() from Static method or static block, the you can do the following way.
You can call getClass() on the Properties object you are loading into.
public static Properties pathProperties = null;
static {
pathProperties = new Properties();
String pathPropertiesFile = "/file.xml";
// Now go for getClass() method
InputStream paths = pathProperties.getClass().getResourceAsStream(pathPropertiesFile);
}

Categories

Resources