JSP中的文件操作:FILE类
String path=request.getRealPath("https://www.jb51.net/");//传递参数"https://www.jb51.net/"可以返回web应用根目录 String tmp_path=path+"tmp"; File f1=new File(tmp_path);//创建FILE类,指定路径为tmp_path f1.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("https://www.jb51.net/"); 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("https://www.jb51.net/"); 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("https://www.jb51.net/"); 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("https://www.jb51.net/"); 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();