0

I have a question about the com.jmatio.io package that I was hoping someone could answer. I am looking to write to a .mat file (using java) that may or may not already exist. If it exists I would like to append the information to the end but if the file is not created I would like to create a new file and just add the contents to that. My second write is overwriting the first but I would not like it to do this. Any suggestions or solutions is gladly appreciated.

Shahzad Barkati
  • 2,532
  • 6
  • 25
  • 33
TomMcG
  • 1
  • 6

2 Answers2

0

You need to write in append mode so the content get appended to the end to the file instead of overwriting.

File out = new File("out.mat");
try(FileWriter fw = new FileWriter(out, true);  // true is for append
    BufferedWriter bw = new BufferedWriter(fw)) {
    // ...
}

If the file does not exist, it will be created.

Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
  • Thanks for the quick reply.This is the few lines of code that im using. "double[] db = new double[] {1.0,2.0,3.0,4.0,5.0,6.0}; MLDouble mlDouble = new MLDouble( "double_arr", db, 3 ); ArrayList list = new ArrayList(); list.add( mlDouble ); MatFileIncrementalWriter MW = new MatFileIncrementalWriter(completePath); MW.write(list); double[] newDB = new double[] {7.0,8.0,9.0,10.0,11.0,12.0}; MLDouble mlDouble1 = new MLDouble( "double_arr", db, 3 ); list.add(0, mlDouble ); MW.write(list); " How can I apply you're answer to that? – TomMcG Apr 14 '15 at 14:15
  • You should write this in your question – yunandtidus Apr 14 '15 at 14:45
0

If you want to write multiple arrays to a new file you can achieve it using the MatFileIncrementalWriter. As it's explained in it's javadoc

An updated writer which allows adding variables incrementally for the life of the writer. This is necessary to allow large variables to be written without having to hold onto then longer than is necessary.

And it states clearly that you can't append to an existing file.

If you want to append to an existing file you might need

  • read variables from the existing file
  • write the existing variables back to the file using a MatFileIncrementalWriter
  • add new variables to the incremental writer
SubOptimal
  • 22,518
  • 3
  • 53
  • 69
  • Thanks for the reply, Yes I used MatFileIncrementalWriter and it worked for me and I now no longer need to append to a new file, thanks for you're help though :) – TomMcG Apr 15 '15 at 08:11