Tomcat saving file gives exception - java

I'm trying to save an uploaded file to my disk like this:
Part filePart = req.getPart("pic");
String fileName = filePart.getSubmittedFileName();
InputStream fileContent = filePart.getInputStream();
File uploads = new File("/images/gin");
File file = new File(uploads, fileName);
if(!file.exists())
file.createNewFile();
Files.copy(fileContent, file.toPath());
Tomcat always gives me the exception:
java.io.IOException: No such file or directory
java.io.UnixFileSystem.createFileExclusively(Native Method)
java.io.File.createNewFile(File.java:1006)
com.springapp.mvc.servlets.AddItemServlet.doPost(AddItemServlet.java:39)
javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
I don't know why it isn't working. Someone that can help me?

Call uploads.mkdirs(); before the new file creation
mkdirs()
* Creates the directory named by this abstract pathname, including any
* necessary but nonexistent parent directories. Note that if this
* operation fails it may have succeeded in creating some of the necessary
* parent directories.

Check with uploads.getAbsolutePath() to see if it's mapping the relative path to the intended folder. If yes, see if the account running tomcat has read/write access to the folder.

Related

/storage/emulated/0/Notes/ (No such file or directory)?

I tried this link:
How to create text file and insert data to that file on Android
But, it says "No such file or directory". Can anybody help me please? Thanks in advance!
---- Updated answer----
I think you can't create a directory inside the internal storage of the device. Except you've a root access for the app. You can only create the directory inside your app private folder within the following path String path = getFilesDir().
you can use like this below -
File mydir = context.getDir("mydirectory", Context.MODE_PRIVATE); //Creating an internal dir;
File fileWithinMyDir = new File(mydir, "myAwesomeFile"); //Getting a file within the dir.
FileOutputStream out = new FileOutputStream(fileWithinMyDir); //Use the stream as usual to write into the file.
getDir(StringName, int mode) method to create or access directories in internal storage.
/storage/emulated/0/Notes/ will always return No such file or directory except device is rooted and dir.mkDirs() will always return false for this path.
Hope this will help you.

How can I write a file in tomcat folder?

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.

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.

When using the jar file xmlparserv2.jar, transforming a doesn't work when the file path has whitespace. How can i fix this?

Normally when using ...
Transformer t = TransformerFactory.newInstance().newTransformer();
t.transform(source,result);
(without the xmlparserv2.jar file) a File Not Found Exception looks like this.
Exception in thread "main" java.io.FileNotFoundException: C:\Documents and Settings\username\nonExistentFile.xml (The system cannot find the file specified)
when you include the xmlparserv2.jar, the Exception turns to this
Caused by: java.io.FileNotFoundException: C:\Documents%20and%20Settings\username\existingFile.xml (The system cannot find the path specified)
The file is actually there (the transform method finds it when i dont include the jar) but when i include the jar, the transform method cant find it due to the %20 that is inserted for whitespace. Can someone please tell me how to fix this?
Sorry, should have included more code... the answer was in the Result Object i was passing in.
originally it looked like this
File f = new File(filePath);
Result result = new StreamResult(f);
changed to this..
File f = new File(filePath);
StreamResult result = new StreamResult();
FileOutputStream fos = new FileOutputStream(f);
result.setOutputStream(fos);

Categories

Resources