try { // smb://Administrator:Htl2010@192.168.71.13/pdf // 协议 帐号 密码@ IP地址 共享文件夹和路径 //ps:非加密共享文件夹 :smb://192.168.0.106/qwe/test.txt SmbFile sf = new SmbFile("smb://Administrator:Htl2010@192.168.71.13/pdf/FED/"+date+'/'+fpe.getTrackingNumber()+".pdf"); //if(!f.exists()){ f.createNewFile();} //从本地读取文件上传到服务主机中 //String URL_remote="smb://192.168.0.100/shareFile/uploadFile.txt"; File localfile=new File(filePath); InputStream ins = new FileInputStream(localfile); //SmbFile smbfile=new SmbFile(URL_remote); if(sf.exists()){ System.out.println("file is exists"); }else{ sf.connect(); OutputStream outs = new SmbFileOutputStream(sf); byte[] buffer = new byte[4096]; int len = 0; //读取长度 while ((len = ins.read(buffer, 0, buffer.length)) != -1) { outs.write(buffer, 0, len); } outs.flush(); //刷新缓冲的输出流 outs.close(); System.out.println("写入成功"); preAwbFedexNewService.saveFilePDF(p.getAgentNo(),hawbNo2,fpe.getTrackingNumber(),path); } ins.close(); } catch (Exception e) { e.printStackTrace(); }finally { } 代码优化
时间: 2023-12-10 16:40:00 浏览: 120
可以对代码进行以下优化:
1. 将所有的文件操作放在try语句块中,这样可以尽早地释放资源;
2. 使用try-with-resources语句块来自动处理资源关闭,不需要手动关闭输入输出流;
3. 对于文件是否存在的判断,可以使用SmbFile提供的方法isFile()或isDirectory()来判断;
4. 将一些常量定义为静态变量,可以提高代码的可读性。
修改后的代码如下:
```
private static final String SMB_PREFIX = "smb://";
private static final String SMB_USERNAME = "Administrator";
private static final String SMB_PASSWORD = "Htl2010";
private static final String SMB_IP_ADDRESS = "192.168.71.13";
private static final String SMB_SHARE_FOLDER = "/pdf/FED/";
try (InputStream ins = new FileInputStream(filePath)) {
SmbFile smbFile = new SmbFile(SMB_PREFIX + SMB_USERNAME + ":" + SMB_PASSWORD + "@" + SMB_IP_ADDRESS + SMB_SHARE_FOLDER + date + "/" + fpe.getTrackingNumber() + ".pdf");
if (smbFile.isFile()) {
System.out.println("File already exists.");
} else {
smbFile.connect();
try (OutputStream outs = new SmbFileOutputStream(smbFile)) {
byte[] buffer = new byte[4096];
int len = 0;
while ((len = ins.read(buffer)) != -1) {
outs.write(buffer, 0, len);
}
outs.flush();
System.out.println("Write file successfully.");
preAwbFedexNewService.saveFilePDF(p.getAgentNo(), hawbNo2, fpe.getTrackingNumber(), path);
}
}
} catch (Exception e) {
e.printStackTrace();
}
```
阅读全文