java File類的基本使用方法總結_java

來源:互聯網
上載者:User

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中的基礎使用,也是使用比較頻繁的部分。

以上就是本文的全部內容,希望對大家的學習有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.