JSP file handling is used to handle file in server and manipulate file related task, e.g copying file to another file, upload images or any file to web server, delete existing file from server, creating new file in web server.
In this file handling we have to use input and output of java classes. This can be File, InputStream or with BufferedInputStream. Let take example to understand better.
Example Reading text file in JSP
fileRead.jsp
<%@ page language="java" import="java.io.*" errorPage="" %>
<html>
<head>
<title>File Handling in JSP</title>
</head>
<body>
<%
String fileName=getServletContext().getRealPath("jsp.txt");
File f=new File(fileName);
InputStream in = new FileInputStream(f);
BufferedInputStream bin = new BufferedInputStream(in);
DataInputStream din = new DataInputStream(bin);
while(din.available()>0)
{
out.print(din.readLine());
}
in.close();
bin.close();
din.close();
%>
</body>
</html>
Make a text file name jsp.txt and put in same folder where this jsp file is exists.
Create new file through JSP
createNewFile.jsp
<%@ page language="java" import="java.io.*" errorPage="" %>
<html>
<head>
<title>File Handling in JSP</title>
</head>
<body>
<%
String fileName=getServletContext().getRealPath("test.txt");
File f=new File(fileName);
f.createNewFile();
%>
</body>
</html>
Examples of Delete file in JSP
This example delete file from defined path.
deleteFile.jsp
<%@ page language="java" import="java.io.*" errorPage="" %>
<html>
<head>
<title>File Handling in JSP</title>
</head>
<body>
<%
String fileName=getServletContext().getRealPath("test.txt");
//// If you know path of the file, can directly put path instead of
///filename e.g c:/tomcat/webapps/jsp/myFile.txt
File f=new File(fileName);
boolean flag=f.delete();
///return type is boolean if deleted return true, otherwise false
%>
</body>
</html>
Can check file exists or not is directory, or file
Example of checking file type for existing, file or as directory
fileType.jsp
<%@ page language="java" import="java.io.*" errorPage="" %>
<html>
<head>
<title>File Handling in JSP</title>
</head>
<body>
<%
String fileName=getServletContext().getRealPath("jsp.txt");
File f=new File(fileName);
out.print("File exists : "+f.exists()+"<br>");
/// return type is boolean exists return true else false
out.print("File is Directory : "+f.isDirectory()+"<br>");
/// return type is boolean exists return true else false
out.print("File is File : "+f.isFile()+"<br>");
/// return type is boolean exists return true else false
out.print("File is creation Date : "+f.lastModified()+"<br>");
/// return type is boolean exists return true else false
%>
</body>
</html>
Example of Rename file in JSP
renameFile.jsp
<%@ page language="java" import="java.io.*" errorPage="" %>
<html>
<head>
<title>File Handling in JSP</title>
</head>
<body>
<%
String fileName=getServletContext().getRealPath("jsp.txt");
File f=new File(fileName);
boolean flag=f.renameTo(new File(getServletContext().getRealPath("myJsp.txt")));
%>
</body>
</html>
|