Store a file temporarily in side temp folder of tomcat - java

Can you please tell me any Java code that I can use to store a file inside Tomcat's temp folder so that once it is used (downloaded) it will be deleted automatically?

Well there are Many ways to do this, you should explore the CATALINA_HOME Environmental Variable as this Points to the Tomcat Installation Directory.
Update
*Try this:*
#SuppressWarnings("restriction")
BASE64Decoder decoder = new BASE64Decoder(); // Decode encoded string into original byte array
System.out.println("in try ");
System.out.println("imagestring "+ imageString);
byte[] decoded = decoder.decodeBuffer(imageString);
System.out.println("image"+ decoded);
BufferedImage image = ImageIO.read(new ByteArrayInputStream(decoded));
File f = new File(System.getenv("CATALINA_HOME") + "/temp");//TomcatHome director/tempfolder
System.out.println(f.getAbsolutePath());//debug like this
if(!f.exists()){
f.mkdir();//make temp folder if it does not exist
}
ImageIO.write(image, "jpg",new File(f.getAbsolutePath() + "/yourimagename.jpg"));//write image to to the temp folder
}
//do some other Processing
File file = new File(f.getAbsolutePath() + "/yourimagename.jpg");
if(file.exists()){
file.delete();
}
After processing , you can delete it in the usual way file.delete();
You need to make sure that the environmental variable CATALINA_HOME Points to Tomcat base directory.

In jsp, this line gives temp folder path, You can use this path to store file <%=System.getProperty("java.io.tmpdir")%>

Related

How to create temp directory in heroku/docker using Java?

I am trying to create a temp file and generate a file name and then save a multipart file. I am using Spring Boot and the following code is working in local. But in heroku or docker it is throwing FileNotFoundException; So how to create a temp directory and save a file inside that temp directory in docker/heroku? Or what is the best way to save multipart file to temp folder in server? Anybody can help me? Thanks in advance.
File tempDirectory = new File(new File(System.getProperty("java.io.tmpdir")), "files");
if (!tempDirectory.exists()) {
tempDirectory.mkdir();
}
String filePath = new File(tempDirectory.getAbsolutePath() + "/temp.pdf").getAbsolutePath();
File tempDirectory = new File(new File(System.getProperty("java.io.tmpdir")), "files");
if(tempDirectory.exists()){
System.out.println("something");
}else{
tempDirectory.mkdirs();
}
File file = new File(tempDirectory.getAbsolutePath()+"/abcd.txt");
if(!file.exists()){
file.createNewFile();
}
String file2= new File(tempDirectory.getAbsolutePath()+"/something.txt").getAbsolutePath();
System.out.println(file2);
Works totally fine at my end. The only problem you might be having is
String filePath = new File(tempDirectory.getAbsolutePath() + "/temp.exe").getAbsolutePath();
This doesn't create the file in the temp directory you have created. It just returns the absolute path if it was to be saved in the directory mentioned. This might be the reason you are getting not found error. Try actually saving by using
file.transferTo(wherefileneedstobesavedlocation);

File is not deleted when file path is generated dynamically

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.

Unable to save the uploaded file into specific directory

I want to upload files and save them into specific directory.And i am new to files concept.When i uploading files from my page they are saved in another directory(C:\Users\ROOTCP~1\AppData\Local\Temp\multipartBody989135345617811478asTemporaryFile) and not in specified directory.I am unable to set it.Please help me in finding a solution.For all help thanks in advance.
public static Result uploadHoFormsByHeadOffice() throws Exception {
Logger.info("#C HoForms -->> uploadHoFormsByHeadOffice() -->> ");
final String basePath = System.getenv("INVOICE_HOME");
play.mvc.Http.MultipartFormData body = request().body()
.asMultipartFormData(); // get Form Body
StringBuffer fileNameString = new StringBuffer(); // to save file path
// in DB
String formType = body.asFormUrlEncoded().get("formType")[0];// get formType from select Box
FilePart upFile = body.getFile("hoFiles");//get the file details
String fileName = upFile.getFilename();//get the file name
String contentType = upFile.getContentType();
File file = upFile.getFile();
//fileName = StringUtils.substringAfterLast(fileName, ".");
// path to Upload Files
File ftemp= new File(basePath +"HeadOfficeForms\\"+formType+"");
//File ftemp = new File(basePath + "//HeadOfficeForms//" + formType);
File f1 = new File(ftemp.getAbsolutePath());// play
ftemp.mkdirs();
file.setWritable(true);
file.setReadable(true);
f1.setWritable(true);
f1.setReadable(true);
//HoForm.create(fileName, new Date(), formType);
Logger.info("#C HoForms -->> uploadHoFormsByHeadOffice() <<-- Redirecting to Upload Page for Head Office");
return redirect(routes.HoForms.showHoFormUploadPage());
}
}
I really confused why the uploaded file is saved in this(C:\Users\ROOTCP~1\AppData\Local\Temp\multipartBody989135345617811478asTemporaryFile) path.
You're almost there.
File file = upFile.getFile(); is the temporary File you're getting through the form input. All you've got to do is move this file to your desired location by doing something like this: file.renameTo(ftemp).
Your problem in your code is that you're creating a bunch of files in memory ftemp and f1, but you never do anything with them (like writing them to the disk).
Also, I recommend you to clean up your code. A lot of it does nothing (aforementioned f1, also the block where you're doing the setWritable's). This will make debugging a lot easier.
I believe when the file is uploaded, it is stored in the system temporary folder as the name you've provided. It's up to you to copy that file to a name and location that you prefer. In your code you are creating the File object f1 which appears to be the location you want the file to end up in.
You need to do a file copy to copy the file from the temporary folder to the folder you want. Probably the easiest way is using the apache commons FileUtils class.
File fileDest = new File(f1, "myDestFileName.txt");
try {
FileUtils.copyFile(ftemp, fileDest);
}
catch(Exception ex) {
...
}

Using java cannot access the files in a folder

Hi i am new to java and i want to know how to access the files in the folder.
My requirement is that,
I am successfully compressing an image files and then writing it into a temporary file.
Now i want to access each file in the folder so that i can check the size of the files individually to perform some operations.
Please tell me how to access each file in the folder dynamically.
This is the code to compress and then access the folder.
BufferedImage resizeImageBmp = resizeImage(originalImage, type);
ImageIO.write(resizeImageBmp, "png", new File(tempDir + roots[i].getName())); //Compressing the file
String Temp = tempDir; //Path to the temporary folder
//Temp1 = ((Temp.length() / 1024)/1024);
if((Temp.length()) > 6){
//writeToDir(Temp,failureDir);
//System.out.println(Temp);
System.out.println(Temp);
}
else{
//System.out.println(Temp);
System.out.println(Temp);
}
Consider using File.listFiles() listed here.
File tempFile = new File(tempDir);
File[] allFilesInTempDir = tempFile.listFiles();

Java - how do I write a file to a specified directory

I want to write a file results.txt to a specific directory on my machine (Z:\results to be precise). How do I go about specifying the directory to BufferedWriter/FileWriter?
Currently, it writes the file successfully but to the directory where my source code is located. Thanks
public void writefile(){
try{
Writer output = null;
File file = new File("results.txt");
output = new BufferedWriter(new FileWriter(file));
for(int i=0; i<100; i++){
//CODE TO FETCH RESULTS AND WRITE FILE
}
output.close();
System.out.println("File has been written");
}catch(Exception e){
System.out.println("Could not create file");
}
}
You should use the secondary constructor for File to specify the directory in which it is to be symbolically created. This is important because the answers that say to create a file by prepending the directory name to original name, are not as system independent as this method.
Sample code:
String dirName = /* something to pull specified dir from input */;
String fileName = "test.txt";
File dir = new File (dirName);
File actualFile = new File (dir, fileName);
/* rest is the same */
Hope it helps.
Use:
File file = new File("Z:\\results\\results.txt");
You need to double the backslashes in Windows because the backslash character itself is an escape in Java literal strings.
For POSIX system such as Linux, just use the default file path without doubling the forward slash. this is because forward slash is not a escape character in Java.
File file = new File("/home/userName/Documents/results.txt");
Just put the full directory location in the File object.
File file = new File("z:\\results.txt");
The best practice is using File.separator in the paths.

Categories

Resources