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

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

 채택된 답변

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by