我试图让用户将我的 servlet 中的数据保存为 CSV 文件。最初我只是在他们的桌面上放置文件,但这条路线的权限会被拒绝,所以我想问用户他们想把它保存在哪里。
从我所见,我不能在 servlet 中使用 Swing API,因为 Tomcat 不知道如何绘制 GUI。我试过这段代码:
String fileName = "ClassMonitor" + formatter.format(currentDate) + ".csv";
File csvFile = new File(fileName);
//Attempt to write as a CSV file
try{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setSelectedFile(csvFile);
int returnValue = fileChooser.showSaveDialog(null);
if(returnValue == JFileChooser.APPROVE_OPTION)
{
BufferedWriter out = new BufferedWriter(new FileWriter(csvFile));
//Iterates and writes to file
for(ClassInfo classes : csvWrite)
{
//Check if the class has a comma. Currently, only section titles have a comma in them, so that's all we check for.
classes.setSectionTitle(replaceComma(classes.getSectionTitle()));
out.write(classes.toString());
}
//Close the connection
out.close();
}
//Log the process as successful.
logger.info("File was successfully written as a CSV file to the desktop at " + new Date() + "\nFilename" +
"stored as " + fileName + ".");
}
catch(FileNotFoundException ex)
{
//Note the exception
logger.error("ERROR: I/O exception has occurred when an attempt was made to write results as a CSV file at " + new Date());
}
catch(IOException ex)
{
//Note the exception
logger.error("ERROR: Permission was denied to desktop. FileNotFoundException thrown.");
}
catch(Exception ex)
{
//Note the exception
logger.error("ERROR: Save file was not successfull. Ex: " + ex.getMessage());
}
}
但这会抛出一个无头异常。
任何有关如何在 servlet 中实现诸如保存文件对话框之类的指导都将不胜感激。