Using java cannot access the files in a folder - java

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

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

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) {
...
}

Store a file temporarily in side temp folder of tomcat

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")%>

Create a folder and a file with Java in Ubuntu

Here is what I wanna do:
Check if a folder exists
If it does not exists, create the folder
If it doest exists do nothing
At last create a file in that folder
Everything is working fine in Windows 7, but when I run the application in Ubuntu it doesn't create the folder, it is just creating the file with the folder name, example: (my file name is xxx.xml and the folder is d:\temp, so in Ubuntu the file is generated at d: with the name temp\xxx.xml). Here is my code:
File folder = new File("D:\\temp");
if (folder.exists() && folder.isDirectory()) {
} else {
folder.mkdir();
}
String filePath = folder + File.separator;
File file = new File(filePath + "xxx.xml");
StreamResult result = new StreamResult(file);
transformer.transform(source, result);
// more code here
Linux does not use drive letters (like D:) and uses forward slashes as file separator.
You can do something like this:
File folder = new File("/path/name/of/the/folder");
folder.mkdirs(); // this will also create parent directories if necessary
File file = new File(folder, "filename");
StreamResult result = new StreamResult(file);
You directory (D:\temp) is nos appropriate on Linux.
Please, consider using linux File System, and the File.SEPARATOR constant :
static String OS = System.getProperty("OS.name").toLowerCase();
String root = "/tmp";
if (OS.indexOf("win") >= 0) {
root="D:\\temp";
} else {
root="/";
}
File folder = new File(ROOT + "dir1" + File.SEPARATOR + "dir2");
if (folder.exists() && folder.isDirectory()) {
} else {
folder.mkdir();
}
Didn't tried it, but whould work.
D:\temp does not exists in linux systems (what I mean is it interprets it as if it were any other foldername)
In Linux systems the file seperator is / instead of \ as in case of Windows
so the solution is to :
File folder = new File("/tmp");
instead of
File folder = new File("D:\\temp");
Before Java 7 the File API has some possibilities to create a temporary file, utilising the operating system configuration (like temp files on a RAM disk). Since Java 7 use the utility functions class Files.
Consider both solutions using the getProperty static method of System class.
String os = System.getProperty("os.name");
if(os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0 ) // Unix
File folder = new File("/home/tmp");
else if(os.indexOf("win") >= 0) // Windows
File folder = new File("D:\\temp");
else
throw Exception("your message");
On Unix-like systems no logical discs. You can try create on /tmp or /home
Below code for create temp dirrectory in your home directory:
String myPathCandidate = System.getProperty("os.name").equals("Linux")? System.getProperty("user.home"):"D:\\";
System.out.println(myPathCandidate);
//Check write permissions
File folder = new File(myPathCandidate);
if (folder.exists() && folder.isDirectory() && folder.canWrite()) {
System.out.println("Create directory here");
} else {System.out.println("Wrong path");}
or, for /tmp - system temp dicecrory. Majority of users can write here:
String myPathCandidate = System.getProperty("os.name").equals("Linux")? System.getProperty("java.io.tmpdir"):"D:\\";
Since Java 7, you can use the Files utility class, with the new Path class. Note that exception handling has been omitted in the examples below.
// uses os separator for path/to/folder.
Path file = Paths.get("path","to","file");
// this creates directories in case they don't exist
Files.createDirectories(file.getParent());
if (!Files.exists(file)) {
Files.createFile(file);
}
StreamResult result = new StreamResult(file.toFile());
transformer.transform(source, result);
this covers the generic case, create a folder if it doesn't exist and a file on that folder.
In case you actually want to create a temporary file, as written in your example, then you just need to do the following:
// this create a temporary file on the system's default temp folder.
Path tempFile = Files.createTempFile("xxx", "xml");
StreamResult result = new StreamResult(Files.newOutputStream(file, CREATE, APPEND, DELETE_ON_CLOSE));
transformer.transform(source, result);
Note that with this method, the file name will not correspond exactly to the prefix you used (xxx, in this case).
Still, given that it's a temp file, that shouldn't matter at all. The DELETE_ON_CLOSE guarantees that the file will get deleted when closed.

Java appending files into a zip [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Appending files to a zip file with Java
I have a zip that contains a few folders in it but the important one is dir and inside that is another folder called folder and folder contains a lot of files that I need to be able to update.
I have now a dir outside of the zip called dir and in that is folder with the files i need to update in so the paths are the same. How can i update those files into the zip?
The tricky part is that dir is at the root of the zip and it contains a lot of folders not just folder but i only need to update the files in folder i can't mess with any of the files out side of folders but still in dir.
Can this be done? I know this can be done in bash using the -u modifier but I would prefer to do this with java if it's possible.
Thank you for any help with this issue
Just to be clearer
Inside Zip
/dir/folder/filestoupdate
Outside the zip
/dir/folder/filestomoveintozip
Alright well here is the final method it's the same method i pastebinned before which i actually got from the stackoverflow topic in the link #Qwe posted before but i added the path variable so that it could add files to folders inside the zip
Alright so now how to use it in my example above i wanted to add a file into a folder that was inside another folder i would do that using my setup in the question like this
private void addFilesToZip(File source, File[] files, String path){
try{
File tmpZip = File.createTempFile(source.getName(), null);
tmpZip.delete();
if(!source.renameTo(tmpZip)){
throw new Exception("Could not make temp file (" + source.getName() + ")");
}
byte[] buffer = new byte[4096];
ZipInputStream zin = new ZipInputStream(new FileInputStream(tmpZip));
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(source));
for(int i = 0; i < files.length; i++){
InputStream in = new FileInputStream(files[i]);
out.putNextEntry(new ZipEntry(path + files[i].getName()));
for(int read = in.read(buffer); read > -1; read = in.read(buffer)){
out.write(buffer, 0, read);
}
out.closeEntry();
in.close();
}
for(ZipEntry ze = zin.getNextEntry(); ze != null; ze = zin.getNextEntry()){
if(!zipEntryMatch(ze.getName(), files, path)){
out.putNextEntry(ze);
for(int read = zin.read(buffer); read > -1; read = zin.read(buffer)){
out.write(buffer, 0, read);
}
out.closeEntry();
}
}
out.close();
tmpZip.delete();
}catch(Exception e){
e.printStackTrace();
}
}
private boolean zipEntryMatch(String zeName, File[] files, String path){
for(int i = 0; i < files.length; i++){
if((path + files[i].getName()).equals(zeName)){
return true;
}
}
return false;
}
Thanks for the link ended up being able to improve that method a bit so that it could add in files that weren't in the root and now i'm a happy camper :) hope this helps someone else out as well
EDIT
I worked a bit more on the method so that it could not only append to the zip but it also is able to update files within the zip
Use the method like this
File[] files = {new File("/path/to/file/to/update/in")};
addFilesToZip(new File("/path/to/zip"), files, "folder/dir/");
You wouldn't start the path (last variable) with / as that's not how it's listed in the zip entries
Unfortunately, Java can't update Zip files. The request to enhance that was submitted 14 years ago ;-)
You will need to unpack it to a temp folder, add files there and pack it back again.

Categories

Resources