How to use java.nio in MATLAB?

 采纳的回答

Here is two example of deleting a file using java.nio.file.
%% Method1
str = fullfile(pwd, 'test1.txt' );
%jpath1 = java.nio.file.Paths.get(str) % not works
jpath1 = java.nio.file.Paths.get(str, javaArray('java.lang.String', 0)); % works
java.nio.file.Files.delete(jpath1)
%% Method2
jpath2 = java.nio.file.Paths.get(pwd, 'test2.txt');
java.nio.file.Files.delete(jpath2)
I've tested in MATLAB R2018b on Windows 10.
As you may know, from R2017b, MATLAB's JVM was changed to Java 8. So, java.nio.file.Files.delete used in MATLAB R2017b ~ R2018b is that of Java 8.

4 个评论

Thank you.
java.nio.file.Files is also part of Java 7, which is available in MATLAB R2013b (8.2) or newer. I use R2015.
Method2 works, but Method1 does not:
str = fullfile(pwd, 'test1.txt' );
jpath1 = java.nio.file.Paths.get(str, javaArray('java.lang.String', 0))
Error using javaArray
All dimension arguments must be greater than zero
The problem is that before I used
java.io.File(['\\?\' filename]).delete
where filename is full file name (e.g. 'C:\myfiles\test1.txt'),
and it worked fine.
That UNC-path prefix ('\\?\') was used to work with unusual files which are not processed by conventional methods (with specific characters in their names).
If I use the Method2 with that pathname:
jpath2 = java.nio.file.Paths.get(['\\?\' pwd], 'test2.txt')
Java exception occurred:
java.nio.file.InvalidPathException: Illegal character [?] in path at index 2: \\?\C:\myfiles\test2.txt
at sun.nio.fs.WindowsPathParser.nextSlash(Unknown Source)
at sun.nio.fs.WindowsPathParser.parse(Unknown Source)
at sun.nio.fs.WindowsPathParser.parse(Unknown Source)
at sun.nio.fs.WindowsPath.parse(Unknown Source)
at sun.nio.fs.WindowsFileSystem.getPath(Unknown Source)
at java.nio.file.Paths.get(Unknown Source)
So, is there any way to use UNC-path with java.nio?
What is the problem with Method1 that you proposed?
Btw, how to determine the success of the operation:
java.nio.file.Files.delete(jpath2)
>> Btw, how to determine the success of the operation:
I would simply use "try catch".
try
java.nio.file.Files.delete(jpath2)
catch ME
% When delete was failed, do some error handle
error(ME.message)
end
% When delete was successful
msgbox('Successfully deleted')
ME.message - gives error...

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Cell Arrays 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by