Home>

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, specifying the path as tmp_path
f1.mkdir ();//Create a directory
file f2=new file (tmp_path, "a.txt");//Create a file class, specifying the path as //tmp_path+"a.txt "
f2.createnewfile ();//Create the file specified by f2
file f3=new file (tmp_path, "b.txt");
f3.createnewfile ();
file f4=new file (tmp_path, "b.txt");
f4.createnewfile ();

among them:

The length () method of the file object can calculate the size of the file

isfile () method can determine whether it is a file

isdirectory () method can determine whether it is a folder

getname () can get the name of the file folder

canread () is readable

canwrite () is writable

Whether ishidden () is hidden

lastmodified () last modified date,Returns an object of the date class

Reading of files

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, 0,10000) //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 ();

Writing of files:

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 ();
jsp
  • Previous Detailed explanation of SQL Server2014 hash index principle
  • Next Android implementation of immersive status bar