【发布时间】:2010-11-02 21:13:22
【问题描述】:
private static final String DESTINATION_DIR_PATH ="/files";
private File destinationDir;
public void init(ServletConfig config) throws ServletException {
super.init(config);
String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
destinationDir = new File(realPath);
if(!destinationDir.isDirectory()) {
throw new ServletException(DESTINATION_DIR_PATH+" is not a directory");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println();
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory ();
fileItemFactory.setSizeThreshold(1*1024*1024);
//fileItemFactory.setRepository(tmpDir);
ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
try {
List items = uploadHandler.parseRequest(request);
Iterator itr = items.iterator();
while(itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if(item.isFormField()) {
out.println("File Name = "+item.getFieldName()+", Value = "+item.getString());
} else {
File file = new File(destinationDir,item.getName());
item.write(file);
String fileToBeRead = "C:/ProgramFiles/Apache/Tomcat/webapps/Readcsv/files/"+item.getName();
try {
BufferedReader br = new BufferedReader(new FileReader(fileToBeRead));..... and the code goes on..
我正在使用上面的代码来读取通过 JSP 表单上传的 .csv 文件。 代码工作得很好。 但我希望代码采用通用格式,因为上述代码仅适用于 Windows 系统,不适用于 UNIX 或任何其他操作系统。
String fileToBeRead = "C:/ProgramFiles/Apache/Tomcat/webapps/Readcsv/files/"+item.getName();
必须更改此特定行以完成任务。请让我知道可以做什么,以便代码在它遍历的任何操作系统中都能正常工作。另外请指出上述代码中需要更改的所有区域。
【问题讨论】:
-
这段代码的格式非常糟糕,难以阅读。打开 IDE 的格式化程序怎么样?
-
抱歉,我没有使用任何 IDE。但是要集中的区域是代码的前两行以及我在位置上单独提到的那一行。
标签: java jsp servlets filepath