The example of this article summarizes the common file operation of JSP. Share to everyone for your reference. Specifically as follows:
File actions in JSP: Files class
String Path=request.getrealpath ("/"),//pass parameter "/" can return the Web application root
String tmp_path=path+ "tmp";
File F1=new file (tmp_path);//Create the file class, specify the path to Tmp_path
F1.mkdir ();//Create directory
file F2=new file (Tmp_path, "a.txt"); Creates a file class that specifies that the path is//tmp_path+ "A.txt"
f2.createnewfile ();//Creates a f2-specified file, filename
f3=new file (Tmp_path, "b.txt");
F3.createnewfile ();
File F4=new file (Tmp_path, "b.txt");
F4.createnewfile ();
which
The length () method of the file object can calculate the size of the files
The Isfile () method can be used to determine whether a file
The Isdirectory () method can determine whether a folder
GetName () can get the name of the file folder
CanRead () is readable
Whether the CanWrite () can be written
Ishidden () is hidden
LastModified () Last modified date, returns an object of the date class
Read the file
Example 1:
String Path=request.getrealpath ("/");
File Fp=new file (path, "file1.txt");//define a document
FileInputStream fistream=new fileinputstream (FP);//define a document input stream bind a file
byte buf[]=new byte[10000];
int Bytesum=fistream.read (buf,0,10000)//writes the byte file to the BUF 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 ();
Write to File:
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 this article will help you with the JSP program design.