没怎么做过Swing方面的,对纯纯新手可能这程序能起到一点点启示作用吧...
--------------------------------------------------------------------------------------
CopyMp3类
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CopyMp3
{
public static void main(String[] args)
{
MainFrame frm = new MainFrame();
frm.setVisible(true);
}
}
class MainFrame extends JFrame
{
public MainFrame()
{
super("COPY");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300,160);
MainPanel pan = new MainPanel();
setContentPane(pan);
setLayout(null);
}
}
class MainPanel extends JPanel
{
JTextArea txtInFile;
JTextArea txtOutFile;
JFileChooser open;
String strFilePath;
String strFilePathCopyTo;
public MainPanel()
{
JLabel lblIn = new JLabel("源文件:");
lblIn.setBounds(30, 30, 50, 20);
txtInFile = new JTextArea();
txtInFile.setBounds(80,30,100,20);
JButton btnSelect = new JButton("选择文件");
btnSelect.setBounds(190, 30, 80, 20);
open = new JFileChooser();
btnSelect.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
open.showOpenDialog(null);
strFilePath = open.getSelectedFile().getPath();
((JButton)e.getSource()).setLabel("已选");
txtInFile.setText(strFilePath);
System.out.println(txtInFile.getText());
System.out.println("打开文件");
}
}
);
JLabel lblOut = new JLabel("复制到:");
lblOut.setBounds(30, 60, 50, 20);
txtOutFile = new JTextArea();
txtOutFile.setBounds(80,60,100,20);
JButton btnSelectCopyTo = new JButton("选择文件");
btnSelectCopyTo.setBounds(190, 60, 80, 20);
btnSelectCopyTo.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
open.showSaveDialog(null);
strFilePathCopyTo = open.getSelectedFile().getPath();
((JButton)e.getSource()).setLabel("已选");
txtOutFile.setText(strFilePathCopyTo);
System.out.println(txtOutFile.getText());
System.out.println("打开文件");
}
}
);
JButton btnCopy = new JButton("开始复制");
btnCopy.setBounds(60, 90, 90, 20);
btnCopy.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
strFilePath = txtInFile.getText();
strFilePathCopyTo = txtOutFile.getText();
System.out.println(strFilePath);
System.out.println(strFilePathCopyTo);
IOTest.copyFile(strFilePath, strFilePathCopyTo);
}
});
add(lblIn);
add(txtInFile);
add(btnSelect);
add(lblOut);
add(txtOutFile);
add(btnSelectCopyTo);
add(btnCopy);
}
}
IOTest类
import java.io.*;
import javax.swing.*;
public class IOTest
{
public static void copyFile(String in,String out)
{
FileInputStream fin = null;
FileOutputStream fout = null;
try
{
fin = new FileInputStream(new File(in));
fout = new FileOutputStream(new File(out));
byte[] b = new byte[512];
while(true)
{
if(fin.read(b)!=-1)
{
fout.write(b);
}
else
{
break;
}
}
System.out.println("成功将文件:" + in + "复制到:" + out);
JOptionPane.showMessageDialog(null, "文件已成功复制!");
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
fin.close();
fout.close();
}catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
}