如何优化使下列代码使其可以弹出选择文件位置对话框 向服务端传输文件 throws Exception public void sendFile throws Exception try File file = new FileE理论实训pptx; iffileexists
可以使用Java Swing提供的JFileChooser类来弹出选择文件位置对话框。具体实现如下:
- 导入Java Swing相关的包:
import javax.swing.JFileChooser; import javax.swing.filechooser.FileNameExtensionFilter;
- 修改代码中的文件路径为选择的文件路径:
// 原代码 File file = new File("E:\理论实训.pptx");
// 修改后的代码 JFileChooser fileChooser = new JFileChooser(); // 设置文件选择框的默认路径 fileChooser.setCurrentDirectory(new File(System.getProperty("user.home"))); // 设置文件类型过滤器,只显示PPTX文件 FileNameExtensionFilter filter = new FileNameExtensionFilter("PPTX Files", "pptx"); fileChooser.setFileFilter(filter); int result = fileChooser.showOpenDialog(null); if (result == JFileChooser.APPROVE_OPTION) { file = fileChooser.getSelectedFile(); }
- 完整代码如下:
import javax.swing.JFileChooser; import javax.swing.filechooser.FileNameExtensionFilter;
public class FileTransfer { private FileInputStream fis = null; private DataOutputStream dos = null; private Socket client = null;
public FileTransfer(Socket client) {
this.client = client;
}
/**
* 向服务端传输文件
* @throws Exception
*/
public void sendFile() throws Exception {
try {
JFileChooser fileChooser = new JFileChooser();
// 设置文件选择框的默认路径
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
// 设置文件类型过滤器,只显示PPTX文件
FileNameExtensionFilter filter = new FileNameExtensionFilter("PPTX Files", "pptx");
fileChooser.setFileFilter(filter);
int result = fileChooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (file.exists()) {
fis = new FileInputStream(file);
dos = new DataOutputStream(client.getOutputStream());
// 文件名和长度
dos.writeUTF(file.getName());
dos.flush();
dos.writeLong(file.length());
dos.flush();
// 传输文件内容
byte[] bytes = new byte[1024];
int length = 0;
while ((length = fis.read(bytes, 0, bytes.length)) != -1) {
dos.write(bytes, 0, length);
dos.flush();
}
}
}
} finally {
if (fis != null)
fis.close();
if (dos != null)
dos.close();
}
}
原文地址: http://www.cveoy.top/t/topic/flVw 著作权归作者所有。请勿转载和采集!