I am stuck with an issue with reading .xlsx file. Some temporary files with random name are created under /tmp/poifiles directory whenever I use WorkbookFactory.create(inputStream);. This directory is created with RW-R-R- permission for the first user. So another user on the same machine when tries to access these files, he CANNOT.
Please suggest me any way
1) How can I create these temp files under /tmp directory and not always in /tmp/poifiles (I am using RHEL V5.0)
2) and how can I configure POI such as to change the location from where it reads the temporary files??
Anymore help to solve my problem of different users accessing same .xlsx files through POI is badly needed.
Yuppie...I got the solution....
POI uses the following method to create temp files.
public static File createTempFile(String prefix, String suffix)
{
if (dir == null) {
dir = new File(System.getProperty("java.io.tmpdir"), "poifiles");
dir.mkdir();
if (System.getProperty("poi.keep.tmp.files") == null) {
dir.deleteOnExit();
}
}
File newFile = new File(dir, prefix + rnd.nextInt() + suffix);
if (System.getProperty("poi.keep.tmp.files") == null) {
newFile.deleteOnExit();
}
return newFile;
}
Now here as we can see it gets the location from property "java.io.tmpdir" and creates poifiles directory inside that...
I changed the location of java.io.tmpdir by setting this property (using System.setProperty("java.io.tmpdir", "somepath"))to user specific location..and Voila....Every user now can create temp files at location always accessible to them and not only the first user gets the privilege to create directory accessible only to him ...!!!
Here is how you can change the location from where POI reads the temporary files programmatically if you are not able to change system property "java.io.tmpdir"
File dir = new File("somepath");
dir.mkdir();
TempFile.setTempFileCreationStrategy(new DefaultTempFileCreationStrategy(dir));
This is driven by the Apache POI TempFile and DefaultTempFileCreationStrategy helper classes.
Related
I'm trying to use a file in my code but I don't want to have specify the absolute file path, only the file name, for example "fileName.txt".
I want to do this so I have the ability to use this code on different laptops where the file may be stored in different folders.
The code below is what I'm using at the moment but I receive a NoSuchFileException when I ran it.
FileSystem fs FileSystems.getDefault();
Path fileIn = Paths.get("fileName.txt");
Any ideas how to overcome this problem so I can find the file without knowing its absolute path?
Ideas on how to find the file without knowing its absolute path:
Instruct the user of the app to place the file in the working directory.
Instruct the user of the app to give the path to the file as a program argument, then change the program to use the argument.
Have the program read a configuration file, found using options 1 or 2, then instruct the user of the app to give the path to the file in the configuration file.
Prompt the user for the file name.
(Not recommended) Scan the entire file system for the file, making sure there is only one file with the given name. Optional: If more than one file is found, prompt the user for which file to use.
if you don't ask the user for the complete path, and you don't have a specific folder that it must be in, then your only choice is to search for it.
Start with a rootmost path. Learn to use the File class. Then search all the children. This implementation only returned the first file found with that name.
public File findFile(File folder, String fileName) {
File fullPath = new File(folder,fileName);
if (fullPath.exists()) {
return fullPath;
}
for (File child : folder.listFiles()) {
if (child.isDirectory()) {
File possible = findFile(child,fileName);
if (possible!=null) {
return possible;
}
}
}
return null;
}
Then start this by calling either the root of the file system, or the configured rootmost path that you want to search
File userFile = findFile( new File("/"), fileName );
the best option, however, is to make the user input the entire path. There are nice file system browsing tools for most environments that will do this for the user.
I have a simple code to generate the temp files and store the some values(I don't want to store the files in normal storage area)
In future, I want to use that file and get the data from that file (its not a problem if the user manually delete the files).
But I don't want to delete the files automatically. when read this link, I get some information, generally temp files not deleted
when you explicitly call deleteOnExit() but when my JVM finish the work temp file deleted automatically.
//create a temp file
File temp = File.createTempFile("demo_", ".txt");
String path = temp.getParent();
//count the file which names starts with "demo"
File f = new File(path);
File[] matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("demo") && name.endsWith(".txt");
}
});
// Print count array elements
System.out.println("Length : " + matchingFiles.length + " ");
Here I never call the deleteOnExit() (but file delete automtically)OR JVM automatically delete the file? By the way its deleted automatically if is it possible
to avoid deleting the file? or any other ways to do my requirement?
File.createTempFile only creates files with unique names, other than that they are just regular files. They are not deleted automatically. It is explained in File.createTempFile API: This method provides only part of a temporary-file facility. To arrange for a file created by this method to be deleted automatically, use the deleteOnExit method
I have writing a program which ask for video file from user. once video is browser by user it is save inside war/content. I do not have any problem to do this. when i want to see the video, i used video tag of html and give the relative path. video come perfectly fine and it can be viewed.
I used the following line of code to resolve the path.
System.setProperty("webapp.root", "C:/solution/totalsolution");
File webappDir = new File(System.getProperty("webapp.root", "./"));
File webappInfo = new File(webappDir, "war");
if(!webappInfo.exists()){
File dir = new File(webappDir, "war");
if(!dir.exists()){
if(dir.mkdir()){
webappDir = dir;
}
}
}
webappDir = webappInfo;
webappInfo = new File(webappDir, "content");
if(!webappInfo.exists()){
File dir = new File(webappDir, "content");
if(!dir.exists() && dir.mkdir()){
webappDir = dir;
}
}
webappDir = webappInfo;
if(contentDir != null){
webappInfo = new File(webappDir, contentDir);
if(!webappInfo.exists()){
File dir = new File(webappDir, contentDir);
if(!dir.exists() && dir.mkdir()){
webappDir = dir;
}
}
webappDir = webappInfo;
}
this program create new folder in specified path like "C:/solution/totalsolution/war/content/abcd/xysa.mp4"
when i show any resource then i make relative path like this
http://localhost:8080/solution/content/abcd/xysa.mp4
till now every thing is ok.But when i extract war file and deploye it into server.
Then is way failed due to static location in system property.
So can any body tell be the right approch to save data into war folder and right back reading it on local as well as on server to.
1) Do not store it in the war folder but in a separate location (probably designed specifically for this).
2) When getting the file from the user, you need to generate new unique name for this file, and store somewhere (e.g. DB) the mapping from the original file name to the new file name. Then on the disk you store the file under the new name. This is to guarantee your file names are unique (think what happens if two users upload files with the same name).
Don't try to save data into your webapp; there is no guarantee that this directory will be writable or even unpacked from the jar. Instead, read a property that tells you where to store data saved at runtime.
In an Android application I'm working on, the user should be able to create a new CSV file on the SD card, named using text they input in an EditText.
The problem is that after instantiating the File using the directory and filename, file.exists() returns false, even when the file does indeed exist at that location. I have browsed to SD card using an Android file browser and through Windows Explorer, and the file does exist.
Is this the correct way to check if the file already exists, and if so, what am I missing so that it returns true when it exists?
String csvname = edittext.getText().toString() + ".csv";
File sdCard = Environment.getExternalStorageDirectory(); //path returns "/mnt/sdcard"
File dir = new File (sdCard.getAbsolutePath() + "/Android/data/" + getPackageName() + "/files/"); // path returns "/mnt/sdcard/Android/data/com.phx.license/files"
dir.mkdirs();
File file = new File(dir, csvname); //path returns "/mnt/sdcard/Android/data/com.phx.license/files/Test.csv"
if(!file.exists()) //WHY DOES IT SAY IT DOESN'T EXIST WHEN IT DOES?
{
...
}
If you use createNewFile it will only create a file if it does not already exist.
Java Files Documentation
public boolean createNewFile()
throws IOException
Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file.
Note: this method should not be used for file-locking, as the resulting protocol cannot be made to work reliably. The FileLock facility should be used instead.
Returns:
true if the named file does not exist and was successfully created; false if the named file already exists
Throws:
IOException - If an I/O error occurred
SecurityException - If a security manager exists and its SecurityManager.checkWrite(java.lang.String) method denies write access to the file
Since:
1.2
Creating a new file object like so new File(dir, csvname); does not create a new file in the file system.
You need to write data to it first.
I had the exact same issue but with yarn on hadoop where a spark job was trying to execute a command.
It was a file permission issue. I troubleshooted it by code like below which is in scala. exists and notExists both return false, which means the jvm is not able to tell if the file exists or not.
import java.nio.file.Path
import java.nio.file.Paths
val path = Paths.get(fileLocation);
println(":"+ Files.exists(path)+ ":" + Files.notExists(path))
The code I am running is in /Test1/Example. If I need to read a .txt file in /Test1 how do I get Java to go back 1 level in the directory tree, and then read my .txt file
I have searched/googled and have not been able to find a way to read files in a different location.
I am running a java script in an .htm file located at /Test1/Test2/testing.htm. Where it says script src=" ". What would I put in the quotations to have it read from my file located at /Test1/example.txt.
In Java you can use getParentFile() to traverse up the tree. So you started your program in /Test1/Example directory. And you want to write your new file as /Test1/Example.txt
File currentDir = new File(".");
File parentDir = currentDir.getParentFile();
File newFile = new File(parentDir,"Example.txt");;
Obviously there are multiple ways to do this.
You should be able to use the parent directory reference of "../"
You may need to do checks on the OS to determine which directory separation you should be using ['\' compared to '/']
When you create a File object in Java, you can give it a pathname. You can either use an absolute pathname or a relative one. Using absolutes to do what you want would require:
File file = new File("/Test1/myFile.txt");
if(file.canRead())
{
// read file here
}
Using relatives paths if you want to run from the location /Test1/Example:
File file = new File("../myFile.txt");
if(file.canRead())
{
// read file here
}
I had a similar experience.
My requirement is: I have a file named "sample.json" under a directory "input", I have my java file named "JsonRead.java" under a directory "testcase". So, the entire folder structure will be like untitled/splunkAutomation/src and under this I have folders input, testcase.
once after you compile your program, you can see a input file copy named "sample.json" under a folder named "out/production/yourparentfolderabovesrc/input" and class file named "JsonRead.class" under a folder named "out/production/yourparentfolderabovesrc/testcase". So, during run time, Java will actually refer these files and NOT our actual .java file under "src".
So, my JsonRead.java looked like this,
package testcase;
import java.io.*;
import org.json.simple.JSONObject;
public class JsonRead{
public static void main(String[] args){
java.net.URL fileURL=JsonRead.class.getClass().getResource("/input/sample.json");
System.out.println("fileURL: "+fileURL);
File f = new File(fileURL.toURI());
System.out.println("fileIs: "+f);
}
}
This will give you the output like,
fileURL: file:/C:/Users/asanthal/untitled/out/production/splunkAutomation/input/sample.json
fileIs: C:\Users\asanthal\untitled\out\production\splunkAutomation\input\sample.json
It worked for me. I was saving all my classes on a folder but I needed to read an input file from the parent directory of my classes folder. This did the job.
String FileName = "Example.txt";
File parentDir = new File(".."); // New file (parent file ..)
File newFile = new File(parentDir,fileName); //open the file