Summary of the basic usage of the java File class

  • 2020-05-09 18:34:57
  • OfStack

File is frequently used in Java IO, which can be used for uploading and deleting files. For example, when we write the management system, we may use the image upload and delete. So we're going to use File for Java.

Basic use of File in Java to create and delete files:


public class FileDemo {
 public static void main(String[] args) {
  
 File f=new File("d:"+File.separator+"io.txt");
 //File.separator  Get" \ " 
 //File.pathSeparator Get is" ; " 
 try {
  f.createNewFile();
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
 // , etc. 1 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 use: 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 folder generated code 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 and frequently used part of Java IO.

The above is the entire content of this article, I hope to help you with your study.


Related articles: