I'm using this method to zip and decrypt a file:
AesZipFileEncrypter.zipAndEncrypt
This code:
AesZipFileEncrypter.zipAndEncrypt(new File("C:\Test\Folder\MyFile.txt"), new File("C:\Test\Folder\MyZip.zip"), password, aesEncrypter);
compresses also the folder tree of my file, not just the file. For example:
Adding C:\Test\Folder\MyFile.txt in the created zip file I will find the folders C:\Test\Folder\MyFile.txt also if I would like to have just MyFile.txt in the root folder.
Is it possibile?
This is the solution:
AESEncrypter aesEncrypter = new AESEncrypterBC();
aesEncrypter.init(password, 0);
AesZipFileEncrypter ze=new AesZipFileEncrypter(outputfilename, aesEncrypter);
ze.add(inputfilename,new FileInputStream(inputfilename), password);
ze.close();
In Windows (which it looks like you are in) I ran into the same problem and it seems to depend on where the file is relative to your application. To get around it, I copied the input file to the local directory, ziped and encrypted it, then moved the output file back to the where the output file was intended.
public static File aesEncrypt(String inFileFullPath, String outFileFullPath, String aesPassword) throws IOException{
File inFile = new File(inFileFullPath);
File localInput = new File(inFile.getName());
Files.copy(inFile, localInput);
File outFile = new File(outFileFullPath);
File localOutFile = new File(outFile.getName());
AESEncrypter aesEncrypter = new AESEncrypterBC();
aesEncrypter.init(aesPassword, 255);
AesZipFileEncrypter ze = new AesZipFileEncrypter(localOutFile, aesEncrypter);
ze.add(localInput, aesPassword);
ze.close();
Files.move(localOutFile, outFile);
localInput.delete();
return outFile;
}
Related
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);
How to write or read any type of file (for example .txt file) to a resources folder with the config.property file, but without using absolute path file.
I tried to solve this like below:
ClassLoader classLoader = Setting.class.getClassLoader();
Setting setting = new Setting();
try (InputStream resourceAsStream = classLoader.getResourceAsStream("config.properties")) {
setting.load(resourceAsStream);
}
String readFileName = setting.getValue("pathSource.txt");
String writeFileName = setting.getValue("outPutPathSourceFile.txt");
String s = System.getProperty("line.separator");
File readFile = new File("./src/main/resources" + File.separator + "pathSource.txt");
File writeFile = new File("./src/main/resources" + File.separator + "outPutPathSourceFile.txt");
However, I don't want using ./src/main/resources prefix.
If your file is located under resources you able to access it like:
File file = new File(classLoader.getResource(fileName).getFile());
if you are using Spring you can use ResourceUtils.getFile():
File file = ResourceUtils.getFile("classpath:fileName")
UPDATE:
If I understand correctly, you want to read file which located under your src/main/resources without relative path usage /src/main/resources.
I created small demo:
public class ReadResourceFile {
public static void main(String[] args) throws IOException {
String fileName = "webAutomationConfig.xml";
ClassLoader classLoader = ReadResourceFile.class.getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
System.out.println("File exists: " + file.exists());
String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);
}
}
Output:
File exists: true
<?xml version="1.0" encoding="utf-8"?>
<config>
<baseUrl>https://www.gmail.com</baseUrl>
</config>
Project structure:
Resources (files on the class path, possibly inside a jar)can be read, but are not intended to be written to. You can use them as template to create an inital copy on the file system. – Joop Eggen
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) {
...
}
Is there a way to use the File class to create a new text file? After doing some research, I tried:
import java.io.*;
public class createNewFile
{
public static void main(String args[]) throws IOException
{
File file = new File("newfile.txt");
boolean b1 = file.createNewFile();
}
}
...but there is still no newfile.txt in my source directory. It would also seem like there would be a void method to do this, instead of having to result to a boolean. Is there a way to do what I'm trying to do with the FIle class, or so I have to result to another class?
You have created a file but apparently not in your source directory but in the current working directory. You can find the location of this new file with:
System.out.println(file.getAbsolutePath());
One possibility to control the location of the new file is to use an absolute path:
File file = new File("<path to the source dir>/newfile.txt");
file.createNewFile();
You can try like this:
File f = new File("C:/Path/SubPath/newfile.txt");
f.getParentFile().mkdirs();
f.createNewFile();
Also make sure that the path where you are checking and creating the file exists.
This question already has answers here:
Copying files from one directory to another in Java
(34 answers)
Closed 9 years ago.
I want to copy a zip file from one folder to another folder in java.
i have a migrate.zip file in sourcefolder .i need to copy that migrat.zip file to destination
folder.
can any one help me on this.
Thanks&Regards,
sivakrishna.m
apache-commons-io library is helpful in you problem
org.apache.commons.io.FileUtils.copyFile(File, File)
FileUtils.copyFile(new File("/sourcefolder/migrate.zip"),
new File("/destination/migrate.zip"))
Please check the below question and answer. This may help you.
Best Way to copy a Zip File via Java
try this set of lines.
String sourceFilePath =" Source path";
File f = new File(sourceFilePath);
File f1 = new File(destinationFilePath);
File fCopy = new File(destinationFilePath);
if (f1.exists()) {
// Don't do anything..
f1.delete();
}
FileUtils.copyFile(f, fCopy)
Use java.util.ZipInputStream class to read migrate.zip file from source folder and use java.util.ZipOutputStream class to write migrate.zip to the destination folder....
public class CopyZip
{
public static void main(String[] args)
{
FileInputStream fin = new FileInputStream(new File("source_folder\migrate.zip"));
ZipInputStream zin = new ZipInputStream(fin);
byte[] in_bytes = new bytes[1000];
zin.read(in_bytes,0,1000);
FileOutputStream fout = new FileOutputStream(new File("dest_folder\migrate.zip"));
ZipOutputSrream zout = new ZipOutputStream(fout);
zout.write(in_bytes,0,in_bytes.length);
}
}