folder is created in eclipse home not in web application - java

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();

Related

Copying File In Current Working Directory is Not Working

private void copyFile() throws IOException {
Path destination;
String currentWorkingDir = System.getProperty("user.dir");
File fileToCopy = component.getArchiveServerFile();
if (path.contains(File.separator)) {
destination = Paths.get(path);
} else {
destination = Paths.get(currentWorkingDir + File.separator + path);
}
if (!Files.exists(destination)) {
try {
Files.createDirectories(destination);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
FileUtils.copyFileToDirectory(fileToCopy, new File(destination.toString()));
}
}
Basically what I'm trying to do here is copying a file in some location using the path provided in the class's constructor. The logic is like this:
If the path has file separator, I consider it a full path and copy the file at the end.
If the path doesn't have file separator, I copy the file in the working directory from which the .exe file was launched.
So far, only the first option works (the full path). For some reason, the working directory option is not working and I can't figure out why.
UPDATE: If I just change the following line:
String currentWorkingDir = System.getProperty("user.dir");
to
String currentWorkingDir = System.getProperty("user.home");
It works. So I'm guessing the problem is coming from user.dir? Maybe at runtime, the folder is already being used and as a result, it can't copy the file into it?
The weird thing is, I don't have any exceptions or error, but nothing happens as well.
UPDATE 2: I think the problem here is that I'm trying to copy a file which is embedded in the application (.exe file) that I'm executing during runtime, and java can't copy it while the current working directory is being used by the application.
UPDATE 3:
Since this copy method is used in an external library, I had to come up with another way (other than logs) to see the content of system property user.dir. So I wrote I little program to create a file and write in it the value return by the property.
To my surprise, the path is not where my application was launched. It was in:
C:\Users\jj\AppData\Local\Temp\2\e4j1263.tmp_dir1602852411
Which is weird because I launched the program from :
C:\Users\jj\workspace\installer\product\target\
Any idea why I'm getting this unexpected value for user.dir?

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 - Get file from jar

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);
}
}

How to set file path to src folder of project

I want to make a program that you can email to someone and they can run it.
Right now my code for making a file is like this:
File f = new File("/Users/S0urceC0ded/Desktop/Code/project/JavaStuffs/src/axmlfile.xml);
f.createNewFile();
But what if someones username is not S0urceC0ded, or they put the project in a different place? How could I set the file path to the src folder plus the filename?
Leave the path off entirely, it will use the directory of the project.
Change
File f = new File("/Users/S0urceC0ded/Desktop/Code/project/JavaStuffs/src/axmlfile.xml");
To
File f = new File("axmlfile.xml");
I generally use code like this for temporary file storage, this way it gets cleaned up when the application finishes. If required you can allow the user to save a version of the file or move it to a permanent location.
try{
//create a temporary file
File temp = File.createTempFile("axmlfile", ".xml");
System.out.println("Location: " + temp.getAbsolutePath());
}catch(IOException e){
e.printStackTrace();
}

Making folder that will be accessable in jar

I want an option that when ever user selects autologin option...My program will make a folder and it will save a file in it...when the program will start it will look for folder and than file inside it. Problem is when i run my code via netbeans it is running perfectly but when i run it through jar it do not find any folder. Any body can guide me, what is best way to make a folder at run time and access it.
Down is my file writing code...
private void writeSerializableUserObject(boolean isAutoLogin , boolean isAutoRemember){
SerializableUser serializeUserObj = new SerializableUser();
serializeUserObj.setUserEmail(TempSessionUser.getTempUser().getEmail());
serializeUserObj.setUserPassword(TempSessionUser.getTempUser().getPassword());
serializeUserObj.setUserName(TempSessionUser.getTempUser().getF_name());
serializeUserObj.setIsAutoLogin(isAutoLogin);
if(isAutoRemember){
serializeUserObj.setIsAutoRemember(true);
}
System.out.println("in side method.......");
Edit
String path = System.getProperty("user.home");
File file = new File(path+"/user.ser");
if(!file.exists()){
file.mkdir();
}
try {
FileOutputStream fileOutPut = new FileOutputStream(file);
ObjectOutputStream oos;
try {
oos = new ObjectOutputStream(fileOutPut);
oos.writeObject(serializeUserObj);
oos.flush();
oos.close();
} catch (IOException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}//Inner catch statment end
} catch (FileNotFoundException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}//Outer Catch statment end
}
After editing it is giving me this exception...within netbeans execution.her uptill HaseebAimal is my home directory path
java.io.FileNotFoundException: C:\Users\HaseebAimal\UserData\user.ser (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:194)
at java.io.FileOutputStream.<init>(FileOutputStream.java:145)
getClass().getResource("/UserData") gives you a location in the class path which sometimes (usually) isn't a directory in the file system. Instead, you should probably pick one or more of:
Prompt the user for a save location.
Use a default location of some file or folder in the user's home directory, which you can get with System.getProperty("user.home").
Save it in the current working directory, which you can get with System.getProperty("user.dir").
The last option is probably the worst unless you know what the working directory will always be because you've handled the installation of your app in some way.
Before creating the FileOutputStream check what do file.canRead() and file.canWrite() return.
You need to make sure that the application can write to the location. If you do not have access to the location, try changing the directory to something else where you have write access.
Something like:
String path = "D:/test";

Categories

Resources