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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

  2021-03-22 我要评论
想了解java File类的基本使用方法总结的相关内容吗,在本文为您仔细讲解java File类的基本使用的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:java,File类,下面大家一起来学习吧。

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中的基础使用,也是使用比较频繁的部分。

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

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们