Summary of common file operations for JSP

  • 2021-06-28 09:39:05
  • OfStack

This article summarizes common file operations for JSP with examples.Share it for your reference.Specifically as follows:

File operations in JSP: FILE class


String path=request.getRealPath("/");// Pass-through parameters "/" Can return web Apply Root Directory 
String tmp_path=path+"tmp";
File f1=new File(tmp_path);// Establish FILE class , Specify path as tmp_path
f1.mkdir();// Create directory 
File f2=new File(tmp_path,"a.txt");// Establish FILE class , Specify path as //tmp_path+"a.txt"
f2.createNewFile();// Establish f2 Specified file 
File f3=new File(tmp_path,"b.txt");
f3.createNewFile();
File f4=new File(tmp_path,"b.txt");
f4.createNewFile();

Where:

The length() method of the File object calculates the size of the file
The isFile() method can determine whether it is a file or not
The isDirectory() method can determine whether it is a folder or not
getName() gets the name of the file folder
Is canRead() readable
Is canWrite() Writable
Is isHidden() hidden
Last modified date of lastModified(), returns an object of class Date

Reading Files

Example 1:


String path=request.getRealPath("/");
File fp=new File(path,"file1.txt");// Definition 1 Files 
FileInputStream fistream=new FileInputStream(fp);// Definition 1 File input stream bindings 1 Files 
byte buf[]=new byte[10000];
int bytesum=fistream.read(buf,0,10000)// Write byte file to buf In array , Returns 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();

Writing files:

Example 1:


String path=request.getRealPath("/");
File fp=new File(path,"file2.txt");
FileWriter fwriter=new FileWriter(fp);
request.setCharacterEncoding("GBK");// Set 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 that the description in this paper will be helpful to everyone's JSP program design.


Related articles: