how to quickly rename file in MATLAB?
how to change file extension quickly in batch?
method 1.
by movefile
eg.
movefile(‘test.txt’,’test.test’); rename file test.txt to test.test.test
but this is a very inefficient function
method 2.
invoke java machine
eg.
java.io.File('test.txt ').renameTo(java.io.File('test.test '));
this is super faster than movefile function
then … using java to do file extension rename
usage:
DirStruct=dir('*.txt');
ChangeFileExtension(DirStruct,'.m');
change all *.txt file to *.m
function ChangeFileExtension(DirStruct,NewExtension)
% author Laiso Taiwan
% extension ,such as '.txt'
% if no extension then append
% else remove old extension and appent the new one
% 'name' char
% 'date' char
% 'bytes' 1*1 double
% 'isdir' 1*1 logic
% 'datenum' 1*1 double
StructFields={'name'
'date'
'bytes'
'isdir'
'datenum'};
if(~isequal(fieldnames(DirStruct),StructFields))
error('input is not dir struct');
end
if ~(ischar(DirStruct(1).name)&&ischar(DirStruct(1).date)&&isa(DirStruct(1).bytes,'double') ...
&&numel(DirStruct(1).bytes)==1&&isa(DirStruct(1).isdir,'logical')...
&&numel(DirStruct(1).isdir)==1&&isa(DirStruct(1).datenum,'double')&&numel(DirStruct(1).datenum)==1)
error('input is not dir struct');
end
for i=1:numel(DirStruct)
Dot=find(DirStruct(i).name=='.',1,'last');
if ~isempty(Dot)
%movefile(DirStruct(i).name,[DirStruct(i).name(1:Dot-1) NewExtension]);
java.io.File(DirStruct(i).name).renameTo(java.io.File([DirStruct(i).name(1:Dot-1) NewExtension]));
else
% movefile(DirStruct(i).name,[DirStruct(i).name NewExtension]);
java.io.File(DirStruct(i).name).renameTo(java.io.File([DirStruct(i).name NewExtension]));
end
end
沒有留言:
張貼留言