当前位置: 移动技术网 > IT编程>开发语言>Java > java File类的基本使用方法总结

java File类的基本使用方法总结

2019年07月22日  | 移动技术网IT编程  | 我要评论

java io中file的使用是比较频繁的,在文件的上传和删除中都会用到的。比如我们在写管理系统的时候有可能会用到图片的上传,和删除。那么我们就会用到java的 file来处理。

java中file的基本使用创建和删除文件:

public class filedemo {
 public static void main(string[] args) {
  
 file f=new file("d:"+file.separator+"io.txt");
 //file.separator 得到“\”
 //file.pathseparator得到是“;”
 try {
  f.createnewfile();
 } catch (ioexception e) {
  // todo auto-generated catch block
  e.printstacktrace();
 }
 //等等一段时间,可以查看文件的生成
 try {
  thread.sleep(3000);
 } catch (interruptedexception e) {
  // todo auto-generated catch block
  e.printstacktrace();
 }
 if(f.exists()){
  f.delete();
 }else{
  system.out.println("文件不存在");
 }
 }
}

java file示例使用:在j2ee开发中使用的图片上传功能代码:

 public void fileupload(@requestparam multipartfile[] myfiles,
 
  httpservletrequest request, httpservletresponse response)
 
  throws ioexception {
 
 string imgpath = "/uploads" + "/";
 
 file directory = new file(request.getsession().getservletcontext()
 
  .getrealpath("/")
 
  + imgpath);
 
 string desfilename = null;
 
 string filenewname = null;
 
 response.setcontenttype("text/html; charset=utf-8");
 
 printwriter out = response.getwriter();
 
 string originalfilename = null;
 
 for (multipartfile myfile : myfiles) {
 
  if (myfile.isempty()) {
 
  out.write("请选择文件后上传");
 
  out.flush();
 
  } else {
 
  originalfilename = myfile.getoriginalfilename();
 
  if (null != originalfilename && originalfilename.length() > 0) {
 
   filenewname = uuid.randomuuid() + originalfilename;
 
   desfilename = directory.tostring() + "/" + filenewname;
 
  }
 
  try {
 
   fileutils.copyinputstreamtofile(myfile.getinputstream(),
 
    new file(desfilename));
 
  } catch (ioexception e) {
 
   e.printstacktrace();
 
   out.write("文件上传失败,请重试!!");
 
   out.flush();
 
  }
 
  }
 
 }
 
 out.print(filenewname);
 
 out.flush();
 
 }

并且其中文件夹生成的代码如下:

 file f1=new file("d:"+file.separator+"test");
 
 f1.mkdir();
 
 //获取文件夹名称的方法
 f1.getname();

这是java io中的基础使用,也是使用比较频繁的部分。

以上就是本文的全部内容,希望对大家的学习有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网