本文執行個體總結了JSP常見的檔案操作。分享給大家供大家參考。具體如下:
JSP中的檔案操作:FILE類
String path=request.getRealPath("/");//傳遞參數"/"可以返回web應用根目錄String tmp_path=path+"tmp";File f1=new File(tmp_path);//建立FILE類,指定路徑為tmp_pathf1.mkdir();//建立目錄File f2=new File(tmp_path,"a.txt");//建立FILE類,指定路徑為//tmp_path+"a.txt"f2.createNewFile();//建立f2指定的檔案File f3=new File(tmp_path,"b.txt");f3.createNewFile();File f4=new File(tmp_path,"b.txt");f4.createNewFile();
其中:
File對象的length()方法可以計算檔案的大小
isFile()方法可以判斷是否為檔案
isDirectory()方法可以判斷是否為檔案夾
getName()可以得到檔案檔案夾的名字
canRead()是否可讀
canWrite()是否可寫
isHidden()是否隱藏
lastModified()最後修改日期,返回Date類的一個對象
檔案的讀取
樣本1:
String path=request.getRealPath("/");File fp=new File(path,"file1.txt");//定義一個檔案FileInputStream fistream=new FileInputStream(fp);//定義一個檔案輸入資料流綁定一個檔案byte buf[]=new byte[10000];int bytesum=fistream.read(buf,0,10000)//把位元組檔案寫入到buf數組中,返回寫入的位元組數String str_file=new String(buf,0,bytesum);out.println(str_file);fistream.close();
樣本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();
檔案的寫入:
樣本1:
String path=request.getRealPath("/");File fp=new File(path,"file2.txt");FileWriter fwriter=new FileWriter(fp);request.setCharacterEncoding("GBK");//設定字元編碼String str_file=request.getParameter("textarea");fwriter.write(str_file);fwriter.close();
樣本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程式設計有所協助。