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());
Related
I am making an HTTP Server in Java so that (on start) it finds all files in a directory (and it's sub-directories) and adds them to the server. But when getting the path of a file and trying to give it to HttpServer.createContext(), it throws a java.lang.IllegalArgumentException: Illegal value for path or protocol. (with the string argument, say "\folder/index.html"). To get this value, I used
file.getParent().substring(24) + "/" + file.getName()
I used substring because I had to exclude the folder the web server is in. The illegal character is the backslash. I have tried extending File to change separator and separatorChar, but that only created 2 new variables. While using String.replace() didn't seem to have any effect. Is there a different method than File.getParent or File.getPath that I can use, or is there a way to use String.replace that I am not seeing?
EDIT:
String.replace() seems to be the best answer... But I am not completely sure how to use it.
EDIT 2: For some reason the backslash isn't showing up, so I changed it.
You have to use the java System.getProperty.
Notice that, in this context, "file.separator" is a key which we are
using to get this property from current system executing the java VM.
Insteady of using a slash (/), you should choose a platform agnostic file separator, as an example it should be:
String separator = System.getProperty("file.separator");
System.out.println(separator);
// unix / , windows \
Have a look at Paths.get(...)
Try Paths.get(".") // current working directory.
Or tell it, on which path it should start:
Use System.getProperty("user.dir"), for current loged in user, home directory.
String pathStr = "/";
Path homeDir = Paths.get(System.getProperty("user.dir"))
Getting from the user directory into the data directory: homeDir.get("data")
Path dataPath = Paths.get(System.getProperty("user.dir"));
File dataFile = dataPath.toFile();
Now use operations on dataFile, to check what files and directories there are, on that location of the file system.
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.
I 'm trying to create new file in windows 7 using
file.createNewFile()
but the file is not created and I got the following exception
Message:
The system cannot find the path specified
Stack Trace:
[java.io.IOException: The system cannot find the path specified,
at java.io.WinNTFileSystem.createFileExclusively(Native Method),
at java.io.File.createNewFile(File.java:883),
at com.mercury.mtf.actions.file.CreateEmptyFileTask.execute(CreateEmptyFileTask.java:56),
at com.mercury.mtf.actions.file.CreateEmptyFileAction.execute(CreateEmptyFileAction.java:42),
at com.mercury.mtf.core.AbstractAction.run(AbstractAction.java:50),
at com.mercury.mtf.core.Unit.runUnitAction(Unit.java:347),
at com.mercury.mtf.core.Unit.executeUnitAction(Unit.java:176),
at com.mercury.mtf.core.Unit.run(Unit.java:121),
at com.mercury.mtf.core.execution.DefaultUnitExecutor.call(DefaultUnitExecutor.java:24),
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303),
at java.util.concurrent.FutureTask.run(FutureTask.java:138),
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:98),
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:207),
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886),
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908),
at java.lang.Thread.run(Thread.java:619)]
I'm sure that the path exists, but I realized that the folder marked as read only. I tried to remove the read only flag but I can't get this to work.
Make sure your path separator character is proper.. You can use single forward slash or double back slashes. For example,
File f = new File("C:\\Documents and Settings\\thandasoru\\My Documents\\temp.txt");
f.createNewFile();
If the file is temporary you can use this function and you can forget all permissions problems:
File.createTempFile("prefix", "suffix")
Use File newFile=new File(folderName+chipItems[i]); rather than using File newFile=new File(folderName+chipItems[i], "w");. That will be OK. Avoid File Mode when you like to give functionality like Unix touch command.
I want to define a property for a working directory(say work.dir=/home/username/working-directory), for my production .properties file, without hard-coding the /home/username.
I want to reference the system property user.home in place on the hard-coded /home/username, to make work.dir more generic.
How do I reference the system property and concatenate it will other user-defined strings in a user-defined .properties?
Note: I don't want to access the user.home property in my java code, but from the .properties that I have defined. I want to be able to replace the value of the work.dir with different value for both my production and development(JUnit tests for example).
Get the property from the file, then replace supported macros.
String propertyValue = System.getProperty("work.dir");
String userHome = System.getProperty("user.home" );
String evaluatedPropertyValue = propertyValue.replace("$user.home", userHome );
You can manage your properties with Commons Configuration and use Variable Interpolation
If you are familiar with Ant or Maven, you have most certainly already encountered the variables (like ${token}) that are automatically expanded when the configuration file is loaded. Commons Configuration supports this feature as well[...]
That would allow a .properties file with
work.dir=${user.home}/working-directory
This feature is not available in java.util.Properties. But many libraries add variable substitution to properties.
Here an example of what you are trying to do using OWNER API library (see paragraph "importing properties"):
public interface SystemPropertiesExample extends Config {
#DefaultValue("Welcome: ${user.name}")
String welcomeString();
#DefaultValue("${TMPDIR}/tempFile.tmp")
File tempFile();
}
SystemPropertiesExample conf =
ConfigFactory.create(SystemPropertiesExample.class, System.getProperties(), System.getenv());
String welcome = conf.welcomeString();
File temp = conf.tempFile();
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