簡體   English   中英

JFileChooser和復制文件

[英]JFileChooser and copying files

我正在上課作業,並且有幾個問題希望得到幫助。 分配是一個GUI,允許用戶選擇要復制的文件並選擇要將文件復制到的位置。

我已經完成任務,但有幾件事我想看看我是否可以改變...

當選擇源文件時,我只希望源文件的名稱顯示在標簽中,但是,該程序需要整個路徑才能復制文件,並且每次我嘗試切換它以僅顯示文件名時程序將無法運行,因為它不知道文件的位置。 第二個問題,是否仍然要使程序自動將文件復制為.bak文件...說源文件是文本文件,用戶選擇目標文件夾並點擊復制,然后保存一個同名文件,但是.bak擴展名?

我將有問題的代碼放在***之間,並留下了我試圖用來僅顯示文件名的代碼並注釋掉了。 謝謝你的幫助!!

public class CopyFile extends JFrame{

private JFileChooser fc;
private JButton copyButton;
private JButton chooseFileButton;
private JButton destinationButton;
private File workingDirectory;
private JLabel sourceLabel;
private JLabel destinationLabel;
private JTextField sourceText;
private JTextField sourceFileText;
private JTextField destinationText;

public static void main(String [] args) {
    CopyFile go = new CopyFile();
    go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    go.setSize(500, 150);
    go.setVisible(true);
}

public CopyFile() {
    super("Copy a text file");
    setLayout(new GridLayout(3, 3, 5, 5));
    fc = new JFileChooser();

    //Open dialog box inside project folder to make easier to find files
    workingDirectory = new File(System.getProperty("user.dir"));
    fc.setCurrentDirectory(workingDirectory);
    //create labels and buttons for window
    chooseFileButton = new JButton("CHOOSE SOURCE FILE");
    destinationButton = new JButton("DESTINATION FOLDER");
    copyButton = new JButton("COPY FILE");      
    sourceLabel = new JLabel("SOURCE FILE: ");
    sourceText = new JTextField(10);
    sourceText.setEditable(false);
    destinationLabel = new JLabel("DESTINATION: ");
    destinationText = new JTextField(10);

    //add everything to JFrame  
    add(sourceLabel);
    add(sourceText);
    add(chooseFileButton);  
    add(destinationLabel);
    add(destinationText);
    add(destinationButton);
    add(copyButton);

    //Create TheHandler object to add action listeners for the buttons.
    TheHandler handler = new TheHandler();
    chooseFileButton.addActionListener(handler);
    destinationButton.addActionListener(handler);
    copyButton.addActionListener(handler);
}

//Inner class to create action listeners    
private class TheHandler implements ActionListener {
    public void actionPerformed(ActionEvent event) {
        int returnVal;
        String selectedFilePath;
        File selectedFile;

******************************************************************************      
        //Selecting a source file and displaying what the user is doing.
        if(event.getSource() == chooseFileButton) {     
            returnVal = fc.showOpenDialog(null);
            //Set the path for the source file. 
            if(returnVal == JFileChooser.APPROVE_OPTION) {  

  /*The two next lines of code are what I was trying to do to get only the
  file name but I get a whole page of errors, mainly I think it's saying no 
  such file exists*/
                //selectedFile = fc.getSelectedFile();
                //sourceText.setText(selectedFile.getName());   
                selectedFilePath = fc.getSelectedFile().getAbsolutePath();
                sourceText.setText(selectedFilePath);
            }       
        }//end if

******************************************************************************          
        //Handle destination button.
        if(event.getSource() == destinationButton) {
            returnVal = fc.showSaveDialog(null);
            if(returnVal == JFileChooser.APPROVE_OPTION) {
                 selectedFilePath = fc.getSelectedFile().getAbsolutePath();
                destinationText.setText(selectedFilePath);
            }               
        }//end if

        //Handle copy button
        if(event.getSource() == copyButton) {
            File sourceFile = new File(sourceText.getText());
            File destinationFile = new File(destinationText.getText());
            Path sourcePath = sourceFile.toPath();
            Path destinationPath = destinationFile.toPath();        
            try {
                Files.copy(sourcePath,  destinationPath);
            } catch (IOException e) {
                e.printStackTrace();
            }   
        }//end if

    }//end actionPerformed      
}//end TheHandler class
}//end class

當選擇源文件時,我只希望源文件的名稱顯示在標簽中,但是,該程序需要整個路徑才能復制文件,並且每次我嘗試切換它以僅顯示文件名時程序將無法運行,因為它不知道文件的位置。

您可以使用File#getName ,它將返回文件名並將其用作標簽的文本,但保留對原始File的引用。 您不應該使用標簽的文本來生成新的File引用,而只需保留對源File和目標File以及實例字段的引用

第二個問題,是否仍然要使程序自動將文件復制為.bak文件...說源文件是文本文件,用戶選擇目標文件夾並點擊復制,然后保存一個同名文件,但是.bak擴展名?

String name = selectedFile.getName();
name = name.substring(0, name.lastIndexOf("."));
name += ".bak";
File destinationFile = new File(destinationPath, name);

會將selectedFile的擴展名更改為.bak ,但是您可能應該添加檢查以查看其是否以擴展名開頭

您必須將文件路徑和目標文件路徑保留為File ,而不是String 如下修改TheHandler類的代碼。

  1. 添加selectedSourceFileselectedDestinationFile本地字段。

     private class TheHandler implements ActionListener { private File selectedSourceFile; private File selectedDestinationFile; 
  2. 選擇文件時更新它們,並設置文件名而不是文本字段的路徑。

源文件按鈕

        if (event.getSource() == chooseFileButton) {
            returnVal = fc.showOpenDialog(null);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                selectedSourceFile = fc.getSelectedFile();
                sourceText.setText(selectedSourceFile.getName());
            }
        }

目標按鈕

        if (event.getSource() == destinationButton) {
            returnVal = fc.showSaveDialog(null);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                selectedDestinationFile = fc.getSelectedFile();
                destinationText.setText(selectedDestinationFile.getName());
            }
        }
  1. 復制它們時,請使用selectedSourceFileselectedDestinationFile

      if (event.getSource() == copyButton) { Path sourcePath = selectedSourceFile.toPath(); Path destinationPath = selectedDestinationFile.toPath(); try { Files.copy(sourcePath, destinationPath); } catch (IOException e) { e.printStackTrace(); } } 

現在,您已經完成了第一個要求。 您可以在選擇目標文件時制作backfile。 因此,在選擇目標按鈕時,添加您的代碼以制作備份文件。

        if (event.getSource() == destinationButton) {
            returnVal = fc.showSaveDialog(null);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                selectedDestinationFile = fc.getSelectedFile();
                destinationText.setText(selectedDestinationFile.getName());

                //copy backup
                String name = selectedSourceFile.getName();
                name = selectedSourceFile.getName().substring(0, name.lastIndexOf(".")) + ".bak";
                File destinationFile = new File(selectedDestinationFile.getParentFile(), name);
                try {
                    Files.copy(selectedSourceFile.toPath(), destinationFile.toPath());
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }

暫無
暫無

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

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