【发布时间】:2016-01-03 17:39:27
【问题描述】:
我已经搜索过这个答案,我试图解决这个问题,但我不能。我得到了类型的异常
No fue posible copiar los archivos. Motivo: C:\Test1 (Acceso denegado)java.io.FileNotFoundException: C:\Test1 (Acceso denegado)
java.io.FileNotFoundException: C:\Test1 (Acceso denegado)
翻译后的内容类似于“无法复制文件。动机:(拒绝访问)”。
我想要做的是将一个列表递归地复制到一个目录中。
我可以简单地递归复制文件(我已经这样做了),但要求是将所有文件复制到一个列表中,然后对列表中的记录做任何我想做的事情(复制、删除等)。
我的列表包含以下记录:
C:\Test\Carpeta_A
C:\Test\Carpeta_A\Entrenamiento_1.txt
C:\Test\Carpeta_A\Requerimientos.txt
C:\Test\Carpeta_B
C:\Test\Carpeta_B\queries.txt
C:\Test\Things.txt
这是我的代码:
这是主要方法..它调用一个方法来列出和保存文件和目录,然后调用将文件复制到另一个目录的方法,保留我的主要结构:
public static void main(String[] args) throws IOException
{
String fuente = "C:/Test";
String ruta = "C:/Test1";
teeeeeest listing = new teeeeeest();
List<File> files = listing.getFileListing(fuente);
listing.copyDirectories(files, ruta);
}
public List<File> getFileListing( String fuente ) throws FileNotFoundException
{
List<File> result = getFileListingNoSort(fuente);
Collections.sort(result);
return result;
}
private List<File> getFileListingNoSort( String fuente ) throws FileNotFoundException
{
File source = new File(fuente);
List<File> result = new ArrayList<>();
File[] filesAndDirs = source.listFiles();
List<File> filesDirs = Arrays.asList(filesAndDirs);
for(File file : filesDirs) {
result.add(file); //always add, even if directory
String s = file.getPath().trim();
if (! file.isFile()) {
//must be a directory
//recursive call!
List<File> deeperList = getFileListingNoSort(s);
result.addAll(deeperList);
}
}
return result;
}
public static void copyDirectories(List<File> files, String destiny)
throws IOException
{
InputStream in = null;
OutputStream out = null;
File targetPath = new File(destiny);
System.out.println(targetPath.getPath());
for(int i = 0; i < files.size(); i++)
{
File temp = new File(files.get(i).toString());
//System.out.println(temp.getPath());
try
{
if(temp.isDirectory())
{
if(!targetPath.exists())
{
targetPath.mkdir();
}
File[] filesAndDirs = temp.listFiles();
List<File> filesDirs = Arrays.asList(filesAndDirs);
for(File file : filesDirs)
{
if (! file.isFile())
{
//must be a directory
//recursive call!
copyDirectories(filesDirs,destiny);
}
}
}
else
{
in = new FileInputStream(files.get(i).toString());
out = new FileOutputStream(targetPath);
System.out.println(temp.getPath());
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
{
out.write(buf, 0, len);
}
}
}
catch(Exception e)
{
System.err.println("No fue posible copiar los archivos. Motivo: " + e.getMessage() + e);
e.printStackTrace();
}
}
}
【问题讨论】:
-
第一个例外是
FileNotFoundException,它拒绝访问,因为它首先找不到文件/目录。当您尝试阅读或尝试写入时是否会引发异常?C:\Test1是您的目标文件夹吗? -
C:\Test1存在吗? -
是的,C:\Test1 存在,是的,它是目标文件夹,在调试时我在这一行得到了异常:out = new FileOutputStream(targetPath);
-
如果您打开命令提示符,导航到 c:\test1 并输入 echo XXX > test.out 会发生什么?这将测试您是否对该目录具有写入权限。
-
Dit it.. 答案是肯定的。我有写权限。