簡體   English   中英

將文件從JFileChooser復制到新目錄

[英]Copy file from JFileChooser to new directory

好的,我不確定這為什么行不通,但是我嘗試使用JFileChooser選擇源文件(C,C ++,Java),然后將其復制到項目的工作區中。 當我運行它時,它會選擇我選擇好的文件,它會將我的工作區識別為目標,但是由於某種原因,它不會復制該文件。

        JButton btnSelectFile = new JButton("Select File");
    btnSelectFile.addMouseListener(new MouseAdapter(){
        public void mouseClicked(MouseEvent e){
            JFileChooser FileChooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("C, C++ or Java Files", "c", "cpp", "java");
            FileChooser.setFileFilter(filter);
            int returnValue = FileChooser.showOpenDialog(null);
            if (returnValue == JFileChooser.APPROVE_OPTION){
                selectedFile = FileChooser.getSelectedFile();
                filePath = selectedFile.getAbsolutePath();
                InputStream inStream = null;
                OutputStream outStream = null;
                try{
                    File source =new File(filePath);
                    File dest =new File(System.getProperty("user.dir") + selectedFile.getName());
                    inStream = new FileInputStream(source);
                    outStream = new FileOutputStream(dest);

                    byte[] buffer = new byte[1024];

                    int length;
                    while ((length = inStream.read(buffer)) > 0){
                        outStream.write(buffer, 0, length);
                    }

                    if (inStream != null)inStream.close();
                    if (outStream != null)outStream.close();
                    System.out.println("File Copied..");
                }catch(IOException e1){
                    e1.printStackTrace();
                }
                textArea.setText("File Loaded: " + selectedFile.getName() + "\n\n\n" + "Hit 'Run Code'");
            }
            else System.out.println("Failed to Load");
                //UnitXMLReader.ChosenFile = filePath;

        }
    });

創建目標File時使用以下內容

File dest =new File(System.getProperty("user.dir"), selectedFile.getName());

代替這個

File dest =new File(System.getProperty("user.dir") + selectedFile.getName());


假設System.getProperty("user.dir")返回C:\\Users\\Me\\WorkspaceselectedFile.getName()返回myfile.cpp
然后,在您的情況下,dest表示C:\\Users\\Me\\Workspacemyfile.cpp而不是C:\\Users\\Me\\Workspace\\myfile.cpp

告訴我是否仍然不清楚。

對於“文件目標”,而不是將兩者相加,請嘗試用逗號分隔它們。

將dest作為附加版本和逗號進行sysout,以查看為什么這樣做會有問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM