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);
Related
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);
I am trying to export zip files to a directory and running into an IOException stating that the file path cannot be found. I am aware that this means that the parent directory does not exist usually, however debugging the line where the file is being written file.getParentFile().exists() returns true, so this is not my issue. To further complicate matters, this only occurs for approximately half of the files written. It is always the same files that fail when unzipping via java, but unzipping them via windows always successfully works.
Here is the code I am using:
ZipInputStream zis =
new ZipInputStream(new ByteArrayInputStream(zipFile));
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String fileName = ze.getName();
File newFile = new File(outputFolder + File.separator + fileName);
if(!newFile.isDirectory()) {
newFile.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(newFile); //Exception occurs here
//newFile.getParentFile().exists() returns true
//copying the path for newFile.getParentFile() into my file browser leads me to a valid, existing folder
//I have tried newFile.createNewFile() and that errors with a similar exception
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
results.add(new Foo());
}
ze = zis.getNextEntry();
}
Example exception:
java.io.FileNotFoundException: \\foo\foo\foo\foo\foo\foo\foo.pdf (The system cannot find the path specified)
Some more notes about the system: the file system is a remote network drive, the system is running windows, and the account has full write access to the drive. I have also verified that naming a file foo.pdf (copy and pasting the name of the file intended to be written) does not cause any issue either.
The issue is that zip files can have trailing spaces in their paths. For example, "Test whatever .zip" could be the file name so java sees the folder as "/Test whatever /" and it tries to create that folder. Windows tells java that it succeeded, but really it created a folder at "/Test Whatever/". When dealing with folders, the file IO has no issue with this, but when writing files, it completely bombs as it's looking for the path explicitly. It does not truncate the extra white space the same way it does when dealing with folders, as you would expect.
Here is the code I used to resolve it:
String path = (outputFolder + File.separator + fileName).replace(" ", "");
File newFile = new File(path);
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?
I am trying to get the following code to work properly. It always prints the output from the catch block, even though the output that is only printed if the file exists, is printed.
String outputFile = "/home/picImg.jpg";
File outFile = new File(outputFile);
if(outFile.exists)
newStatus(" File does indeed exist");
FileOutputStream fos;
try {
fos = new FileOutputStream(outFile);
fos.write(response);
fos.close();
return outputFile;
} catch (FileNotFoundException ex) {
newStatus("Error: Couldn't find local picture!");
return null;
}
In the code response is a byte[] containig a .jpg image from a URL. Overall I am trying to download an image from a URL and save it to the local file system and return the path. I think the issue has to do with read/write permissions within /home/. I chose to write the file there because I'm lazy and didn't want to find the username to find the path /home/USER/Documents. I think I need to do this now.
I notice in the terminal I can do cd ~ and get to /home/USER/. Is there a "path shortcut" I can use within the file name so that I can read/write in a folder that has those permissions?
No. The ~ is expanded by the shell. In Java File.exists() is a method, you can use File.separatorChar and you can get a user's home folder with System property "user.home" like
String outputFile = System.getProperty("user.home") + File.separatorChar
+ "picImg.jpg";
File outFile = new File(outputFile);
if (outFile.exists())
Edit
Also, as #StephenP notes below, you might also use File(File parent, String child) to construct the File
File outFile = new File(System.getProperty("user.home"), "picImg.jpg");
if (outFile.exists())
~ expansion is a function of your shell and means nothing special for the file system. Look for Java System Properties "user.home"
Java provides a System property to get the user home directory: System.getProperty("user.home");.
The advantage of this is, that it works for every operating system that can run the Java virtual machine.
More about System properties: Link.
I have a bean that download emails from SMTP server. After read emails it saves attachments on the server. To read attachment I use this code:
File f = new File("\\attachments\\" + attachment.getFileName());
f.mkdirs();
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
fos.write(bytes);
fos.close();
I got a FileNotFoundException on FileOutputStream creating and I can't understand why.
If can help, I use NetBeans with GlassFish and the tests are made in debug in local machine.
When you do
f.mkdirs();
You are creating a directory with the name of your file (that is, you create not only the directory "attachments", you also create a subdirectory with the name of your attachment filename). Then
f.createNewFile();
does not do anything since the file already exist (in the form of a directory you just created). It returns false to tell you that the file already exists.
Then this fails:
FileOutputStream fos = new FileOutputStream(f);
You are trying to open an output stream on a directory. The system doesn't allow you to write in a directory, so it fails.
The bottom line is:
mkdirs() doesn't do what you think it does.
you should check the return value of your call to createNewFile().
The simplest way to make it work is by replacing your line with:
f.getParentFile().mkdirs();