How to create a File object with a String - java

In my TestClass I want to read the txt-file. I am always very confused how I should go about getting a reference to the txt-file though. The example I dug out of the internet suggested using a BufferedReader which requires a Path object to instantiate. I thought I'd create a File object and invoke it's .toPath(). But now how do I instantiate my File object? The least scary of its constructors require a string, but which string?

The easiest way to reference the file path within the scope of your project would be to use the System properties. Using the below value would return to you the users current working directory. Something like this would do the trick:
File file = new File (System.getProperty ("user.dir") + "/" + path_to_txt_file);
Depending on your system you may need to modify the delimiter.

Related

Unable to resolve ${file.separator} programmatically to read property path

I am trying to read a property which contains a file path including logged in user name in path as below.
test.file = ${file.separator}test${file.separator}${user.name}${file.separator}file.txt
I am able to read file with OS specific path (/ - unix or -windows) when I read the property using #Value annotation in a class and when used it in pom.xml as an argument..
When i read this as regular property from property file, spring is reading it as another string value which is expected.
But if i pass this value to File constructor, ${file.separator} doesn't get resolved..
what is the best way to represent file separator in a property file? I want to avoid .replace technique to replace a variable with File.separator in code.
If you are just looking for a file separator which is platform neutral then, we have been using / separator without any problem.
path=C:/Users/<user_name>/myconfig.properties
path=/Users/<user_name>/myconfig.properties
The following code always returns true on both systems.
finput = new File(prop.getProperty("path"));
System.out.println(finput.exists());

How can I limit the scope of System.setProperty to only to the method that sets it?

I am working on an export that requires the files to be stored in a folder inside the tmp folder, and each folder must be different for different exports.
So my export() method does the below:
System.setProperty("java.io.tmpdir", System.getProperty("java.io.tmpdir")+pathSpecificToFirstExport);
the createTempFile method makes use of System.getProperty("java.io.tmpdir") to store the files in it.
While the above method is running, another call to export() sets the new System.getProperty("java.io.tmpdir") to System.getProperty("java.io.tmpdir")+pathSpecificToFirstExport+pathSpecificToSecondExport while what I really want is only System.getProperty("java.io.tmpdir")+pathSpecificToSecondExport.
I cannot hardcode System.getProperty("java.io.tmpdir") instead of appending new path to it everytime as System.getProperty("java.io.tmpdir") changes for different environments. I cannot change the way temp file is created as it is not done by me, but by write() of SXSSFWorkbook.java:
File tmplFile = TempFile.createTempFile("poi-sxssf-template", ".xlsx");
What I am looking for is to limit the scope of System.getProperty("java.io.tmpdir") only to the instance of method export()
Any thoughts?
You can't do that. The System properties object is effectively global, and there is no scoping mechanism applicable to it.
What you need to do is use a different mechanism for creating temporary files that doesn't depend on the "java.io.tmpdir". Solution: use createTempFile(String prefix, String suffix, File directory), and keep track of the "current" temporary directory using (for example) thread locals.
Better still, use the equivalent method in java.nio.Files.
Unfortunately I cannot make the above change since the createTempDirectory is done by another method that I cannot change (SXSSFWorkbook does that for me).
So I took a look at SXSSFWorkbook, and here is where it is creating temporary files:
/**
* Write out this workbook to an Outputstream.
*
* #param stream - the java OutputStream you wish to write to
* #exception IOException if anything can't be written.
*/
public void write(OutputStream stream) throws IOException {
for (SXSSFSheet sheet : _xFromSxHash.values()) {
sheet.flushRows();
}
//Save the template
File tmplFile = File.createTempFile("poi-sxssf-template", ".xlsx");
tmplFile.deleteOnExit();
FileOutputStream os = new FileOutputStream(tmplFile);
_wb.write(os);
os.close();
//Substitute the template entries with the generated sheet data files
injectData(tmplFile, stream);
tmplFile.delete();
}
First of all, Apache-POI is open source, and that means that you are free to modify it, if you need to. In this case, modifying the write method would be better than trying to make it behave differently by messing around with the global temporary directory.
But this begs the question: Why are you trying to do this? Looking at the code of write, it is pretty clear that the method is designed to clean up after itself. If write terminates normally, the temporary file is deleted before the method returns. If it terminates abnormally, the file should be cleaned up when the JVM exits.
And if, despite the above, temporary files are still "leaking", then it should be a simple matter to write an external script that periodically finds and deletes them.
Can you save the first value of "java.io.tmpdir" in a temp variable and the set it back once you finish?
String defaultDir = System.getProperty("java.io.tmpdir")
System.setProperty("java.io.tmpdir", System.getProperty("java.io.tmpdir")+pathSpecificToFirstExport);
//createTempFile method
System.setProperty("java.io.tmpdir",defaultDir);
You can't. setProperty is always global. What you should do instead is something like
Files.createTempDirectory(System.getProperty("java.io.tempdir") + pathSpecificToFirstExport);
If you can run the jobs from maven commands you can try
mvn <command to execute job> -Djava.io.tmpdir=absolutePathSpecificToFirstExport
and run a mvn command for each job.

Java File - Append pre-defined filename to a user-defined directory

I have a program that creates multiple output files e.g. daily_results.txt, overall_results.txt etc.
I want to allow the user to specify the directory that these files will be saved to using JFileChooser.
So if the user selected the directory they wanted their output to be saved to as "C:\temp\". What is the best way to append daily_results.txt to that file object. Is there a more elegant way to do this other than:
File file = new File(userDirectory.getPath() + "daily_results.txt");
Any ideas?
Apologies!
I think this can quite easily be accomplished with the JFileChoosers setSelectedFile method.

Can I use File.createTempFile() to create a file with a non-random name

I want to create a temporary file (that goes away when the application closes) with a specific name. I'm using this code:
f = File.createTempFile("tmp", ".txt", new File("D:/"));
This creates something like D:\tmp4501156806082176909.txt. I want just D:\tmp.txt. How can I do this?
In this case, don't use createTempFile. The point of createTempFile is to generate the "garbage" name in order to avoid name colisions.
You should use File.createNewFile() or simply write to the file. Whichever is more appropriate for your use case. You can then call File.deleteOnExit() to get the VM to look after cleaning up the file.
If you want to create just tmp.txt, then just create the file using createNewFile(), instead of createTempFile(). createTempFile is used to create temporary files that should not have the same name when created over and over.
Also have a look at this post which shows a very simple way to create files.
Taken the post mentioned above:
String path = "C:"+File.separator+"hello"+File.separator+"hi.txt";
//(use relative path for Unix systems)
File f = new File(path);
//(works for both Windows and Linux)
f.mkdirs();
f.createNewFile();
try regex
fileName = fileName.replaceAll("\\d", "");

Need help with making a settings file

I am trying to make an application launcher that has a settings file that will save 'names' for programs and the path to that program, and when you type the name in an input box it will run the program that name is assigned to.
Also if it the name entered is not known by the application (in the settings file) it will ask the user to add the path and will save that name with the user set path in the settings file.
What I need to know is the best way for me to do this and read/write the file, and the easiest way to organize the settings file to be interpreted.
Any suggestions?
You could use java.util.Properties - it stores key/value pairs in a textfile, and is fairly easy to instantiate. e.g:
Properties mySettings = new Properties();
mySettings.load(new FileInputStream("myapp.cfg"));
// getProperty() returns a String
filepath1 = mySettings.getProperty("filePath1");
Then you simply save your settings in myapp.cfg, either directly (it's a simple textfile with key=value pairs), or via mySettings.store(...). The contents of myapp.cfg will look something like this:
# comment and date added by the Properties object
filePath1=/usr/bin/share/filename
otherVar=52

Categories

Resources