当前位置:网站首页>Thread pool and singleton mode and file operation

Thread pool and singleton mode and file operation

2022-07-07 18:20:00 Luo Hanxiang

Link to the original text :

Keep learning Java100 Tiandi 024 God Thread pool and singleton mode and file operation

 

 

Thread pool and singleton mode and file operation

Learning goals

  • Producers and consumers

  • JDK5 characteristic JUC

  • The singleton pattern

  • keyword volatile

  • Thread pool

  • ConcurrentHashMap

Producer and consumer safety issues arise

When there are multiple producers or consumers , The previous producer and consumer model had security problems . The main causes are as follows :

  • The thread itself is a newly created method stack memory (CPU Come in and read the data )

  • Thread notify(), Wake up the first waiting thread , But there are many threads waiting at the beginning , Other threads that have fallen into wait before may not be able to wake up . The solution is to wake up all notifyAll().

  • Wake up thread , It's been done if Judge , Once you wake up, continue , But resources may not be available at this time . The solution is to wake up the thread , You can't do it right away , Judge the flag bit again , Utilization cycle .while( Sign a ) The sign is true, Never get out .

Define resource objects ,Resource.java

package com.zhangdapeng520.thread01_producer_consumer;

/**
*  Define resource objects 
*  member  :  A counter that produces goods 
*  Sign a 
*/
public class Resource {
   private int count;
   private boolean flag;

   //  Consumer calls 
   public synchronized void getCount() {
       // flag yes false, Consumption complete , Waiting for production 
       while (!flag)
           // Wait indefinitely 
           try {
               this.wait();
          } catch (Exception ex) {
          }
       System.out.println(" Consumption first " + count);

       //  Modify flag bit , Complete... For consumption 
       flag = false;

       //  Wake up the other thread 
       this.notifyAll();
  }

   //  Producer call 
   public synchronized void setCount() {
       // flag yes true, Production of complete , Waiting for consumption 
       while (flag)
           //  Wait indefinitely 
           try {
               this.wait();
          } catch (Exception ex) {
          }
       count++;
       System.out.println(" Production section " + count + " individual ");

       //  Modify flag bit , Complete... For production 
       flag = true;

       //  Wake up the other thread 
       this.notifyAll();
  }
}

Create a producer thread ,Produce.java

package com.zhangdapeng520.thread01_producer_consumer;

/**
*  Producer thread 
*    Variables in the resource object ++
*/
public class Produce implements Runnable{

   private Resource r ;

   public Produce(Resource r) {
       this.r = r;
  }

   @Override
   public void run() {
       while (true) {
           r.setCount();
      }
  }
}

Create consumer thread ,Customer.java

package com.zhangdapeng520.thread01_producer_consumer;

/**
*  Consumer thread 
*    The variable output in the resource object prints 
*/
public class Customer implements Runnable{
   private Resource r ;

   public Customer(Resource r) {
       this.r = r;
  }

   @Override
   public void run() {
       while (true) {
           r.getCount();
      }
  }
}

Create test class ,ThreadTest.java

package com.zhangdapeng520.thread01_producer_consumer;

public class ThreadTest {
   public static void main(String[] args) {
       Resource r = new Resource();

       //  Interface implementation class , The production of , The consumption of 
       Produce produce = new Produce(r);
       Customer customer = new Customer(r);

       //  Create thread 
       new Thread(produce).start();
       new Thread(produce).start();
       new Thread(produce).start();
       new Thread(produce).start();
       new Thread(produce).start();
       new Thread(produce).start();
       new Thread(customer).start();
       new Thread(customer).start();
       new Thread(customer).start();
       new Thread(customer).start();
       new Thread(customer).start();
       new Thread(customer).start();
  }
}

Thread method sleep and wait The difference between

sleep During hibernation , The synchronization lock will not be lost , Don't release .

wait() Waiting time , Ownership of the publishing monitor , Release the lock . After waking up, you need to re acquire the lock , To perform .

sleep and wait The difference is ,sleep It doesn't release the sync lock ,wait Will release the sync lock .

Producer and consumer case performance issues

wait() Methods and notify() Method , Local method call OS The function of , Interact with the operating system ,JVM look for OS, Stop the thread . Wait and wake up frequently , Lead to JVM and OS Too many interactions .

notifyAll() Wake up all threads , It also wastes thread resources , For a thread , All threads must not be awakened .

Lock The interface goes deep

Lock Interface replaces synchronization synchronized, Provides more flexibility , Better locking operation .

Lock Method in interface :  newCondition() The return value of the method is the interface : Condition.

Use Condition Interface , We can also make a thread stop or wake up , And there is no need to let JVM and OS Interaction , It can effectively solve the performance problems in the cases of producers and consumers .

Condition It is essentially a thread queue , We can create a producer thread queue for producers , Create a consumer generation queue for consumers . When producers finish producing resources , We call producerCondition.wait(), Let the producer thread queue enter the waiting state , And then call costomerCondition.signal() Inform consumers to queue up for consumption . conversely , When consumers consume resources , We call consumerCondition.wait() Let the consumer thread queue enter the waiting state , And then call producerCondition.signal() Let the producer thread queue production resources .

Equally important ,Condition Support and Lock Nesting uses , We can do it in one Lock Locked code block , Use Condition.

Producers and consumers improve to Lock Interface

Condition Interface ( Thread blocking queue )

  • The thread entering the queue , Release the lock

  • Threads out of the queue , Get the lock again

  • Interface method : await() Thread release lock , Enter the queue

  • Interface method : signal() Thread out of the queue , Acquire the lock again

Thread blocking queue , rely on Lock Interface to create

Create a resource class ,Resource.java

package com.zhangdapeng520.thread02_producer_consumer_condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
*  Improved to high performance Lock Blocking queues for interfaces and threads 
*/
public class Resource {
   private int count;
   private boolean flag;
   private final Lock lock = new ReentrantLock(); // Lock Interface implementation class object 

   //Lock Interface lock , Create 2 Blocking queue of threads 
   private final Condition producerCondition = lock.newCondition(); //  The producer thread blocks the queue 
   private final Condition customerCondition = lock.newCondition(); //  Consumer thread blocking queue 

   // Consumer calls 
   public void getCount() {
       lock.lock();// Get the lock 

       // flag yes false, Consumption complete , Waiting for production 
       while (!flag)
           //  Wait indefinitely , Consumer thread waiting , The thread that executes here , Release the lock , Enter the consumer's blocking queue 
           try {
               customerCondition.await();
          } catch (Exception ex) {
          }
       System.out.println(" Consumption first " + count);

       //  Modify flag bit , Complete... For consumption 
       flag = false;

       //  Wake up a in the production thread queue 
       producerCondition.signal();
       lock.unlock(); //  Release the lock 
  }

   // Producer call 
   public void setCount() {
       lock.lock();// Get the lock 
       // flag yes true, Production of complete , Waiting for consumption 
       while (flag)
           //  Wait indefinitely , Release the lock , Enter the production thread queue 
           try {
               producerCondition.await();
          } catch (Exception ex) {
          }
       count++;
       System.out.println(" Production section " + count + " individual ");

       //  Modify flag bit , Complete... For production 
       flag = true;

       //  Wake up the consumer thread to block a middle-aged in the queue 
       customerCondition.signal();
       lock.unlock(); //  Release the lock 
  }
}

Create producer class ,Producer.java

package com.zhangdapeng520.thread02_producer_consumer_condition;

/**
*  Producer thread 
*  Variables in the resource object ++
*/
public class Producer implements Runnable {
   private final Resource r;

   public Producer(Resource r) {
       this.r = r;
  }

   @Override
   public void run() {
       while (true) {
           r.setCount();
      }
  }
}

Create a consumer class ,Customer.java

package com.zhangdapeng520.thread02_producer_consumer_condition;

/**
*  Consumer thread 
*  The variable output in the resource object prints 
*/
public class Customer implements Runnable {
   private Resource r;

   public Customer(Resource r) {
       this.r = r;
  }

   @Override
   public void run() {
       while (true) {
           r.getCount();
      }
  }
}

Create test class ,ThreadTest.java

package com.zhangdapeng520.thread02_producer_consumer_condition;

public class ThreadTest {
   public static void main(String[] args) {
       Resource r = new Resource();

       //  Interface implementation class , The production of , The consumption of 
       Producer produce = new Producer(r);
       Customer customer = new Customer(r);

       //  Create thread 
       new Thread(produce).start();
       new Thread(produce).start();
       new Thread(produce).start();

       new Thread(customer).start();
       new Thread(customer).start();
       new Thread(customer).start();
  }
}

Lock How locks work

  Using technology is not open source , The name of the technology is called lightweight lock .

  It uses CAS lock (Compare And Swap) spinlocks .

 JDK Limit : When competing threads are greater than or equal to 10, Or a single thread spins more than 10 When the time

 JDK mandatory CAS Lock cancellation . Upgrade to heavyweight lock (OS lock CPU Communication bus with memory ).

Design patterns

Design patterns It's not technology , Is a former developer , In order to solve some problems, the experience of writing code .

The core technology of all design patterns , It's object-oriented .

Java The design patterns are 23 Kind of , It is divided into 3 Categories , Creation type , Behavior type , Functional .

The singleton pattern

Singleton mode is a way to create objects , The main goal is to ensure that only one object exists in memory . There are many ways to do this , Usually, multithreading is not considered . In multithreading , Considering the safety of threads , There is also a multithreaded version of singleton mode .

Implementation steps

  • Private modification construction method

  • Create your own objects

  • Method get, Return the object of this class

Sample code :

package com.zhangdapeng520.single01;

/**
* -  Private modification construction method 
* -  Create your own objects 
* -  Method get, Return the object of this class 
*/
public class Single {
   private Single() {
  }

   private static Single s = new Single(); //  Create your own objects 

   //  Method get, Return the object of this class 
   public static Single getInstance() {
       return s;
  }
}

Create a test code test :

package com.zhangdapeng520.single01;

public class Test {
   public static void main(String[] args) {
       // Static methods , obtain Single Class object 
       Single instance = Single.getInstance();
       System.out.println("instance = " + instance);

       instance = Single.getInstance();
       System.out.println("instance = " + instance);

       instance = Single.getInstance();
       System.out.println("instance = " + instance);

       instance = Single.getInstance();
       System.out.println("instance = " + instance);

       instance = Single.getInstance();
       System.out.println("instance = " + instance);
  }
}

Lazy security issues

A thread judges the variables s=null, Not implemented yet new object , Snatched by another thread CPU resources , At the same time there is 2 All threads judge variables , Object is created more than once .

That is, the most common thread safety in multithreading , When multiple threads operate on the same resource , It's easy to repeat . To solve thread safety problems , Use synchronized Key words can be used . It can be a synchronous method , It can also be synchronized code blocks .

Transform the singleton mode :Single.java

package com.zhangdapeng520.single02;

/**
* -  Private modification construction method 
* -  Create a member variable of this class ,  No new object 
* -  Method get, Return the object of this class 
*/
public class Single {
   private Single() {
  }

   private static volatile Single s = null;

   public static Single getInstance() {
       // Judge the variable again , Increase of efficiency 
       if (s == null) {
           synchronized (Single.class) {
               // Judgment variable s, yes null create 
               if (s == null) {
                   s = new Single();
              }
          }
      }
       return s;
  }

}

next , We create a test class to test :Test.java

package com.zhangdapeng520.single02;

public class Test {
   public static void main(String[] args) {
       // Static methods , obtain Single Class object 
       Single instance = Single.getInstance();
       System.out.println("instance = " + instance);

       instance = Single.getInstance();
       System.out.println("instance = " + instance);

       instance = Single.getInstance();
       System.out.println("instance = " + instance);

       instance = Single.getInstance();
       System.out.println("instance = " + instance);

       instance = Single.getInstance();
       System.out.println("instance = " + instance);
  }
}

Performance issues : The first thread gets the lock , Create objects , Returns the object . When the second thread calls the method , Variable s There are already objects , There's no need to synchronize at all , Don't judge empty , direct return Is the most efficient . Double if Judge , Increase of efficiency  Double Check Lock

private static volatile Single s = null; 
public static Single getInstance(){
        // Judge the variable again , Increase of efficiency 
        if(s == null) {
            synchronized (Single.class) {
                // Judgment variable s, yes null create 
                if (s == null) {
                    s = new Single();
                }
            }
        }
        return s;
    }

keyword volatile

  Member variable modifier , Can't decorate anything else .

Key role :

  • Ensure that the modified variable , Visibility in threads

  • Prevent instruction reordering

  • Singleton mode , Keyword used , Don't use keywords , Maybe the thread will get an object that has not been initialized yet ( Semi initialization ).

Example :MyRunnable.java

package com.zhangdapeng520.single03;

public class MyRunnable implements Runnable {
   private volatile boolean flag = true; // volatile Guarantee flag It's the only thing in the world 

   @Override
   public void run() {
       m();
  }

   private void m() {
       System.out.println(" Start execution ");
       while (flag) {

      }
       System.out.println(" End to perform ");
  }


   //  modify flag sign 
   public void setFlag(boolean flag) {
       this.flag = flag;
  }
}

Test class :VolatileTest.java

package com.zhangdapeng520.single03;

public class VolatileTest {
   public static void main(String[] args) throws InterruptedException {
       MyRunnable myRunnable = new MyRunnable();

       //  Thread start execution 
       new Thread(myRunnable).start();

       //  rest 2s
       Thread.sleep(2000);

       // main Threads modify variables 
       myRunnable.setFlag(false);
  }
}

Thread pool ThreadPool

Thread buffer pool , The purpose is to improve efficiency ..new Thread().start(), A thread is an independent method stack in memory ,JVM No ability to open up memory space , and OS Interaction .

JDK5 Start the built-in thread pool .

Executors class

Static methods static newFixedThreadPool(int Number of threads ), Return value of method ExecutorService Implementation class of interface , Manage the threads in the pool .

ExecutorService Interface method submit (Runnable r), Submit the task executed by the thread .

Callable Interface

Multithreaded program , The interface is characterized by a return value , You can throw an exception (Runnable No, ). There is only one abstract method call. Start thread , Thread call override method call.

ExecutorService Interface method

  • submit (Callable c) Submit the task executed by the thread

  • Future submit() Method after submitting the thread task , Method has a return value Future Interface type

  • Future Interface , Get the return value result after thread execution

Callable and Runnable Can implement multithreaded programs , The difference is ,Callable There is a return value ,Runnable no return value . Use Executors You can create thread pools , Thread pool can execute with Callable Implementation class of , It can also be executed Runnable Implementation class of .

Let's write an example to feel .

Create a thread class , Realization Runnable Interface .MyRunnable.java

package com.zhangdapeng520.thread03;

public class MyRunnable implements Runnable {
   @Override
   public void run() {
       System.out.println(Thread.currentThread().getName()+" Thread start ");
  }
}

Create a thread class , Realization Callable Interface .MyCallable.java

package com.zhangdapeng520.thread03;

import java.util.concurrent.Callable;

public class MyCall implements Callable<String> {
   public String call() throws Exception{
       return " Return string ";
  }
}

Create a test class , Creating a thread pool , Submit Callable Tasks and Runable Task to test .ThreadTest.java

package com.zhangdapeng520.thread03;

import java.util.concurrent.*;

public class ThreadTest {
   public static void main(String[] args) throws ExecutionException, InterruptedException {
       //  Creating a thread pool , The number of threads is 2 individual 
       ExecutorService es = Executors.newFixedThreadPool(2);

       //  Thread pool management object service, Call method submit Submit the task of the thread 
       MyRunnable my = new MyRunnable();

       //  Submit thread tasks , Use Callable Interface implementation class 
       Future<String> future = es.submit(new MyCall()); //  Returns the interface type  Future

       //  Interface method get, Get the return value of the thread 
       String str = future.get();
       System.out.println("str = " + str);

       //  Thread tasks without return values can also be submitted 
       es.submit(my);
       es.submit(my);
       es.submit(my);
       es.shutdown();// Destroy thread pool 
  }
}

ConcurrentHashMap

ConcurrentHashMap Classes are essentially Map aggregate , Set of key value pairs . Usage and HashMap There is no difference between .

For this Map Operations on collections , Don't modify the elements inside , It won't lock .

ConcurrentHashMap Is a thread safe Map, In a multithreaded program , Recommended ConcurrentHashMap Store the data .

State of thread

At some point , A thread can only be in one of these States . The state of this thread reflects JVM Thread state in , and OS irrelevant .

Threads mainly have the following states :

  Blocked state BLOCKED
 New state NEW      Running state RUNABLE      Time waits TIMED_WAITING
  End state TERMINATED Wait indefinitely WAITING

call Thread.sleep() Methods and this.wait() Method will enter the wait state .sleep It won't release the lock ,wait Can release the lock .

File class

Folder Directory , Container for storing files , Prevent file name duplication and set . Document classification , The folder itself does not store any data , Calculating professional data is called a catalog . file File, Storing data , File names in the same directory cannot be the same .

There can be many files in a folder , And folders can also be nested in the storage folder . But in the document , Only data can be saved , Cannot save folder . File is the carrier of data storage in computer , It's a whole .

route Path, The location of a directory or file on disk .

  • c:\jdk8\jar   It's the path to the directory , Is the path to a folder

  • c:\jdk8\bin\javac.exe It's the path to the file

Path is divided into absolute path and relative path , The path is used to locate the resources stored in the computer , This resource is either a file , Or a folder . There are other very special resources , For example, soft links , Hard link, etc .

Generally speaking , Folders do not have any suffixes , Files usually have suffixes , But there are special circumstances . Some folders are suffixed , Because this itself is allowed . Some files also do not have suffixes , This is also allowed by the computer . For example, we often use hosts The configuration file , That is, files without suffixes .

File class , Objects that describe directory files and paths , Platform independent .

Create by file path File

package com.zhangdapeng520.file;

import java.io.File;

/**
* @author https://github.com/zhangdapeng520
* @version 1.0.0
* @className Demo01FileByPath.java
* @description do something about Demo01FileByPath
* @createTime 2022-07-01 23:42:00
*/
public class Demo01FileByPath {
   public static void main(String[] args) {
       //  Declare the path 
       String path = "C:\\tmp";

       //  Create objects 
       File file = new File(path);
       System.out.println(" Whether there is :" + file.exists());
       System.out.println(" Is it a directory :" + file.isDirectory());
  }
}

Create through parent-child path File

Can pass File(String parent,String child) establish File object .parent Pass the string of the parent path ,child Pass the string of sub path .

package com.zhangdapeng520.file;

import java.io.File;

/**
* @author https://github.com/zhangdapeng520
* @version 1.0.0
* @className Demo02FileByFatherAndChild.java
* @description do something about Demo02FileByFatherAndChild
* @createTime 2022-07-01 23:47:00
*/
public class Demo02FileByFatherAndChild {
   public static void main(String[] args) {
       //  Declare the path 
       String path = "C:\\tmp";

       //  Create objects 
       File file = new File(path, "test.txt");
       System.out.println(" Whether there is :" + file.exists());
       System.out.println(" Is it a document :" + file.isFile());
  }
}

adopt File objects creating File

Can pass File(File parent,String child) To create File object .parent Pass on File The parent path of the type ,child Pass the string of sub path .

package com.zhangdapeng520.file;

import java.io.File;

/**
* @author https://github.com/zhangdapeng520
* @version 1.0.0
* @className Demo02FileByFatherAndChild.java
* @description do something about Demo02FileByFatherAndChild
* @createTime 2022-07-01 23:47:00
*/
public class Demo03FileByFatherAndChild {
   public static void main(String[] args) {
       //  Declare the path 
       String path = "C:\\tmp";

       //  Create objects 
       File parent = new File(path);
       File file = new File(parent, "test.txt");
       
       System.out.println(" Whether there is :" + file.exists());
       System.out.println(" Is it a document :" + file.isFile());
  }
}

Create folder

adopt boolean mkdirs() Create directory , This directory can be a multi-level directory , such as a/b/c. The location and name of the directory are written in File In the construction method of .

Sample code :

package com.zhangdapeng520.file;

import java.io.File;

/**
* @author https://github.com/zhangdapeng520
* @version 1.0.0
* @className Demo02FileByFatherAndChild.java
* @description do something about Demo02FileByFatherAndChild
* @createTime 2022-07-01 23:47:00
*/
public class Demo04CreateDir {
   public static void main(String[] args) {
       //  Declare the path 
       String path = "C:\\tmp";

       //  Create a file object 
       File file = new File(path, "a/b/c");
       System.out.println(" Whether there is :" + file.exists());


       //  Create folder 
       boolean isOk = file.mkdirs();
       System.out.println(" Whether to create successfully :" + isOk);
       System.out.println(" Whether there is :" + file.exists());
  }
}

create a file

Can pass boolean createNewFile() Create a file . It should be noted that , The folder where the file is located must exist , Otherwise it won't work . The file path is written in File In the construction method of .

Sample code :

package com.zhangdapeng520.file;

import java.io.File;
import java.io.IOException;

/**
* @author https://github.com/zhangdapeng520
* @version 1.0.0
* @className Demo02FileByFatherAndChild.java
* @description do something about Demo02FileByFatherAndChild
* @createTime 2022-07-01 23:47:00
*/
public class Demo04CreateNewFile {
   public static void main(String[] args) throws IOException {
       //  Declare the path 
       String path = "C:\\tmp";

       //  Create a file object 
       File file = new File(path, "a/b/c");
       System.out.println(" Whether there is :" + file.exists());


       //  Create folder 
       boolean isOk = file.mkdirs();
       System.out.println(" Whether to create successfully :" + isOk);
       System.out.println(" Whether there is :" + file.exists());

       //  create a file 
       File testFile = new File(file, "test.txt");
       isOk = testFile.createNewFile();
       System.out.println(" Whether the file was created successfully :" + isOk);
       System.out.println(" Whether the file created exists :" + testFile.exists());
  }
}

Delete file

adopt boolean delete() Delete the specified directory or file . Path written in File Construction method of class . We need to pay attention to , Deleted files or folders will not enter the recycle bin , Deleted... Directly from disk , There are risks .

Sample code :

package com.zhangdapeng520.file;

import java.io.File;
import java.io.IOException;

/**
* @author https://github.com/zhangdapeng520
* @version 1.0.0
* @className Demo02FileByFatherAndChild.java
* @description do something about Demo02FileByFatherAndChild
* @createTime 2022-07-01 23:47:00
*/
public class Demo05Delete {
   public static void main(String[] args) throws IOException {
       //  Declare the path 
       String path = "C:\\tmp";

       //  Create a file object 
       File file = new File(path, "a/b/c");
       System.out.println(" Whether there is :" + file.exists());


       //  Create folder 
       boolean isOk = file.mkdirs();
       System.out.println(" Whether to create successfully :" + isOk);
       System.out.println(" Whether there is :" + file.exists());

       //  create a file 
       File testFile = new File(file, "test.txt");
       isOk = testFile.createNewFile();
       System.out.println(" Whether the file was created successfully :" + isOk);
       System.out.println(" Whether the file created exists :" + testFile.exists());

       //  Delete file 
       isOk = testFile.delete();
       System.out.println(" Whether the file was deleted successfully :" + isOk);
       System.out.println(" Whether the file created exists :" + testFile.exists());

       //  Delete folder 
       isOk = file.delete();
       System.out.println(" Whether the folder was deleted successfully :" + isOk);
       System.out.println(" Whether the folder is created or not :" + file.exists());
  }
}

File Class judgment method

  • boolean exists() Determine whether the path in the construction method exists

  • boolean isDirectory() Determine whether the path in the construction method is a folder

  • boolean isFile() Determine whether the path in the construction method is a file

  • boolean isAbsolute() Judge whether the path in the construction method is an absolute path

Sample code :

package com.zhangdapeng520.file;

import java.io.File;
import java.io.IOException;

/**
* @author https://github.com/zhangdapeng520
* @version 1.0.0
* @className Demo02FileByFatherAndChild.java
* @description do something about Demo02FileByFatherAndChild
* @createTime 2022-07-01 23:47:00
*/
public class Demo05Delete {
   public static void main(String[] args) throws IOException {
       //  Declare the path 
       String path = "C:\\tmp";

       //  Create a file object 
       File file = new File(path, "a/b/c");


       //  Create folder 
       boolean isOk = file.mkdirs();
       System.out.println(" Whether to create successfully :" + isOk);
       System.out.println(" Whether there is :" + file.exists());
       System.out.println(" Whether the folder is a file :" + file.isFile());
       System.out.println(" Whether the folder is an absolute path :" + file.isAbsolute());
       System.out.println(" Whether the folder is created or not :" + file.exists());
       System.out.println("====================");

       //  create a file 
       File testFile = new File(file, "test.txt");
       isOk = testFile.createNewFile();
       System.out.println(" The file is created except successfully :" + isOk);
       System.out.println(" Whether the file created exists :" + testFile.exists());
       System.out.println(" Whether the file is a file :" + testFile.isFile());
       System.out.println(" Whether the file is an absolute path :" + testFile.isAbsolute());
  }
}

File path

Absolute path

  • The path in the disk is unique

  • Windows In the system , The beginning of the drive C:/Java/jdk1.8.0_221/bin/javac.exe

  • Linux perhaps Unix System , / start , Disk root /usr/local

  • Internet path :www.baidu.com

    • https://item.jd.com/100007300763.html

    • https://pro.jd.com/mall/active/3WA2zN8wkwc9fL9TxAJXHh5Nj79u/index.html

Relative paths

  • There must be a reference

  • C:/Java/jdk1.8.0_221/bin/javac.exe

  • bin It's a reference point : Parent path C:/Java/jdk1.8.0_221

  • bin It's a reference point : Subpath javac.exe

  • bin Reference point : The parent path uses ../ Express

package com.zhangdapeng520.file;

import java.io.File;
import java.io.IOException;

/**
* @author https://github.com/zhangdapeng520
* @version 1.0.0
* @className Demo02FileByFatherAndChild.java
* @description do something about Demo02FileByFatherAndChild
* @createTime 2022-07-01 23:47:00
*/
public class Demo06Absolute {
   public static void main(String[] args) throws IOException {
       //  Declare the path 
       String path = "C:\\tmp";

       //  Absolute path 
       File absoluteFile = new File(path, "a/b/c");
       boolean isOk = absoluteFile.mkdirs();
       System.out.println(" Whether the folder is an absolute path :" + absoluteFile.isAbsolute());

       //  Relative paths 
       File relativeFile = new File("tmp/a/b/c");
       isOk = relativeFile.mkdirs();
       System.out.println(" Whether the folder is an absolute path :" + relativeFile.isAbsolute());
  }
}

原网站

版权声明
本文为[Luo Hanxiang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071619172534.html