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);
Related
Below is my project like:
projectName
-package
- Util.java
- Test.json
In Util.java, I need to read the content from Test.json file and parse it.
Thus I use:
File currentfile = new File("");//get the current path
String absJsonPath = currentfile.getAbsolutePath() + "/Test.json";
While it did not work when I use a main method to test it. The thing is that the /src/package is lost in the obtained file path and I just got the path of the project.
And, when I deploy the project to weblogic server, I got another new error, the obtained current path is like:
.../DefaultDomain/.
I just want the file path in the file system, which is not related to the server.
What can I do for this? Thanks!
Put your file in resources folder and get it as following:
//Get file from resources folder
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("Test.json").getFile());
To read the content you can use following:
StringBuilder result = new StringBuilder("");
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
result.append(line).append("\n");
}
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
It's CanonicalPath() not Absolute. Check this out, let me know if it any helps.
Try this to get current path
String currentPath = System.getProperty("user.dir");
If you want to read a file in a specific package. You can use
File jsonFile = new File(getClass().getResource("/Test.json").getFile());
In my SpringBoot project I would like to read an image file located in:
I tried:
URL url = getClass().getResource("android.png");
File f = new File(url.getPath());
and:
URL url = getClass().getResource("static/images/android.png");
File f = new File(url.getPath());
but the result is null.
EDIT: this worked
try {
File file = new ClassPathResource("static/images/android.png").getFile();
} catch (IOException e) {
}
If you are using Spring, then it's better to use the built-in ClassPathResource class to access files within your classpath.
You can try this
File file = new ClassPathResource("/images/android.png").getFile();
because we can access static folder from anywhere
you can use this.getClass().getResource("/static/images").getFile(); to get the folder location and then append with the file name to get the file location.
Example
String path=this.getClass().getResource("/static/images").getFile();
File File f = new File(path+"/​android.png");
Have you tried
ClassLoader.getSystemResourceAsStream("/static/images/android.png");
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) {
...
}
I created a desktop project in netbeans, in the project folder I have three files : file.txt, file2.txt and file3.txt, in the load of the program I want to call these three files, and this is the code I tried :
public void run() {
Path path = Paths.get("file.txt");
Path path2 = Paths.get("file2.txt");
Path path3 = Paths.get("file3.txt");
if(Files.exists(path) && Files.exists(path2) && Files.exists(path3)) {
lireFichiers();
}else{
JOptionPane.showConfirmDialog(null, "Files didn't found !");
}
}
but when I run my program I get the message : "Files didn't found !" which means he didn't found those files.
those files are created by this code :
File file = new File("Id.txt");
File file2 = new File("Pass.txt");
File file3 = new File("Remember.txt");
The following three lines will only create file handlers for your program to use. This will not create a file by itself. If you are using the handler to write it will also create a file for you provided you close correctly after writing.
File file = new File("Id.txt");
File file2 = new File("Pass.txt");
File file3 = new File("Remember.txt");
So, a sample code will look like:
File file = new File("Id.txt");
FileWriter fw = new FileWriter(file);
try
{
// write to file
}
finally
{
fw.close();
}
If the file is in the root of your project, this should work:
Path path = Paths.get("foo.txt");
System.out.println(Files.exists(path)); // true
Where exatlcy are the files you want to open in your project?
Please specify the language you use.
Generally you could search the file to see whether the files are in the program bootup folder. For webapps you should pay attention to the "absolute path and the relative path".
=========Edit============
If you are using Jave, then the file should be write out using FileWriter.close() before you can find them in your hard disk.
Ref
Thank you all for your help, I just tried this :
File file = new File("Id.txt");
File file2 = new File("Pass.txt");
File file3 = new File("Remember.txt");
if(file.exists() && file2.exists() && file3.exists()){
// manipulation
}
and it works
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();