Java IO中File的使用是比較頻繁的,在文件的上傳和刪除中都會用到的。比如我們在寫管理系統(tǒng)的時候有可能會用到圖片的上傳,和刪除。那么我們就會用到Java的 File來處理。
Java中File的基本使用創(chuàng)建和刪除文件:
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開發(fā)中使用的圖片上傳功能代碼:
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中的基礎(chǔ)使用,也是使用比較頻繁的部分。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選