File is not deleted when file path is generated dynamically - java

I am facing a problem but have not able to solve it yet. Let me share what I have done till now. I tried to delete a file using java.nio.file packages. And below is my code.
// directory will be dynamically generated.
String directory = fileDirectory+ "//" + fileName;
Path path = Paths.get(directory);
if (Files.exists(path)) {
Files.delete(path);
}
I generated the path correctly. But when Files.exists(path) calls it return false. That's why file is not deleted. But if I generated the directory string by hard-coded than it works perfectly.
// hard-coded directory works perfectly.
String directory = "C://opt//tomcat//webapps//resources//images//sprite.jpg";
I also tried the another method Files.deleteIfExists(path);. Which check the both the file existence and delete the file.
The other packages org.apache.commons.io.FileUtils and java.io.File have tried. But can't resolve the issue.
Note: My application is in spring-boot. And I read the directory from the application.properties file for both save images and delete images.
EDIT:
file uploading I mean save into the directory is perfectly worked. But file deletion does not work.
application.properties
image.root.dir=images
image.root.save.dir=C:/opt/tomcat/webapps/resources/
in implementation file
#Value("${image.root.dir}")
private String UPLOADED_FOLDER;
#Value("${image.root.save.dir}")
private String saveDir;
String directory = saveDir + UPLOADED_FOLDER + "/" + fileName;
save file into directory
String directory = saveDir + UPLOADED_FOLDER + "/";
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(directory);
if (!Files.exists(path)) {
Files.createDirectories(path);
}
path = Paths.get(directory, file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
logger.error("save image into directory : " + e);
}

String directory = fileDirectory+ "//" + fileName;
This is not the correct separator used between a directory and a file name, though it seems to work as well.
This means the problem is not the separator, but a mismatch between the code that you use to generate the path and this code. You're generating the directory into somewhere else than where this is pointing.

Related

Java: How to get path of a file when running JAR file

When I use relative path, I can run my Java program from Eclipse. But when I run it as a JAR file, the path doesn't work anymore. In my src/components/SettingsWindow.java I have:
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("./src/files/profile.ser"));
I get a FileNotFoundException.
My file directory looks like this:
file directory
What I've tried:
String filePath = this.getClass().getResource("/files/profile.ser").toString();
String filePath = this.getClass().getResource("/files/profile.ser").getPath();
String filePath = this.getClass().getResource("/files/profile.ser").getFile().toString();
And I'd just put filePath in new FileInputStream(filePath) but none of these work and I still get a FileNotFoundException. When I System.out.println(filePath) it says: files/profile.ser
I'm trying to get the path of src/files/profile.ser while I'm in src/components/SettingsWindow.java
You can get the URL to the class:
String path =
String.join("/", getClass().getName().split(Pattern.quote(".")))
+ ".class";
URL url = getClass().getResource("/" + path);
which will either yield "file:/path/to/package/class.class" or "jar:/path/to/jar.jar!/package/class.class". You either can work with the URL or use
JarFile jar =
((JarURLConnection) url.openConnection()).getJarFile();
and use jar.getName() to get the path to parse to get your installation directory.
To get the current JAR file path I use:
public static String getJarFilePath() throws FileNotFoundException {
String path = getClass().getResource(getClass().getSimpleName() + ".class").getFile();
if(path.startsWith("/")) {
throw new FileNotFoundException("This is not a jar file: \n"+path);
}
if(path.lastIndexOf("!")!=-1) path = path.substring(path.lastIndexOf("!/")+2, path.length());
path = ClassLoader.getSystemClassLoader().getResource(path).getFile();
return path.substring(0, path.lastIndexOf('!')).replaceAll("%20", " ");
}

save file with different name in spring boot

I am uploading one file that is kind of multipart. I want this file to save with different name.
tried with renameTo method but did not work.
tried moveto but did not work
below is my code
here graphic is multipart file
String picName = graphic.getOriginalFilename();EN_LENGTH) + "." + graphic.getContentType();
Path dirLocation = Paths.get(dirPath);
String newName = CommonUtil.getToken(Constants.STANDRAD_TOKEN_LENGTH) + "." + graphic.getContentType();
try {
InputStream is = graphic.getInputStream();
Files.copy(is, dirLocation.resolve(picName), StandardCopyOption.REPLACE_EXISTING);
boolean a = new File(dirLocation+picName).renameTo(new File(dirLocation+newName));
for security reasons I want it to save with different name.
Solved the issue by correcting the filename. The file name which I was generating randomly was not correct. it had some slash etc.

Java get resource is not working

I try to read a resource file from my application but it doesn't work.
Code:
String filename = getClass().getClassLoader().getResource("test.xsd").getFile();
System.out.println(filename);
File file = new File(filename);
System.out.println(file.exists());
Output when I execute the jar-file:
file:/C:/Users/username/Repo/run/Application.jar!/test.xsd
false
It works when I run the application from IntelliJ but not when I execute the jar-file. If I open my jar-file with 7-zip test.xsd is located in the root-folder. Why isn't the code working when I execute the jar-file?
Also, File refers to actual OS file-system files; in the OS's file-system, there is only a jar file, and that jar file is not a folder. You should either extract the contents of the URL to a temporary file, or operate with its bytes in-memory or as a stream.
Note that myURL.getFile() is returning a String representation, and not an actual File. In a similar way, this will not work:
File f = new URL("http://www.example.com/docs/resource1.html").getFile();
f.exists(); // always false - will not be found in the local filesystem
A nice wrapper could be the following:
public static File openResourceAsTempFile(ClassLoader loader, String resourceName)
throws IOException {
Path tmpPath = Files.createTempFile(null, null);
try (InputStream is = loader.getResourceAsStream(resourceName)) {
Files.copy(is, tmpPath, StandardCopyOption.REPLACE_EXISTING);
return tmpPath.toFile();
} catch (Exception e) {
if (Files.exists(tmpPath)) Files.delete(tmpPath);
throw new IOException("Could not create temp file '" + tmpPath
+ "' for resource '" + resourceName + "': " + e, e);
}
}

Java path in Linux

I have a bit problem, and i dont seem to understand what is causing it.
i have a folder in my project, and in that folder i have a class, and i have a resource file (in this case jasper report).
but the only way i can access file is with absolute path or some path that starts from root of my project.
String path = "src/main/java/Views/LagerMain/lager.jrxml";
^^this works, both my class LagerController and lager.jrxml are under LagerMain folder, but when i try to do this :
String path = "lager.jrxml";
i have an error that file is not found.
I tried googling this to have a better understanding but i found nothing.
Bottom line, why cant i access my file, from class when they are both on same place, why does not relative path work.
If the main class is in a different directory, then the program will try to accesslager.jrxml there instead of the directory of the regular class.
For regular-class directory:
String path = new String(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
.getPath() + System.getProperty("line.separator") + "lager.jrxml");
If that doesn't work, try this:
// your directory
File f = new File("src");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("lager") && name.endsWith("jrxml");
}
});
If you have more than one file with the name lager.jrxml, then this method will return both of them and you will need to use a for to cycle through them. Otherwise, you can just use
String path = new String(matchingFiles[0].getAbsolutePath())
For main-class directory:
String path = new String(System.getProperty("user.dir")
+ System.getProperty("line.separator") + "lager.jrxml");

getResourceAsStream() is returning null. Properties file is not loading

I am trying to load properties file. Here is my structure
Now i am trying to load test.properties file. But i am getting null. Here how i am doing
public class Test {
String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + workingDir);
File temp = new File(workingDir + "\\" + "test.properties");
String absolutePath = temp.getAbsolutePath();
System.out.println("File path : " + absolutePath);
Properties properties = null;
try {
properties = new Properties();
InputStream resourceAsStream = Test.class.getClassLoader().getResourceAsStream(absolutePath);
if (resourceAsStream != null) {
properties.load(resourceAsStream);
}
} catch (IOException e) {
e.printStackTrace();
}
System.exit(0);
} //end of class Test
This program prints
Current working directory : D:\Personal Work\eclipse 32 Bit\workspace\Spring Integration\LS360BatchImportIntegration
File path : D:\Personal Work\eclipse 32 Bit\workspace\Spring Integration\LS360BatchImportIntegration\test.properties
But it is not loading properties file from this path. Although it is present there. Why i am getting null ?
Thanks
Edit---
----------------------------
String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + workingDir);
File temp = new File(workingDir, "test.properties");
String absolutePath = temp.getAbsolutePath();
System.out.println("File path : " + absolutePath);
try {
properties = new Properties();
InputStream resourceAsStream = new FileInputStream(temp);
if (resourceAsStream != null) {
properties.load(resourceAsStream);
}
} catch (IOException e) {
e.printStackTrace();
}
System.exit(0);
Current working directory : D:\Personal Work\eclipse 32 Bit\workspace\Spring Integration\LS360BatchImportIntegration
File path : D:\Personal Work\eclipse 32 Bit\workspace\Spring Integration\LS360BatchImportIntegration\test.properties
java.io.FileNotFoundException: D:\Personal Work\eclipse 32 Bit\workspace\Spring Integration\LS360BatchImportIntegration\test.properties (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at com.softech.ls360.integration.BatchImport.main(BatchImport.java:57)
Oh oh ... There are several problems here:
1) In your first provided code snippet, you are using a ClassLoader for loading a resource file. This is indeed a good decision. But the getResourceAsStream method needs a "class-path relative" name. You are providing an absolute path.
2) Your second code snippet (after edit) results in not being able to find the file "D:...\LS360BatchImportIntegration\test.properties". According to your screenshot, the file should be "D:...\LS360AutomatedRegulatorsReportingService\test.properties". This is another directory.
I fear, that your descriptions are not up to date with the findings on your machine.
But let's just move to a reasonable solution:
1) In your Eclipse project (the screenshot tells us, that you are using Eclipse), create a new directory named "resources" in the same depth as your "src" directory. Copy - or better move - the properties file into it.
2) This new directory must be put into the "build path". Right-click the directory in the Package Explorer or Project Explorer view, select "Build Path", then "Use as Source Folder". Note: This build path will be the class path for the project, when you run it.
3) As the resources directory now is part of your class path and contains your properties file, you can simply load it with getResourceAsStream("test.properties").
EDIT
I just see, that you also use Maven (the pom.xml file). In Maven, such a resources directory exists by default and is part of the build path. It is "src/main/resources". If so, just use this.
Please put your property file in /src/main/resources folder and load from ClassLoader. It will be fix.
like
/src/main/resources/test.properties
Properties properties = null;
try {
properties = new Properties();
InputStream resourceAsStream = Test.class.getClassLoader().getResourceAsStream("test.properties");
if (resourceAsStream != null) {
properties.load(resourceAsStream);
}
} catch (IOException e) {
e.printStackTrace();
}
You are using the class loader (which reads in the classpath) whereas you are using the absolute path.
Simply try:
InputStream resourceAsStream = new FileInputStream(temp);
As a side note, try instanciating your file doing:
File temp = new File(workingDir, "test.properties");
to use the system-dependent path spearator.
I had a similar problem with a file not being found by getResourceAsStream(). The file was in the resources folder (src/main/resources), and still not found.
The problem got resolved when I went into the eclipse Package Explorer and "refreshed" the resources folder. It was in the directory, but Eclipse did not see it until the folder was refreshed (right-click on the folder and select Refresh).
I hope this helps !!
You can keep your test.properties into src/main/resources
public static Properties props = new Properties();
InputStream inStream = Test.class.getResourceAsStream("/test.properties");
try {
loadConfigurations(inStream);
} catch (IOException ex) {
String errMsg = "Exception in loading configuration file. Please check if application.properties file is present in classpath.";
ExceptionUtils.throwRuntimeException(errMsg, ex, LOGGER);
}
public static void loadConfigurations(InputStream inputStream) throws IOException{
props.load(inputStream);
}
You're passing a file path to getResourceAsStream(String name), but name here is a class path, not a file path...
You could make sure the file is on your classpath, or use a FileInputStream instead.

Categories

Resources