在java中传输文件的问题

时间:2011-09-01 10:52:12

标签: java file-transfer

我有方法

protected String browsesFile() {        
            String url = null;
            FileDialog dialog = new FileDialog(PlatformUI.getWorkbench()
                    .getActiveWorkbenchWindow().getShell(), SWT.NULL);
            // set the filter options
            dialog.setFilterExtensions(new String[] { "*.jpg", "*.jpeg", "*.png" });
            String path = dialog.open();
            if (path != null) {
                File file = new File(path);
                if (file.isFile())
                    url = file.toString();
                else
                    url = file.list().toString();
            }
            return url;
        }// end of method browseFile()

它将带来文件的url 。我将其称为text.setText(browsesFile());。这将带来我选择的图像网址。我希望将该图片转移到G:\myImage。为了转移我做了以下。

    public static void copyFile(File sourceFile, File destFile) throws IOException {
     if(!destFile.exists()) {
      destFile.createNewFile();
     }

     FileChannel source = null;
     FileChannel destination = null;
     try {
      source = new FileInputStream(sourceFile).getChannel();
      destination = new FileOutputStream(destFile).getChannel();
      destination.transferFrom(source, 0, source.size());
     }
     finally {
      if(source != null) {
       source.close();
      }
      if(destination != null) {
       destination.close();
      }
}}

我通过使用函数发送

File source = new File(text.getText());         
    String url ="G:\\myImage";
    File dest = new File(url);
try {
    copyFile(source, dest);
    } catch (IOException e1) {
    e1.printStackTrace();
    }
    }

我收到错误消息

java.io.FileNotFoundException: G:\myImage (Access is denied)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.<init>(Unknown Source)
    at java.io.FileOutputStream.<init>(Unknown Source)

这可能是什么原因?我正在使用Windows 7

1 个答案:

答案 0 :(得分:2)

您正在使用目录名作为错误来源的目标。

您可以通过

将源文件名添加到目的地来轻松解决此问题
File source = new File(text.getText());         
String url ="G:\\myImage";
File dest = new File(url, source.getName() );