java图形用户界面的选择一个文件并复制(另存为)的代码,麻烦了。

想要实现下图那个界面,按下“打开”按钮可以弹出文件选择对话框,选择一个文件并在文本框中显示路径和文件名,也可以通过在文本框中手动输入路径和文件名来读取这个文件。按下“浏览”按钮选择保存目录并显示在文本框中,也可以手动输入。按下“另存为”按钮把这个文件复制到保存目录中。若原文件不存在则弹出提示框,若保存目录不存在则创建目录。

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.awt.Font;

import javax.swing.JTextField;
import javax.swing.JButton;

import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

import javax.swing.JFileChooser;

public class CopyFile {

private JFrame frame;
private JTextField textField;
private JTextField textField_1;
private JFileChooser chooser;
private String readPath;
private String writePath;

/**
 * Launch the application.
 */
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CopyFile window = new CopyFile();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
 * Create the application.
 */
public CopyFile() {
initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 545, 277);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);

JLabel label = new JLabel("\u6587\u4EF6\uFF1A");
label.setFont(new Font("黑体", Font.BOLD, 18));
label.setBounds(26, 68, 57, 25);
frame.getContentPane().add(label);

JLabel lblNewLabel = new JLabel("\u4FDD\u5B58\u76EE\u5F55\uFF1A");
lblNewLabel.setFont(new Font("黑体", Font.BOLD, 18));
lblNewLabel.setBounds(10, 119, 95, 25);
frame.getContentPane().add(lblNewLabel);

textField = new JTextField();
textField.setBounds(105, 68, 299, 25);
frame.getContentPane().add(textField);
textField.setColumns(10);

textField_1 = new JTextField();
textField_1.setBounds(105, 121, 299, 25);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);

chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);// 设置选择模式,既可以选择文件又可以选择文件夹

JButton button = new JButton("\u6253\u5F00");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int index = chooser.showOpenDialog(null);
chooser.setDialogType(JFileChooser.OPEN_DIALOG);
chooser.setMultiSelectionEnabled(false);
chooser.setAcceptAllFileFilterUsed(false);
if (index == JFileChooser.APPROVE_OPTION) {
// 把获取到的文件的绝对路径显示在文本编辑框中
textField.setText(chooser.getSelectedFile()
.getAbsolutePath());
readPath = textField.getText();
}
}
});
button.setFont(new Font("黑体", Font.BOLD, 18));
button.setBounds(432, 67, 87, 26);
frame.getContentPane().add(button);

JButton button_1 = new JButton("\u6D4F\u89C8");
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int index = chooser.showSaveDialog(null);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
chooser.setMultiSelectionEnabled(false);
chooser.setAcceptAllFileFilterUsed(false);
if (index == JFileChooser.APPROVE_OPTION) {
// 把获取到的文件的绝对路径显示在文本编辑框中
textField_1.setText(chooser.getSelectedFile()
.getAbsolutePath());
writePath = textField_1.getText() + "\\";
}
}
});
button_1.setFont(new Font("黑体", Font.BOLD, 18));
button_1.setBounds(432, 118, 87, 26);
frame.getContentPane().add(button_1);

JButton button_2 = new JButton("\u53E6\u5B58\u4E3A");
button_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
readPath = textField.getText();
writePath = textField_1.getText() + "\\";
if(copyFile(readPath, writePath)== -1){//原文件不存在
JOptionPane.showMessageDialog(null, "源文件不存在", "警告", JOptionPane.ERROR_MESSAGE);
}
}
});
button_2.setForeground(Color.RED);
button_2.setFont(new Font("黑体", Font.BOLD, 18));
button_2.setBounds(213, 180, 93, 34);
frame.getContentPane().add(button_2);
}

/*
 * *
 * 复制单个文件
 * 
 * @param oldPath String 原文件路径 如:c:/fqf.txt
 * 
 * @param newPath String 复制后路径 如:f:/fgf.txt
 * 
 * @return int 0表示成功,-1表示原文件不存在,-2表示未知错误。
 */
public int copyFile(String oldPath, String newPath) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
if (oldfile.exists()) { // 文件存在时
InputStream inStream = new FileInputStream(oldPath); // 读入原文件
System.out.println(newPath);
if(isExist(newPath)){
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; // 字节数 文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
fs.close();
return 0;
}else{
return -2;
}
}
return -1;
} catch (Exception e) {
System.out.println("复制单个文件操作出错");
e.printStackTrace();
return -2;
}
}

public static boolean isExist(String filePath) {
String paths[] = filePath.split("\\\\");
String dir = paths[0];
for (int i = 0; i < paths.length - 2; i++) {// 注意此处循环的长度
try {
dir = dir + "/" + paths[i + 1];
File dirFile = new File(dir);
if (!dirFile.exists()) {
dirFile.mkdir();
System.out.println("创建目录为:" + dir);
}
} catch (Exception err) {
System.err.println("ELS - Chart : 文件夹创建发生异常");
}
}
File fp = new File(filePath);
if (!fp.exists()) {
return true; // 文件不存在,执行下载功能
} else {
return false; // 文件存在不做处理
}
}

}

 

追问

你好,请问文件选择对话框能不能用FileDialog来实现?怎么弄的?

追答

之前发给你的那个加密的程序就是FileDialog实现的,这个是用JFileChooser实现的。

你自己也稍微看看代码,这样自己也能学点东西,在FileEncrypter.java文件中实现的。

要改的话只要改button的ActionListener里的东西就好。

下图为我之前发你的程序FileDialog实现方法。


来自:求助得到的回答
温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-06-06
可以给JTextField t1 一个初始路径,那样,如果每次都是备份同一个文件直接点保存选路径就可以,如果想备份其他文件再选其他文件就可以了

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Calendar;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class BakTo extends JFrame implements ActionListener {
JLabel l1 = new JLabel("原始文件");
JTextField t1 = new JTextField(40);
JButton b1 = new JButton("选择");
JLabel l2 = new JLabel("保存目录");
JTextField t2 = new JTextField(40);
JButton b2 = new JButton("保存");
JFileChooser j1 = new JFileChooser();
JFileChooser j2 = new JFileChooser();
static File fileFlag = new File("");

public BakTo() {
setBounds(200, 200, 600, 140);
setLayout(new FlowLayout());
add(l1);
add(t1);
add(b1);
add(l2);
add(t2);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
setResizable(false);
setVisible(true);
validate();
}

public void actionPerformed(ActionEvent e) {
try {

if (e.getSource() == b1) {

int n = j1.showOpenDialog(null);
String filename = j1.getSelectedFile().toString();
if (n == JFileChooser.APPROVE_OPTION) {
t1.setText(filename);
fileFlag = new File(filename);
}

}

else if (e.getSource() == b2) {
j2.setCurrentDirectory(fileFlag);// 设置打开对话框的默认路径
j2.setSelectedFile(fileFlag);// 设置选中原来的文件
int n = j2.showSaveDialog(null);
String filename2 = j2.getSelectedFile().toString();
if(filename2.indexOf(".")!=-1){
filename2=filename2.substring(0,filename2.indexOf("."));
}

// 以下两句是获得原文件的扩展名
int flag = t1.getText().lastIndexOf(".");
String kuozhan = t1.getText().substring(flag);
String date = getDate();// 取得当前日期
if (n == JFileChooser.APPROVE_OPTION) {
t2.setText(filename2 +date+ kuozhan);// 把日期和扩展名添加到原来文件的后面
}

int b;
char[] t = new char[25];

// 这里我改用了文件流
FileInputStream input = new FileInputStream(t1.getText());

FileOutputStream output = new FileOutputStream(filename2+date
+ kuozhan);// 把扩展名添加到原来文件的后面

int in = input.read();
while (in != -1) {
output.write(in);
in = input.read();
}
input.close();
output.close();

}
} catch (Exception x) {
System.out.println(x);
}
}

public String getDate() {
Calendar rightNow = Calendar.getInstance();
System.out.println(rightNow.toString());
int year = rightNow.YEAR;
int date = rightNow.DATE;
int month = rightNow.MONTH + 1;
String d = year + "年" + month + "月" + date + "日";
return d;
}

public static void main(String args[]) {
BakTo c1 = new BakTo();
}

}本回答被网友采纳
相似回答