File is used frequently in Java IO, and is used in uploading and deleting files. For example, when we write to the management system, we may use uploading and deleting pictures. Then we will use Java File to handle it.
Basic use of File in Java creates and deletes files:
public class FileDemo { public static void main(String[] args) { File f=new File("d:"+File.separator+"io.txt"); //File.separator gets "/" //File.pathSeparator gets ";" try { f.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // etc. for a while, you can view the file generation try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(f.exists()){ f.delete(); }else{ System.out.println("File does not exist"); } }} Java File example usage: Image upload function code used in J2EE development:
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("Please select the file and upload it"); 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("File upload failed, please try again!!"); out.flush(); } } } out.print(fileNewName); out.flush(); } And the code generated by the folder is as follows:
File f1=new File("d:"+File.separator+"test"); f1.mkdir(); //Method to get the folder name f1.getName();This is the basic use in Java IO and is also the part that is used more frequently.
The above is all about this article, I hope it will be helpful to everyone's learning.