FileNotFoundExeption Access is denied when writing a file - java

java.io.FileNotFoundException: C:\Emails\ToSend\. (Access is denied)
I'm trying to download a file from FTP and save it to a folder to be processed, But when I setup the OutputStream it throws this error. Here is the code:
File downloadFile1 = new File("C:" + File.separator + "Emails"
+ File.separator + "ToSend" + File.separator
+ f.getName());
OutputStream outputStream1 = new BufferedOutputStream(
new FileOutputStream(downloadFile1));
The FTPFile f is fetched by the FTPClient from the FTP server. I've got full control of the folder Emails and all of its sub folders and I have given these same permissions to all application packages.
I'm sure its just because I'm abit out of my depth when it comes to file permissions.
Any and all help appreciated

Instead of hard-coding the file location, how about using a temporary directory? This is assuming the file will be processed immediately by your application and does not need to be kept.
For how to do this, see the accepted answer to this question: How to create a temporary directory/folder in Java?

Related

Download file showing in tomcat bin folder

When I run my war file on Tomcat server then I run my project on chrome and download the xls file from my project and this file showing in tomcat bin folder as well as download folder in our computer.
Please suggest me how we can stop this download file in tomcat bin folder
thanks
String FILE_EXTENSION = ".xlsx";
DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
filename = "SearchPayment_Transactions_" + df.format(new Date()) + FILE_EXTENSION;
File file = new File(filename);
// this Writes the workbook
FileOutputStream out = new FileOutputStream(file);
wb.write(out);
out.flush();
out.close();
wb.dispose();
fileInputStream = new FileInputStream(file);
addActionMessage(filename + " written successfully on disk.");
i think the this problem can be sovled, just by fixing the place you want to created the file
String FILE_EXTENSION = ".xlsx";
DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
filename = "SearchPayment_Transactions_" + df.format(new Date()) + FILE_EXTENSION;
File file = new File(path any fixed directory like temp\filename);
As long as you specify the path where you want to generate the file then it will generating only in tht directory. PLease make proper permission is given to path to generate file, and this will solve your issue.
The file appears twice on your computer, because your servlet code saves the *.xlsx file to disk before sending it to your browser. That's the behavior your chose in your code.
Remark however, that file in your code is a relative path, so the folder you write it is the working directory (according to the OS) of your server. The value of the working directory is not defined in the Servlet Specification and may vary from system to system.
A better solution would be:
either don't write any file at all and write your data directly to ServletResponse#getOutputStream(),
or write the file to the Servlet's temporary directory, which you can obtain through (File) servletContext.getAttribute(ServletContext.TEMPDIR). E.g. you can replace your file variable with:
final File file = new File((File) servletContext.getAttribute(ServletContext.TEMPDIR), filename);

Changing file path to a more common folder

I currently have a simple code in which i save a CSV file in a folder, according to my android studio monitor i am successfully saving that file in a folder i can't access which is "/storage/emulated/0/Download/myfolder/552.csv".
File path =new
File(Environment.getExternalStoragePublicDirectory(Environment. +
DIRECTORY_DOWNLOADS),"myfolder");
System.out.println(path);
if (!path.exists()){
path.mkdir();
}
File mypath=new File(path,(editSesion.getText().toString()+".csv"));
FileWriter mFile = new FileWriter(mypath,true);
CSVWriter writer = new CSVWriter(new FileWriter(mypath));
System.out.println(mypath);
Is there any way to obtain the path to a more commonly accesable folder?
/storage/emulated/0/Download/ is the Downloads folder of your phone storage.
How much common directory are you expecting than this?
Please add / (Forward slash) like this myfolder/
File(Environment.getExternalStoragePublicDirectory(Environment. +
DIRECTORY_DOWNLOADS),"myfolder");
change into
File(Environment.getExternalStoragePublicDirectory(Environment. +
DIRECTORY_DOWNLOADS),"myfolder/");

Creating a file in linux server Java

i upload a csv file from client side and i want to create this file in server side.
Here is my function
public void uploadFile(FileUploadEvent e) throws IOException{
UploadedFile uploadedCsv=e.getFile();
String filePath="//ipAdress:/home/cg/Temp/input/ressource.csv";
byte[] bytes=null;
if(uploadedCsv != null){
bytes=uploadedCsv.getContents();
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
String filename = FilenameUtils.getName(uploadedCsv.getFileName());
stream.write(bytes);
stream.close();
}
}
When I want to write the file I get this exception (No such file or directory)
SEVERE: java.io.FileNotFoundException: /ipAdress:/home/cg/Temp/input/ressource.csv (No such file or directory)
Knowing that the / home / cg / Temp / input path is created on the server.
Could you try:
String filePath="////ipAdress/home/cg/Temp/input/ressource.csv";
Instead of:
String filePath="//ipAdress:/home/cg/Temp/input/ressource.csv";
And this:
new File(new URI(filePath))
Instead of:
new File(filePath)
Or you can use jcif API How can I open a UNC path from Linux in Java?
I would use the <file>.mkdirs(); at one level above the file itself.
So do String filePath="//ipAdress:/home/cg/Temp/input
File directory = new File(filePath);
directory.mkdirs();
You can then make the file
File tempFile = new File(directory + "/ressource.csv);
Or a cleaner solution all around is just use Files.createTempFile(prefix, suffix) this will create a file in the temp directory of the system.
The reason that your code does not work is that you are trying to use a UNC pathname on Linux. Linux does not support UNC pathnames ... natively. They are a Windows-ism.
Here's your example
"//ipAdress:/home/cg/Temp/input/ressource.csv";
If you try to use that on Linux, the OS will look for a directory in the root directory of the file system. The directory it will look for will have the name ipaddress: ... noting that there is a colon in the directory name!
That will most likely fail ... because no directory with that name exists in the / directory.. And the exception message you are getting is consistent with this diagnosis.
If you are doing this because you are trying to push files out to other systems then you are going to do it some other way. For example:
Use NFS and mount the other system's file systems on the server.
Use a Java implementation of UNC names; e.g. How can I open a UNC path from Linux in Java?
(Which ever way you do it, there are security issues to consider!)
trying this new File(new URI(filePath)) instead of new File(filePath) i get this erreur. SEVERE: java.lang.IllegalArgumentException: URI is not absolute
It won't work. A UNC name is NOT a valid URL or URI.
I have found a solution for this problem, but it's not smart and still and it works
String fileName="ressource.csv";
File f = new File(System.getProperty("user.home") + "/Temp/input",fileName);
if (f.exists() && !f.canWrite())
throw new IOException("erreur " + f.getAbsolutePath());
if (!f.exists())
Files.createFile(f.toPath());
if (!f.isFile()) {
f.createNewFile(); // Exception here
} else {
f.setLastModified(System.currentTimeMillis());
}
Pending a more intelligent solution

JAVA - Get access to a file in different subfolder

I am programming a file transfer, and i am having troubles with it.
In my current location i have created a folder called "Server Folder", where i will have files that the Client can transfer (I will be transfered with the same name, to the workspace directory), But every time i try to access it, it fails.
FILE_SERVER_PATH = "./ServerFolder/";
File fileToRead = new File(FILE_SERVER_PATH + fileName);
fileToRead = fileToRead.getParentFile();
if(fileToRead.exists()){
FileInputStream readingBuffer = new FileInputStream(fileToRead);
fileName is received throw datagram, and the name is correct. It always fails in the condition --> fileToRead.exists()
Can anyone please give me a tip?
Thx! :-)
try to use the folder path as absolute.
will help and work...current directory works only if you know in which directory you are in at the time of execution.

Downloading zip or exe file from SFTP location

Below are the two snippets from my applications and am using J2SSH jar for SFTP access.
first one:
.........
.........
//Open the SFTP channel
com.sshtools.j2ssh.SftpClient client = sshClient.openSftpClient();
// writing from source path to outputstream
client.get("/Repository/Test/index.zip", outputStream);
........
........
second one (JSP file):
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition","attachment; filename=index.zip");
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
client.fillOutputStream(bos); // this method calls to first block code.
bos.flush();
bos.close();
response.flushBuffer();
everything is working fine in the application without any exceptions.
There are no issues when Text files are downloaded.
But while am trying to download zip or exe files, something is missing in it.
Even the download is getting succesful, the file is not able to extract or not getting executed.
Plz suggest me which might be the problem in it.... especially it should work for exe file...
For this kind of work i use http://commons.apache.org/vfs/
StandardFileSystemManager manager = new StandardFileSystemManager();
FileObject target = manager.resolveFile("file://" + path + File.separator + filenameTarget);
FileObject source = manager.resolveFile(sftpUri + path + File.separator + filenameSource, options);
target.copyFrom(fichierSource, Selectors.SELECT_SELF);

Categories