How can I write a file in tomcat folder? - java

I have deployed my application in Apache Tomcat.
I have a folder(assets) to save the files. So want to write a file inside webapps/assets
I tried the following code for that
private String uploadedFiles(MultipartFile files) throws IOException {
String filePath = "../assets/users/image/" + files.getOriginalFilename();
File file = new File(filePath);
byte[] bytes = file.getBytes();
FileOutputStream out = new FileOutputStream(file);
out.write(bytes);
out.close();
But i am getting java.io.FileNotFoundException: ../assets/myfile.jpg (The system cannot find the path specified)
How can save this file?
Note: I want this kind of folder structure. Since I will save "../assets/myfile.png" in the database to access from the client application deployed in the same server.

You can get the tomcat home path with
System.getProperty( "catalina.base" );
You can then add to this your path, in your case /webapps/assets
Hope this helps :)

Maybe I am wrong, but you should give bytes from Multipart files !
And such of kind
../assets/users/image/
is wrong. I think, you should start with root folder, or use Paths.get() nio.

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 :).

Confused on getting the path for writing a text file using a Servlet

I've the below project structure in my eclipse.
and my code in servlet is as below.
File entityFile = new File(getServletContext().getContextPath() + "/EntityList/entities.txt");
FileWriter fout = new FileWriter(entityFile);
fout.write("The Content");
fout.close();
here basically I'm trying to write to a file available at /EntityList/entities.txt, but when I run this, I get the exception as below.
SEVERE: Servlet.service() for servlet
[com.luis.servlets.WriteEntityToAFile] in context with path
[/LUISWebUI] threw exception java.io.FileNotFoundException:
\LUISWebUI\EntityList\entities.txt (The system cannot find the path
specified)
I know that I'm going wrong with the path, Can someone please put me in the right direction.
Update
Apologies for the confusion.
I'm sending some data from jsp to servlet to write to the entities.txt file. I'm able to capture it in servlet(Cross checked it by doing sysout).
First of all I think you have a typo problem, try /EntitiesList/entities.txt instead of /EntityList/entities.txt.
Also, move the /EntitiesList/entities.txt under /WEB-INF/ for example, so that your servlet class can access it.
You can read a more detailed explanation in this SO answer.
Edit:
About writing to file: your application will be packaged inside a WAR file so you won't be able to write to it, only read from it (more about this here).
But you can just use this way of creating directly a file outside the WAR and using this location to write your content (before that, make sure you have appropriate rights):
File entityFile = new File(getServletContext().getContextPath() + "entities.txt");
FileWriter fOut = new FileWriter(entityFile);
fOut.write("The Content");
fOut.close();
Or if you want the directory also, you'll have to execute some additional steps, create it first then specify the file name inside it where you want to write:
File entityFolder = new File(getServletContext().getContextPath() + "EntitiesList");
entityFolder.mkdir();
File entityFile = new File(entityFolder, "entities.txt");
FileWriter fOut = new FileWriter(entityFile);
fOut.write("The Content");
fOut.close();
First there is Typo error in your path
Second you should use getResourceAsStream() for loading file for writing.
Code example:
InputStream input = getServletContext().
getResourceAsStream("/WEB-INF/EntityList/entities.txt");
Files.copy(InputStream input , Path target)
//Or Files.copy(Path source, OutputStream out)
It seem easier to use FileInputStream, but it is better to use ResourceStream.
Read here https://stackoverflow.com/a/2161583/8307755
https://stackoverflow.com/a/2308224/8307755

Jar null point exception when reading a file

The following code works fine on my Eclipse IDE.
private void getLayersAndDisplay() throws Exception {
URL imageURL = ImageLab.class.getResource("earthlights.jpg");
File imageFile = new File(imageURL.toURI());
URL shapeFileURL = ImageLab.class.getResource("countries.shp");
File shapeFile = new File(shapeFileURL.toURI());
URL shapeFileURL2 = ImageLab.class.getResource("Brasil.shp");
File shapeFile2 = new File(shapeFileURL2.toURI());
displayLayers(imageFile, shapeFile,shapeFile2);
}
However, when compiling to a jar, it gives me a null pointer exception. I thought that since I am getting it as a class.getResource, it would work. Can't I use the File class in a jar? Not even in a cast?
Thank you
An entry of a zip file (that's what a jar file is) is not a file existing in your file system. So you can't use a File, which represents a path on your filesystem, to refer to a zip entry. And you can't use file IO to read its content, since it's not a file.
I have no idea what you want to do, but if you want to read the content of the jar resource, just use ImageLab.class.getResourceAsStream() to get an InputStream back, reading from the entry.

java.lang.NullPointerException while getting a filepath in Java (executing through a jar file)

I am getting an NPE at the point of getting path of a File (an sh file in assets folder).
I have tried to read about NPE i detail from the following thread, but this actually could not solve my problem.
What is a NullPointerException, and how do I fix it?
Following is my code snippet:
File absPathofBash;
url = ClassLoader.class.getResource("assets/forbackingup.sh");
absPathofBash = new File(url.getPath());
Later I'm using it in a ProcessBuilder, as
ProcessBuilder pb = new ProcessBuilder(url.getPath(), param2, param3)
I've also tried getting the absolute path directly, like
absPathofBash = new File("assets/forbackingup.sh").getAbsolutePath();
Using the latter way, I am able to process it, but if I create a jar then the file cannot be found. (although the Jar contains the file within the respective folder assets)
I would be thankful if anyone can help me on that.
Once you have packaged your code as a jar, you can not load files that are inside the jar using file path, instead they are class resources and you have to use this to load:
this.getClass().getClassLoader().getResource("assets/forbackingup.sh");
This way you load assets/forbackingup.sh as an absolute path inside your jar. you also can use this.getClass().getResource() but this way the path must be relative to this class path inside jar.
getResource method gives you an URL, if you want to get directly an InputStream you can use getResourceAsStream
Hope it helps!
Since the file itself is in the jar file, you could try using:
InputStream is = this.getClass().getClassLoader().getResourceAsStream(fileNameFromJar);
In case of jar file , classloader will return URL different than that of when the target file is not embedded inside jar. Refer to answer on link which should help u :
How to use ClassLoader.getResources() in jar file
I got it done by creating a temp file. Though it's not difficult, yet I'm posting the code patch here:
InputStream stream = MyClass.class.getClassLoader().
getResourceAsStream("assets/forbackingup.sh");
File temp = File.createTempFile("forbackingup", ".sh");
OutputStream outputStream =
new FileOutputStream(temp);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = stream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
outputStream.close();
}
Now, we have this temp file here which we can pipe to the ProcessBuilder like,
String _filePath=temp.getPath();
ProcessBuilder pb = new ProcessBuilder(url.getPath(), param2, param3)
Thank you everyone for your considerations.
You can use Path class like :
Path path = Paths.get("data/test-write.txt");
if(!Files.exists(path)){
// can handle null pointer exception
}

maven/spring uploaded on jelastic having images problem, when uploaded by user?

I have uploaded my maven/spring project on jelastic and using following to save images:
ServletContext servletContext = request.getSession().getServletContext();
String absoluteFilesystemPath = servletContext.getRealPath("/");
byte[] fileData = file.getBytes();
String name=Trader.getImage();
if (fileData.length != 0) {
String fileName =login.getUserName()+".jpeg";
File f = new File(absoluteFilesystemPath+"\\img\\"+fileName);
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(fileData);
fileOutputStream.close();
}
It is working on localhost images are saved in img folder while on server it is saved on absolute path as name "img/xyz.jpeg"
i want to save it on
myproject/img/
It is saving on
myproject
Isn't your \ the wrong way? I'm going to guess that your localhost is Windows?
Jelastic is Linux based, so filesystem paths contain / not \. Maybe try
File(absoluteFilesystemPath+"/img/"+fileName);
Edit: according to File.separator vs Slash in Paths you might want to use File.separator instead for proper platform independence.

Categories

Resources