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.
Related
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().
I've written my own 3D Game Engine and started writing a game. I am using OBJ-Models that use the TurboSquid Royalty Free License
Basically, it says that I can use their OBJ-Files but have to implement something that avoids the users to extract the OBJ-Files out of my program.
I've written a converter that extracts the information out of the OBJ-File and creates several float/integer arrays [vertices, vertexCoords, normals, tangents..., indices]
These arrays will be used later for creating the VAOs / VBOs. So my idea was to create a Java class called OBJModelData that contains these arrays. OBJModelDataimplements Serializable. My attempt was to save the class into a file and use them instead of the OBJ-File so that the user cannot see and use the content.
My attempt looks like this:
public void writeToFile(String file){
File f = new File(OBJLoader.RES_LOC+ file +".dat");
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f));
out.writeObject(this);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
This results in a file called modelName.dat and looks like this:
Obviously reverse engineering must be done the recreate my arrays. I just do not like the way its written. For example the class that has been serialized is written in the first line. If someone somehow manages the get the source files of my engine by doing some reverse engineering on that he could easily read the file.
Is my method save enough to avoid recreating the obj files and can I still use this method to fulfill the license conditions or is there any other way that is normally used (e.g. in other games/engines) ?
The end of your quote says: "without reverse engineering", so you do not need carry about reverse engineering. You need only "translate" from OBJ to another format of your creation, like you do.
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");
I get a stream of values as CSV , based on some condition I need to generate a XML including only a set of values from the CSV. For e.g .
Input : a:value1, b:value2, c:value3, d:value4, e:value5.
if (condition1)
XML O/P = <Request><ValueOfA>value1</ValueOfA><ValueOfE>value5</ValueOfE></Request>
else if (condition2)
XML O/P = <Request><ValueOfB>value2</ValueOfB><ValueOfD>value4</ValueOfD></Request>
I want to externalize the process in a way that given a template the output XML is generated accordingly. String manipulation is the easiest way of implementing this but I do not want to mess up the XML if some special characters appear in the input, etc. Please suggest.
Perhaps you could benefit from templating engine, something like Apache Velocity.
I would suggest creating an xsd and using JAXB to create the Java binding classes that you can use to generate the XML.
I recommend my own templating engine (JATL http://code.google.com/p/jatl/) Although its geared to (X)HTML its also very good at generating XML.
I didn't bother solving the whole problem for you (that is double splitting on the input ("," and then ":").) but this is how you would use JATL.
final String a = "stuff";
HtmlWriter html = new HtmlWriter() {
#Override
protected void build() {
//If condition1
start("Request").start("ValueOfA").text(a).end().end();
}
};
//Now write.
StringWriter writer = new StringWriter();
String results = html.write(writer).getBuffer().toString();
Which would generate
<Request><ValueOfA>stuff</ValueOfA></Request>
All the correct escaping is handled for you.
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.