Java Properties File: Useful Case of Empty Property Value? - java

I am messing with properties-files in Java. I want to know if there are some properties-files that use empty values ('propertyName=\n') and what they are used for?
[Update]
Since some folks are still irritated here is a better description:
A sample properties file might look like:
database.username = john
database.password = johnsSecret
Ok so its simple. Now the question is if someone have seen something like:
anyProperty =
I am just asking if you know a use case that actually happen where you needed to express an empty property value within a property file and why was it.
PS: This is no social experiment, it is to determine if this case is practical needed or if I can use it to express the desire to remove the property when specifying a delta to transform an existing properties file by adding or removing its entries. Alternatively I will use -propertyname to remove any property.

The question is so vague I vote to close for "unclear what you are asking", it's so strange that even seems to be a social experiment to analyse people answers from random generated questions..
Having said that, this code saves and read a properties files with what you are asking for.
//Write
String fileName="fileInTheWild.properties";
Properties prop= new Properties();
OutputStream fos = new FileOutputStream( fileName );
prop.put("propertyName", "\n");
prop.store(fos, "Some Properties");
//Read
prop.load(new FileReader(fileName));
String newLine= prop.getProperty("propertyName");
System.out.println("Line 1" + newLine +"Line 2");

Related

How can I modify a particular line in a file without deleting the existing data using Java?

I need to change the values in a file which has more than 30 lines and each line has a data like:
ENABLE_TLS=true
PSWD_MIN_LENGTH=8
Here, let us consider this as a key and value pair, and I needed to change only the value for the 2nd line alone, without deleting the 1st line. Can someone help me how can I do this??
I have tried bufferedwriter, but it is replacing all the lines.
My expectation is:
I need to modify only a particular key's value and the remaining lines should not get deleted
Your description of the data sounds like Java Properties. If you are certain that all the data in that file takes the form key=value you could read it in as a Properties object, update the value for the key in question, and write it back to the file.
Properties properties = new Properties();
try (FileInputStream inputStream = new FileInputStream("/path/to/file")) {
properties.load(inputStream);
}
properties.put("PSWD_MIN_LENGTH", 12);
try (FileOutputStream outputStream = new FileOutputStream("/path/to/file")) {
properties.store(outputStream, null);
}
BEWARE: there is no guarantee that the order of the key/value entries in the file will be maintained (they probably won't). If you are looking for a Properties implementation that will maintain the order, maybe this SO answer will do the trick (UNTESTED!) How maintain the order of keys in Java properties file?

Creating a text file with java without using absolute path

following the question I asked before How to have my java project to use some files without using their absolute path? I found the solution but another problem popped up in creating text files that I want to write into.here's my code:
private String pathProvider() throws Exception {
//finding the location where the jar file has been located
String jarPath=URLDecoder.decode(getClass().getProtectionDomain().getCodeSource().getLocation().getPath(), "UTF-8");
//creating the full and final path
String completePath=jarPath.substring(0,jarPath.lastIndexOf("/"))+File.separator+"Records.txt";
return completePath;
}
public void writeRecord() {
try(Formatter writer=new Formatter(new FileWriter(new File(pathProvider()),true))) {
writer.format("%s %s %s %s %s %s %s %s %n", whichIsChecked(),nameInput.getText(),lastNameInput.getText()
,idInput.getText(),fieldOfStudyInput.getText(),date.getSelectedItem().toString()
,month.getSelectedItem().toString(),year.getSelectedItem().toString());
successful();
} catch (Exception e) {
failure();
}
}
this works and creates the text file wherever the jar file is running from but my problem is that when the information is been written to the file, the numbers,symbols, and English characters are remained but other characters which are in Persian are turned into question marks. like: ????? 111 ????? ????.although running the app in eclipse doesn't make this problem,running the jar does.
Note:I found the code ,inside pathProvider method, in some person's question.
Your pasted code and the linked question are complete red herrings - they have nothing whatsoever to do with the error you ran into. Also, that protection domain stuff is a hack and you've been told before not to write data files next to your jar files, it's not how OSes (are supposed to) work. Use user.home for this.
There is nothing in this method that explains the question marks - the string, as returned, has plenty of issues (see above), but NOT that it will result in question marks in the output.
Files are fundamentally bytes. Strings are fundamentally characters. Therefore, when you write code that writes a string to a file, some code somewhere is converting chars to bytes.
Make sure the place where that happens includes a charset encoding.
Use the new API (I think you've also been told to do this, by me, in an earlier question of yours) which defaults to UTF-8. Alternatively, specify UTF-8 when you write. Note that the usage of UTF-8 here is about the file name, not the contents of it (as in, if you put persian symbols in the file name, it's not about persian symbols in the contents of the file / in the contents you want to write).
Because you didn't paste the code, I can't give you specific details as there are hundreds of ways to do this, and I do not know which one you used.
To write to a file given a String representing its path:
Path p = Paths.get(completePath);
Files.write("Hello, World!", p);
is all you need. This will write as UTF_8, which can handle persian symbols (because the Files API defaults to UTF-8 if you specify no encoding, unlike e.g. new File, FileOutputStream, FileWriter, etc).
If you're using outdated APIs: new BufferedWriter(new OutputStreamWriter(new FileOutputStream(thePath), StandardCharsets.UTF-8) - but note that this is a resource leak bug unless you add the appropriate try-with-resources.
If you're using FileWriter: FileWriter is broken, never use this class. Use something else.
If you're converting the string on its own, it's str.getBytes(StandardCharsets.UTF_8), not str.getBytes().

filter properties input file

I've an existing application using language specific properties files.
For better handling I want to work within a single file only and
select entries while reading the file. The format should be
...
//en myValue=myValue
//ge myValue=meinWert
...
instantiated for 'ge' properties loading should only catch
...
myValue=meinWert
...
I like to stick with the Properties class and hand over an
e.g. FilterInputStream.
Is this the right way to go or any better idea?
thanks
Wolfgang R.
String langTag = "en"; //Example
try {
BufferedReader input = new BufferedReader(new FileReader(<path to file>));
String inputString;
while((inputString = input.readLine()) != null) {
if(inputString.substring(2, 4).equals(langTag))
//Do something
}
} catch(IOException e) {
System.err.println(e);
}
I will admit the while loop is very doubious.
As you ask if this is the right way, I answer NO unless you have a very good reason to do so. You are about to replace a core JDK fuctionnality that is extensively tested, used and probably correctly optimized by your own ... that you will have to test and maintain.
You'd didn't say why you want a different format for your properties file. I presume you simply find it easier to maintain. If its the real reason, you'd better contemplate a preprocessor task (in ant, maven or ... a simple batch) that take your proposed format as input and produces standard properties files. That way :
you have your prefered format in edition
the app has its standard format in production
the conversion only occurs when properties are modified
If you look how advanced CSS frameworks (SASS, LESS or Stylus) work, they do have an internal format that is pre-processed to produce standard CSS files.

How to change the Properties.store() divider symbol from "=" to ":"?

I recently found out about java.util.Properties, which allows me to write and read from a config without writing my own function for it.
I was excited since it is so easy to use, but later noticed a flaw when I stored the modified config file.
Here is my code, quite simple for now:
FileWriter writer = null;
Properties configFile = new Properties();
configFile.load(ReadFileTest.class.getClassLoader().getResourceAsStream("config.txt"));
String screenwidth = configFile.getProperty("screenwidth");
String screenheight = configFile.getProperty("screenheight");
System.out.println(screenwidth);
System.out.println(screenheight);
configFile.setProperty("screenwidth", "1024");
configFile.setProperty("screenheight", "600");
try {
writer = new FileWriter("config.txt" );
configFile.store(writer, null);
} catch (IOException e) {
e.printStackTrace();
}
writer.flush();
writer.close();
The problem I noticed was that the config file I try to edit is stored like this:
foo: bar
bar: foo
foobar: barfoo
However, the output after properties.store(writer, null) is this:
foo=bar
bar=foo
foobar=barfoo
The config file I edit is not for my program, it is for an other application that needs the config file to be in the format shown above with : as divider or else it will reset the configuration to default.
Does anybody know how to easily change this?
I searched through the first 5 Google pages now but found noone with a similar problem.
I also checked the Javadoc and found no function that allows me to change it without writing a class for myself.
I would like to use Properties for now since it is there and quite easy to use.
I also got the idea of just replacing all = with : after I saved the file but maybe someone got a better suggestion?
Don't use a tool that isn't designed for the task - don't use Properties here. Instead, I'd just write your own - should be easy enough.
You can still use a Properties instance as your "store", but don't use it for serializing the properties to text. Instead, just use a FileWriter, iterate through the properties, and write the lines yourself - as key + ": " + value.
New idea here
Your comment about converting the = to : got me thinking: Properties.store() writes to a Stream. You could use an in-memory ByteArrayOutputStream, convert as appropriate in memory before you write to a file, then write the file. Likewise for Properties.load(). Or you could insert FilterXXXs instead. (I'd probably do it in memory).
I was looking into how hard it would be to subclass. It's nearly impossible. :-(
If you look at the source code for Properties, (I'm looking at Java 6) store() calls store0(). Now, unfortunately, store0 is private, not protected, and the "=" is given as a magic constant, not something read from a property. And it calls another private method called saveConvert() that also has a lot of magic constants.
Overall, I rate this code as D- quality. It breaks almost all the rules of good code and good style.
But, it's open source, so, theoretically, you could copy and paste (and improve!) a bunch of code into your own BetterProperties class.

Get real file extension -Java code

I would like to determine real file extension for security reason.
How can I do that?
Supposing you really mean to get the true content type of a file (ie it's MIME type) you should refer to this excellent answer.
You can get the true content type of a file in Java using the following code:
File file = new File("filename.asgdsag");
InputStream is = new BufferedInputStream(new FileInputStream(file));
String mimeType = URLConnection.guessContentTypeFromStream(is);
There are a number of ways that you can do this, some more complicated (and more reliable) than others. The page I linked to discusses quite a few of these approaches.
Not sure exactly what you mean, but however you do this it is only going to work for the specific set of file formats which are known to you
you could exclude executables (are you talking windows here?) - there's some file header information here http://support.microsoft.com/kb/65122 - you could scan and block files which look like they have an exe header - is this getting close to what you mean when you say 'real file extension'?

Categories

Resources