New edit:
Now i found the cause, it is because there are two servers and it write into temp folder in 1st server and try to read from the 2nd one. But I still didn't find a solution for this unless write to Amazon S3 and read from there.
I tried to export csv with struts2 action. However if I tried to export 10 times i can only succeed once, all the others failed with File not found exception (if I refresh the link again, the file can be downloaded). Here is my code:
public String exportFile(String fileName) {
File exportFile = null;
try {
if (CollectionUtils.isEmpty(receipts)) {
return "";
}
exportFile = File.createTempFile(fileName, ".csv");
exportFile.deleteOnExit();
try (BufferedWriter fw = new BufferedWriter(new FileWriter(exportFile))) {
try {
fw.write("test");
} finally {
fw.close();
}
}
return exportFile.getPath();
} catch (Exception ex) {
logger.error("Error exporting report. ", ex.getMessage());
}
return "";
}
String getStreamFromPath(String filePath) {
try {
File downloadFile = new File(filePath);
fileInputStream = new FileInputStream(downloadFile);
return SUCCESS;
} catch (IOException e) {
log.error(e.getMessage(), e);
return ERROR;
}
}
This is really weird, when i test in another server it works totally fine. Any ideas?
Related
After reading a file, I'm trying to delete it, but the following error appears:
java.io.IOException: Unable to delete file test.zip at
org.apache.commons.io.FileUtils.forceDelete (FileUtils.java:1390) at
org.apache.commons.io.FileUtils.cleanDirectory (FileUtils.java:1044)
at org.apache.commons.io.FileUtils.deleteDirectory
(FileUtils.java:977)
Here is my code. I've been careful to close the InputStream in the finally clause and only then call the method that deletes the file, but even then I can only delete it when I stop the program.
InputStream is = null;
try {
is = new URL(filePath).openStream(); // filePath is a string containing the path to the file like http://test.com/file.zip
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line.trim());
}
String xml = sb.toString(); // this code is working, the result of the "xml" variable is as expected
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
removeFileAndFolder(absolutePath);
}
private void removeFileAndFolder(String absolutePath) {
new Thread(new Runnable() {
#Override
public void run() {
try {
String folder = getFolder(absolutePath); // this method just get the path to the folder, because I want to delete the entire folder, but the error occurs when deleting the file
FileUtils.deleteDirectory(new File(folder));
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
After some tests I discovered that I can manually delete the file just before the line "is = new URL (filePath) .openStream ();". After it, and even after the line "is.close ();" I can not delete the file manually unless I stop the program.
I got it. I was opening the file by the url (is = new URL(filePath).openStream();), and trying to delete it by absolute path. I changed it to "is = new FileInputStream(absoluteFilePath);" and it works!
My web app is made on Spring MVC. I have a method where the user can upload PDFs
.
The I am sending the file as mutlipart file to the server. Every time the user uploads.
All what I want is to send the files as attachments in that email.
My code
private File prepareAttachment(final MultipartFile mFile) {
File file = new File(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + mFile.getOriginalFilename());
try {
if(file.exists()) {
file.delete();
}
mFile.transferTo(file);
} catch (FileNotFoundException fnfE) {
file.delete();
LOG.error(" file was not found.", fnfE);
} catch (IOException ioE) {
file.delete();
LOG.error("file has failed to upload.", ioE);
}
return file;
}
calling the method to prepare the attachment:
MimeMessagePreparator preparator = new MimeMessagePreparator() {
#Override
public void prepare(final MimeMessage mimeMessage) throws Exception {
File file = prepareAttachment(form.getFile());
File file2 = prepareAttachment(form.getFile2());
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
message.addAttachment(form.getFile().getOriginalFilename(), file);
message.addAttachment(form.getFile2().getOriginalFilename(), file2);
Getting exception:
2017-08-28 15:10:59,549 ERROR com.menards.requestForms.business.service.EmailService - file has failed to upload.
java.io.IOException: Destination file [C:\opt\tcserver\main\temp] already exists and could not be deleted
at org.springframework.web.multipart.commons.CommonsMultipartFile.transferTo(CommonsMultipartFile.java:160) ~[spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at com.menards.requestForms.business.service.EmailService.prepareAttachment(EmailService.java:552) ~[classes/:?]
this will work perfectly if I comment out adding the second file :(
message.addAttachment(form.getFile2().getOriginalFilename(), file2);
any advise?
Generally, you shouldn't let your users determine the path of a file that you're creating on your server - it introduces a lot of security vulnerabilities. In this case, they may be attempting to create a temp file that has the same as some other file in your temp directory, potentially one that has nothing to do with your current application. File.createTempFile ensures that it creates a file with a unique name on each invocation.
It's also good practice to clean up temp files as soon as you're finished with them, so you don't have to worry about maintaining state on your server between method calls. This can sometimes create code that's a bit busy with catch/finally blocks, but it's worth it to avoid waking up at 3 AM to a hard disk that's full of garbage temp files.
I'd implement this roughly as:
private File prepareAttachment(final MultipartFile mFile) throws IOException {
File tmp = null;
try {
tmp = File.createTempFile("upload", ".tmp");
mFile.transferTo(tmp);
return tmp;
} catch (IOException ioE) {
if (tmp != null) {
tmp.delete();
}
LOG.error("file has failed to upload.", ioE);
throw ioE;
}
}
MimeMessagePreparator preparator = new MimeMessagePreparator() {
#Override
public void prepare(final MimeMessage mimeMessage) throws Exception {
File file1 = null;
File file2 = null;
try {
file1 = prepareAttachment(form.getFile());
file2 = prepareAttachment(form.getFile2());
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
message.addAttachment(form.getFile().getOriginalFilename(), file1);
message.addAttachment(form.getFile2().getOriginalFilename(), file2);
// do your other stuff
} catch (IOException e) {
// some sort of error-handling, probably returning a message with an error status
} finally {
if (file1 != null) {
file1.delete();
}
if (file2 != null) {
file2.delete();
}
}
}
};
I try to use the official Dropbox API for uploading a zip file to my account. My project is a desktop application (standard Java). My code looks like this:
public void uploadZipFile(File file) throws Exception {
FileInputStream fis = new FileInputStream(file);
try {
getClient(accessToken).uploadFile("/" + file.getName(), DbxWriteMode.add(), file.length(), fis);
} finally {
fis.close();
}
}
private DbxClient getClient(String accessToken) {
DbxRequestConfig dbxRequestConfig = new DbxRequestConfig(Constants.APP_NAME, Locale.getDefault().toString());
return new DbxClient(dbxRequestConfig, accessToken);
}
And I call it:
File zipFile = new File("C:\\Test\\MyFile.zip");
try {
uploadZipFile(zipFile);
} catch (Exception e) {
e.printStackTrace();
}
The file is transferred without any problems but then I want to delete the file after synchronization:
File zipFile = new File("C:\\Test\\MyFile.zip");
try {
uploadZipFile(zipFile);
System.out.println(zipFile.delete());
} catch (Exception e) {
e.printStackTrace();
}
The file is transferred successfully again, but the file still exists in the local file system and the delete method returns false.
Like in the method i have attached i have used practiceData.txt i am getting same results while using just practiceData in file constructor so is it ok to use file without any extension or txt is better?
private void saveData(String data) {
File file = new File(this.getFilesDir(), "practiceData.txt");
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(data.getBytes());
saveStatus = "Data was successfully saved.";
} catch (java.io.IOException e) {
e.printStackTrace();
saveStatus = "Error occurred: " + e.toString();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
It doesn't matter what file extension you use, it just tells the OS how to open the file. So yes, you can use no extension and it will work just as well.
If you intend the file to be opened manually via another application, it may be helpful to use a standard extension however.
I have been trying many ways of downloading a file from a URL and putting it in a folder.
public static void saveFile(String fileName,String fileUrl) throws MalformedURLException, IOException {
FileUtils.copyURLToFile(new URL(fileUrl), new File(fileName));
}
boolean success = (new File("File")).mkdirs();
if (!success) {
Status.setText("Failed");
}
try {
saveFile("DownloadedFileName", "ADirectDownloadLinkForAFile");
} catch (MalformedURLException ex) {
Status.setText("MalformedURLException");
Logger.getLogger(DownloadFile.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Status.setText("IOException Error");
Logger.getLogger(DownloadFile.class.getName()).log(Level.SEVERE, null, ex);
}
I found this code on the net, am i using it correctly?
If i did:
saveFile("FolderName", "ADirectDownloadLinkForAFile")
I would get IOException error
What I want my code to do is:
Create folder
Download file
Downloaded file to go to the just created folder
I'm a newbie here sorry. Please help
There are various ways in java to download a file from the internet.
The easiest one is to use a buffer and a stream:
File theDir = new File("new folder");
// if the directory does not exist, create it
if (!theDir.exists())
{
System.out.println("creating directory: " + directoryName);
boolean result = theDir.mkdir();
if(result){
System.out.println("DIR created");
}
}
FileOutputStream out = new FileOutputStream(new File(theDir.getAbsolutePath() +"filename"));
BufferedInputStream in = new BufferedInputStream(new URL("URLtoYourFIle").openStream());
byte data[] = new byte[1024];
int count;
while((count = in.read(data,0,1024)) != -1)
{
out.write(data, 0, count);
}
Just the basic concept. Dont forget the close the streams ;)
The File.mkdirs() statement appears to be creating a folder called Files, but the saveFile() method doesn't appear to be using this, and simply saving the file in the current directory.