在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

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

2016-7-29 15:37| 发布者: zhangjf| 查看: 760| 评论: 0

摘要: Java IO中File的使用是比较频繁的,在文件的上传和删除中都会用到的。比如我们在写管理系统的时候有可能会用到图片的上传,和删除。那么我们就会用到Java的 File来处理。 Java中File的基本使用创建和删除文件: pub ...

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

Java中File的基本使用创建和删除文件:

  1. public class FileDemo {
  2. public static void main(String[] args) {
  3. File f=new File("d:"+File.separator+"io.txt");
  4. //File.separator 得到“”
  5. //File.pathSeparator得到是“;”
  6. try {
  7. f.createNewFile();
  8. } catch (IOException e) {
  9. // TODO Auto-generated catch block
  10. e.printStackTrace();
  11. }
  12. //等等一段时间,可以查看文件的生成
  13. try {
  14. Thread.sleep(3000);
  15. } catch (InterruptedException e) {
  16. // TODO Auto-generated catch block
  17. e.printStackTrace();
  18. }
  19. if(f.exists()){
  20. f.delete();
  21. }else{
  22. System.out.println("文件不存在");
  23. }
  24. }
  25. }
复制代码

Java File示例使用:在J2EE开发中使用的图片上传功能代码:

  1. public void fileUpload(@RequestParam MultipartFile[] myfiles,
  2. HttpServletRequest request, HttpServletResponse response)
  3. throws IOException {
  4. String imgPath = "/uploads" + "/";
  5. File directory = new File(request.getSession().getServletContext()
  6. .getRealPath("/")
  7. + imgPath);
  8. String desFileName = null;
  9. String fileNewName = null;
  10. response.setContentType("text/html; charset=UTF-8");
  11. PrintWriter out = response.getWriter();
  12. String originalFilename = null;
  13. for (MultipartFile myfile : myfiles) {
  14. if (myfile.isEmpty()) {
  15. out.write("请选择文件后上传");
  16. out.flush();
  17. } else {
  18. originalFilename = myfile.getOriginalFilename();
  19. if (null != originalFilename && originalFilename.length() > 0) {
  20. fileNewName = UUID.randomUUID() + originalFilename;
  21. desFileName = directory.toString() + "/" + fileNewName;
  22. }
  23. try {
  24. FileUtils.copyInputStreamToFile(myfile.getInputStream(),
  25. new File(desFileName));
  26. } catch (IOException e) {
  27. e.printStackTrace();
  28. out.write("文件上传失败,请重试!!");
  29. out.flush();
  30. }
  31. }
  32. }
  33. out.print(fileNewName);
  34. out.flush();
  35. }
复制代码

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

  1. File f1=new File("d:"+File.separator+"test");
  2. f1.mkdir();
  3. //获取文件夹名称的方法
  4. f1.getName();
复制代码

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

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

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-5-6 19:00

Copyright 2015-2025 djqfx

返回顶部