1

I've made a java application that manipulates a few matrices it gets as input, and then outputs some text. Currently the matrices are hardcoded in my application (for testing), but recompiling is quite silly for a new matrix.

So I'm looking for a config file format that would be suited for inputting matrices.

I know I can read ini files easily ( What is the easiest way to parse an INI file in Java?), but then parsing a thing like [ [ 1, 2, 3], [4, 5, 6] ] to a matrix would probably require annoying string manipulation.

Does anyone know of a nice method to read in these matrices?

Community
  • 1
  • 1
Tominator
  • 1,224
  • 3
  • 19
  • 37

3 Answers3

3

You can use JSON as the data interchange format. Take a look at JSON in Java.

Community
  • 1
  • 1
Marcelo
  • 11,218
  • 1
  • 37
  • 51
2

how about CSV files?

your input could look something like

1;2;3
4;5;6

There are also some already built CSV parser around... like http://commons.apache.org/sandbox/csv/

udo
  • 1,486
  • 13
  • 18
  • CSV is simple. Simple is good. Lots more than Apache's parser available: http://www.google.com/search?q=java+csv – Jonathon Faust Jun 20 '11 at 14:22
  • Since you're controlling your input, you can simply use two delimiters for rows and columns, and use String.split() to parse them. The other way would be to use one type of delimiter and head your file with the row and column count. –  Jun 20 '11 at 14:23
  • CSV is a handy format, but I'm using a set of ~15 small matrices, so I'd need to be sure all separate files are in order, and it's a bit more tricky to maintain. It's not a bad solution, just not one i'll follow in this current case, thanks though! – Tominator Jun 20 '11 at 14:50
1

I second on csv files. However, it can also be handy to use property files, one line representing one matrix. Something like this:

property.test="A,B,C;A1,B1,C1;A2,B2,C2";

And then using java.util.Properties to read the file.

Parsing: The trick here is in choosing separators, they must not be present in the entries themselves.

String str = "A,B,C;A1,B1,C1;A2,B2,C2";
String[] rows = str.split(";");
if(rows != null && rows.length > 0){
   String[][] result = new String[rows.length][];
   for(int row = 0; row < rows.length; row++){
       result[row] = rows[row].split(",");      
   }
 }
Taisin
  • 491
  • 2
  • 6
  • Properties library and example code are a plus! But still needs parsing and knowing the separators, while JSON handles them (escaping rules and so on).. Thanks for the help! – Tominator Jun 20 '11 at 14:51