MATLAB: How to keep java file formatting after modification in Matlab using fprintf()

fprintfjavaMATLABregexprep

I am trying to modify the content of a .java file and write a new modified .java file. Without loss of generality imagine the content is:
import com
V8_Final\\Study_components_gap_dependence
and I want the new .java file to be
import com
V9_Final\\Study_components_gap_dependence
My approach to do this is as follow:
clc, clear all, close all
%%Import
fid = fopen('A.java','r');
f = textscan(fid,'%s','Delimiter','\n');
txt = f{:};
fclose(fid);
%%Make changes
txt = regexprep(txt,'V8','V9');
%%Write the new file
txt = regexprep(txt,'(.*)','$1\n');
txt = [txt{:}];
fid = fopen('A_mod.java','w');
fprintf(fid,txt);
fclose(fid);
But I get:
import com
V9_Final\Study_components_gap_dependence
I need to keep the blank line in between lines, the spaces before V8… and the double \\, otherwise the .java file is unusable.
All those 3 undesirable changes seems to happen when I do
fprintf(fid,txt);
Any idea how to fix it?
Thank you

Best Answer

txt = fileread('A.java');
txt = regexprep(txt, 'V8_', 'V9_', 'once');
fid = fopen('A_mod.java', 'w');
fwrite(fid, txt);
fclose(fid);