gpt4 book ai didi

java - 创建一个文件,然后在java中删除

转载 作者:行者123 更新时间:2023-11-29 03:54:34 24 4
gpt4 key购买 nike

我的要求是有一个导出按钮,点击数据库中的数据被加载然后转换成一个.csv,.doc或.html文件,可以在这里打开或保存,这个需要转换成file ,将其保存在本地路径并上传到SFTP服务器并从loacl路径中删除。我的代码是这样的......

public String a(String tableName, String format,String jsondataAsString,String jsonKeyName,String userName,
String password, String hostName,String remotePath) throws IOException{
userName="a";
password="a";
hostName="10.100.10.100";
remotePath="/tmp";
System.out.println("TableName-->" +tableName);
System.out.println("Format-->" +format);
System.out.println("JsonData-->" +jsondataAsString);
System.out.println("userName-->" +userName);
System.out.println("password-->" +password);
System.out.println("hostname-->" +hostName);
System.out.println("RemotePath-->" +remotePath);
String mimeType = null;
String fileName = null;
String seperator = null;
String lineSeperator = null;
boolean isFileTransferComplete=true;
OutputStream f1 =null;

if (format.equalsIgnoreCase("CSV")) {
fileName = tableName + ".csv";
mimeType = "application/CSV";
seperator = ",";
lineSeperator = "\n";



} else if (format.equalsIgnoreCase("Word")) {
fileName = tableName + ".doc";
mimeType = "application/msword";
seperator = " ";
lineSeperator = "\n\n";
} else {

fileName = tableName + ".html";
mimeType = "application/html";
seperator = "  ";
lineSeperator = "<br><br>";
}
String localfilePath="D:/aaa/" +fileName;
String error="";
try{
String data = convertJsonToString(jsondataAsString, seperator, jsonKeyName,lineSeperator,format);
if (data == null || data.length() == 0) {
data = "[BLANK]";
}
boolean isFileTobeDeleted=true;
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
System.out.println("Buffer-->" +buffer);

buffer.flush();
buffer.write(data.getBytes());

f1 = new FileOutputStream(localfilePath);
buffer.writeTo(f1);

isFileTransferComplete = new SFTPHandler(hostName,
PicoEmsGuiConstants.SFTP_Port, userName, password)
.uploadFile(remotePath,localfilePath);
System.out.println("FileTransfer" +isFileTransferComplete);

File target = new File(localfilePath);

target.delete();


}
System.out.println("isFileTobeDeleted" +isFileTobeDeleted);



}catch(Exception e){
System.out.println("Exception :::>" +e.getMessage());

}finally{
f1.close();
}

return isFileTransferComplete+"--"+ remotePath;

}

我能够创建文件,但在上传完成后无法从 loacl 路径中删除...任何人都可以告诉我哪里错了

最佳答案

您不必关闭流然后尝试删除它吗?

finally {
f1.close();
if(file != null && file.exists()) {
file.delete();
}
}

关于java - 创建一个文件,然后在java中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7091074/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com