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);
Related
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/");
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
I am trying to create a folder by running java. As of now I have this and it works.
File f = new File ("/Users/myName/Desktop/nameOfDir");
f.mkdirs();
The question is what happens when I send this code to my friend? Would he have to change the code to the below for it to work?
File f = new File ("/Users/myFriendsName/Desktop/nameOfDir");
f.mkdirs();
how can I make the program find the correct path and create the folder where I want it (the desktop), regardless of who the user is?
Also, after creating the folder I will have to create a .txt in the folder. I can do this now, but same problem arise concerning different user names.
try using the following:
String userName = System.getProperty("user.name"); //platform independent
File f = new File ("/Users/" + userName + "/Desktop/nameOfDir");
f.mkdirs();
You can get the path to a user's home directory in a platform-independent way using:
System.getProperty("user.home");
So:
File f = new File(System.getProperty("user.home"), "Desktop/nameOfDir");
f.mkdirs();
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.
Fixed: Instead of calling isFile() I used exists() and it seems to be working fine. If possible could someone explain why this change worked?
I'm attempting to write out to an excel file but am having a problem when trying to create that file if the name already exists.
Basically I am taking a file that is uploaded to a server, reading it, and then outputting a report file in a new location with the same filename. I tried to do this by simply checking if the file already existed and then adding a number onto the filename. My code works if the file doesn't exist or if it exists without a number (e.g. filename.xls). If a file exists with the name "filename1.xls" the server just seems to hang when trying to write the file. What can do to fix this?
Here is my code:
String destination = "c:/apache-tomcat-7.0.8/webapps/reports/" + fileName.substring( fileName.lastIndexOf("\\")+1, fileName.lastIndexOf(".")) + ".xls";
int filenum = 1;
while (new File(destination).isFile()) {
destination = "c:/apache-tomcat-7.0.8/webapps/reports/" + fileName.substring( fileName.lastIndexOf("\\")+1, fileName.lastIndexOf(".")) + filenum + ".xls";
filenum++;
}
WritableWorkbook workbook = Workbook.createWorkbook(new File(destination));
That will happen if some process is still keeping the file open. E.g. you've created a FileInputStream on the file to read it, but are never calling close() on it after reading.
Unrelated to the problem, the expanded WAR folder is not the best place to use as a permanent storage. All those files in the expanded WAR folder will get lost whenever you redeploy the WAR. Also hardcoding a servletcontainer-specific path in the code makes it totally unportable.
If your actual intent is to return the Excel file on a per-request basis to the client using a servlet, then you should be using
WritableWorkbook workBook = Workbook.createWorkbook(response.getOutputStream());
// ...
This way it writes to the response immediately without the need for an intermediate file.
Use the File.createTempFile(prefix, suffix, directory) API:
String localName = new File(fileName).getName();
String nameNoExt = localName.substring(0, fileName.lastIndexOf("."));
String extension = localName.substring(fileName.lastIndexOf(".")); // need to include the .
File directory = new File("c:/apache-tomcat-7.0.8/webapps/reports/");
File destFile = File.createTempFile(nameNoExt, extension, directory)