请考虑以下示例Java类(下面的pom.xml):
package test.filedelete;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import org.apache.commons.io.IOUtils;
public class Main
{
public static void main(String[] args) throws IOException
{
byte[] bytes = "testtesttesttesttesttesttesttesttesttest".getBytes();
InputStream is = new ByteArrayInputStream(bytes);
Path tempFileToBeDeleted = Files.createTempFile("test", "");
OutputStream os = Files.newOutputStream(tempFileToBeDeleted);
IOUtils.copy(is, os);
deleteAndCheck(tempFileToBeDeleted);
// breakpoint 1
System.out.println("\nClosing stream\n");
os.close();
deleteAndCheck(tempFileToBeDeleted);
}
private static void deleteAndCheck(Path file) throws IOException
{
System.out.println("Deleting file: " + file);
try
{
Files.delete(file);
}
catch (NoSuchFileException e) …Run Code Online (Sandbox Code Playgroud) 我有以下代码,我需要捕获AccessDeniedException异常
import java.io.PrintWriter;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
class MyFileClass {
public void write()
throws IOException
{
PrintWriter out = new PrintWriter("sample.txt");
out.printf("%8.2f\n", 3.4);
out.close();
}
}
public class MyClass {
public static void main(String[] args)
throws Exception
{
try {
MyFileClass mf = new MyFileClass();
mf.write();
} catch (AccessDeniedException e) {
print("Access denided");
}
catch (FileNotFoundException e) {
print("File not found");
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果sample.txt是只读的,我输出为" 找不到文件 "而不是" 访问已拒绝 ".我想了解这是什么原因?另外,上面的结构是否AccessDeniedException正确捕捉?
我正在做一个java.nio.file.Files.move(path, path.resolveSibling("newfilename"))重命名Windows 7上的目录.
但我得到以下异常:
java.nio.file.AccessDeniedException: oldfilename -> newfilename
at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:83)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
at sun.nio.fs.WindowsFileCopy.move(WindowsFileCopy.java:387)
at sun.nio.fs.WindowsFileSystemProvider.move(WindowsFileSystemProvider.java:287)
at java.nio.file.Files.move(Files.java:1345)
Run Code Online (Sandbox Code Playgroud)
是什么造成的?我正在使用Java 7.
在调用之前目标路径不存在Files.move().
UPDATE
When moving a directory requires that its entries be moved then this method fails
(by throwing an IOException).
Run Code Online (Sandbox Code Playgroud)
我的目录是非空的并且包含常规文件,所以也许这就是它不能在这里使用的原因?我在理解"要求移动其条目"的措辞方面遇到了问题.这是什么情况?