Common JSP file operations and jsp operations
This example summarizes common JSP file operations. Share it with you for your reference. The details are as follows:
FILE Operations in JSP: FILE class
String path = request. getRealPath ("/"); // pass the parameter "/" to return the web application root directory String tmp_path = path + "tmp"; File f1 = new File (tmp_path ); // create a FILE class and specify the path tmp_pathf1.mkdir (); // create the directory File f2 = new File (tmp_path, "a.txt"); // create a FILE class, specify the path to // tmp_path + "a.txt" f2.createNewFile (); // create the File f3 = new File (tmp_path, "B .txt") specified by f2; f3.createNewFile (); file f4 = new File (tmp_path, "B .txt"); f4.createNewFile ();
Where:
The length () method of the File object can calculate the File size.
The isFile () method can be used to determine whether a file is used.
The isDirectory () method can be used to determine whether a folder is used.
GetName () to get the name of the file folder
Whether canRead () is readable
CanWrite () is writable?
Whether isHidden () is hidden
LastModified () returns an object of the Date class
File Reading
Example 1:
String path = request. getRealPath ("/"); File fp = new File (path, "file1.txt"); // define a File FileInputStream fistream = new FileInputStream (fp ); // define a file input stream to bind a file byte buf [] = new byte [10000]; int bytesum = fistream. read (buf,) // write the byte file to the buf array and return the number of bytes written. String str_file = new String (buf, 0, bytesum); out. println (str_file); fistream. close ();
Example 2:
String path=request.getRealPath("/");File fp=new File(path,"file1.txt");FileReader freader=new FileReader(fp):BufferedReader bfdreader=new BufferedReader(freader);String str_line=bfdreader.readLine();while(str_line!=null){ out.println(str_line); out.println("<br>"); str_line=bfdreader.readLine(); } bfdreader.close(); freader.close();
File writing:
Example 1:
String path = request. getRealPath ("/"); File fp = new File (path, "file2.txt"); FileWriter fwriter = new FileWriter (fp); request. setCharacterEncoding ("GBK"); // set the character encoding String str_file = request. getParameter ("textarea"); fwriter. write (str_file); fwriter. close ();
Example 2:
String path=request.getRealPath("/");File fp=new FIle(path,"file2.txt");FileWriter fwriter=new FIleWriter(fp);BufferedWriter bfwriter=new BufferedWriter(fwriter);request.setCharacterEncoding("GBK");String str_file=request.getParameter("textarea");bfwriter.write(str_file,0,str_file.length());bfwriter.flush();bfwriter.close();
I hope this article will help you with JSP program design.