Reading INI File in JAVA - java

I was trying to get values from an INI File and I'm writing the code in Java.
So far, I have read about this function and yes, it is returning values from the INI File.
String property = properties.getProperty("property.name");
But this is the code that I need.
Is there a function in Java that is equivalent to the GetPrivateProfileString of C?

No, there is no built-in initialization .INI file support in Java.
Java uses Properties files, which lays its data out like so:
propertyOne = 1
propertyTwo = 2
C uses Initialization files (.INI), which lays its data out in sections:
[Section]
propertyOne = 1
propertyTwo = 2
In Java, Properties don't have "sections", but can be divided up into sections by the same convention for naming packages:
section.propertyOne = 1
section.propertyTwo = 2
So you would call properties.getProperty("section.propertyOne");, where in INI you call the section first and then the property instead of as one.
INI files offer some more usefulness, but are not natively supported. A good 3rd party Java API for dealing with INI files is ini4j.
http://ini4j.sourceforge.net/
The reason for this is that .INI is a Windows-specific file. You won't really find .INI files on other operating systems, and Java is a cross-platform language.

Related

How can you load data dynamically with the FMPP Java API?

I am integrating a FMPP transformation into our Java code base. For this, I am using the FMPP Java API. For practical reasons, I have two separate directories:
one which contains the template: <absolute path template>/template.ftlx
one which contains the data: <absolute path data>/data.xml
This somehow complicates things, as I have to work with absolute paths here. Typically, the data is inside the template directory (together with a ignoredir.fmpp file). However, in our application, the data is coming from an external source (it is uploadable via a REST API), while the template is in the classpath. This also means that the data directory isn't static.
I am struggling to define all this and get the transformation happening via the Java API. Currently, I have the following:
Settings s = new Settings(new File("."));
s.set(Settings.NAME_SOURCES, new File("<absolute path template>/template.ftlx").getAbsolutePath());
s.set(Settings.NAME_OUTPUT_FILE, new File("<absolute path output>/output.xml").getAbsolutePath());
s.execute();
The code snippet above is not complete, as I have to add the data. There are the Settings.NAME_DATA and Settings.NAME_DATA_ROOT properties, but I can't get it working. I tried setting Settings.NAME_DATA_ROOT as following:
s.set(Settings.NAME_DATA_ROOT, new File("<absolute path data>").getAbsolutePath());
Then, I get the exception that FreeMarker cannot find my data:
The following has evaluated to null or missing:
==> d [in template "template.ftlx" at line 4, column 12]
In the template, I simply do:
<#list d.items>...</#list>
This makes sense that this would not work, as I did nowhere define that the data should be accessible via the d. hash (which I am doing below in config.fmpp). But I don't know how to define that properly via Settings.NAME_DATA and/or Settings.NAME_DATA_ROOT.
How can I inject my data file into all this? It should get the key d, so I can refer to d. in the template.
reference
Just as reference, if I create the following config.fmpp file in <absolute path config>, put the data.xml data file in directory <absolute path data> and call s.load(new File("<absolute path config>/config.fmpp")) before s.execute() above, everything is working fine.
data: {
d: xml(<absolute path data>/data.xml)
}
All I have to figure out is doing this in a dynamic fashion via the Java API. I cannot use config.fmpp for this, as the location of the data isn't static (and, as far as I know, config.fmpp is not parametrizable).
working solution, with doubts
After some code reading, I got it working if I do the following:
Settings s = new Settings(new File("."));
s.set(Settings.NAME_SOURCES, new File("<absolute path template>/template.ftlx").getAbsolutePath());
s.set(Settings.NAME_OUTPUT_FILE, new File("<absolute path output>/output.xml").getAbsolutePath());
s.set(Settings.NAME_DATA, "{d:xml(<absolute path output>/data.xml)}");
s.execute();
Here, we pass {configuration:xml(<absolute path output>/data.xml)} as a TDD to the NAME_DATA property. Is this the way to go? It "feels" strange to construct a textual definition in our code. Is there a way to do this in pure Java?

How to set the User Defined File Attribute in Java NIO for Unix OS?

I am trying to set user defined attribute to a file, for example, version=1 to the file foo.txt. So that I can retrieve the version attribute later.
I see Java NIO package provide such mechanism, I followed this document. However, I am trying to run this in my Unix operating system, it says null pointer exception, also I see that the blog says it is window-specific. So How can write attributes to file in Unix?
UserDefinedFileAttributeView userDefinedFAView = Files
.getFileAttributeView(path, UserDefinedFileAttributeView.class);
List<String> attributeList = userDefinedFAView.list();
System.out.println("User Defined Attribute List Size Before Adding: "
+ attributeList.size());
// set user define attribute
String attributeName = "version";
String attributeValue = "1";
userDefinedFAView.write(attributeName,
Charset.defaultCharset().encode(attributeValue));
The entire source code is below:
https://gist.github.com/ajayramesh23/e21d6159d8271fe0a4cfaf7209f6fb74
Reference blog for the source-code:
http://javapapers.com/java/file-attributes-using-java-nio/
Please provide the best way in Java 7 or above to set the file attributes.
Also, I see that Java Doc mentioned this below note:
Note:
In Linux, you might have to enable extended attributes for
user-defined attributes to work. If you receive an
UnsupportedOperationException when trying to access the user-defined
attribute view, you need to remount the file system. The following
command remounts the root partition with extended attributes for the
ext3 file system. If this command does not work for your flavor of
Linux, consult the documentation.
$ sudo mount -o remount,user_xattr /
If you want to make the change permanent, add an entry to /etc/fstab.
So How to set user-defined attributes without doing above note.

What type of File is created when we create new File without the extension?

In java, when we create a file, we create files using the name of the extension.
For example :
File file = new File("D:/light.txt");
I would like to know what type of file format do we get when we create a file without the file extension type.
For example :
File file = new File("D:/light");
This answer assumes you're doing more than just creating a File object - that you're actually creating a file on the file system. (A File object is just a logically representation of a file system entry which may or may not exist.) If you're really just creating a File object, read EJP's answer - at that point, you've basically just got a name. That doesn't have a "type" or a "format".
The extension is just part of the name. The operating system may try to use that to display a different icon, or launch a specific application when you double-click on the icon, or whatever - but it's really just part of the name.
Fundamentally, a file consists of:
The name you specify when you create it
The bytes you write in it
Metadata such as access control
Unless you deliberately add metadata, it's typically just inherited (default permissions etc).
You can write any data in any file - just because a file has an extension of .txt doesn't mean it's definitely a text file. It could have content which is actually MP3-encoded audio data, for example. Whether the OS uses the file extension or the content to work out what to do with the file is up to the OS.
What type of File is created when we create new File without the extension?
No file is created at all, and there is only one type of File.
In java, when we create a file, we create files using the name of the extension.
Or not.
For example: File file = new File("D:/light.txt");
I would like to know what type of file format do we get when we create a file without the file extension type.
You don't. You don't get any file format at all, because you don't get a file: only a File object in memory.
For example: File file = new File("D:/light");
You can produce all the examples you want, but no file is created, and no file format.
In any case Java doesn't care about filename extensions. Your operating system might, but that's a different story.

How to reference a system property within a user-defined .properties file?

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();

Get the Last Access Time for a File

I know that using File object we can get the last modified time for a File (i.e. File.lastModified()). But, my requirement is to get the last accessed time for a File in Java. How do I get it?
You will need to use the new file I/O API (NIO2) which comes with Java 7. It has a method lastAccessTime() for reading the last access time.
Here is a usage example:
Path file = ...
BasicFileAttributes attrs = Files.readAttributes(file, BasicFileAttributes.class);
FileTime time = attrs.lastAccessTime();
For more information see Managing Metadata in the Java Tutorial.
You can't do it with plain Java, you'll need to use JNI to access the platform specific data such as this or use extensions to the core Java library like the following:
javaxt.io.File file = new javaxt.io.File("path");
file.getLastAccessTime();
Or, if you have Java 7, go with Esko's answer and use NIO.

Categories

Resources