Catalogue of series articles
Java thread learning introduction to the basic use of threads
catalogue
1, Writing and reading of XML and excel
1. Three methods of obtaining objects
2. Get properties and methods in the reflection class
3. Constructor in reflection get class
4. Wrapper class Method of the Method in the reflection acquisition class
5. Basic use of Properties class
6. Use reflection + properties to obtain the content in the configuration file
4, There are two ways to implement multithreading:
Method 1: inherit THread class
Method 2: implement Runnable interface
Difference: the difference between implementing runnable interface and inheriting Thread class:
Advantages of implementing runnable interface and inheriting Thread class:
*Method 3: simply write it to enable multithreading through anonymous classes
1. Singlethreaded pool -- singleThreadPool
2. Cacheable thread pool -- CachedThreadPool
3. Thread pool with fixed length and supporting periodic scheduling -- newScheduledThreadPool
6, Callable and Future/FutureTask create multithreading
1. Use Callable+Future to get execution results
2. Use Callable+Future to get results and throw exceptions
3. Use Callable+FutureTask to get execution results
3. Use URLConnection to obtain the source code of the web page
4.URLConnection application example to realize image download
1. The test uses commons io Tool class of operation file built by jar
1, Writing and reading of XML and excel
1. Writing and reading of XML
- XML is an extensible markup language. It is a way to store data. Its characteristic is to follow containment
- Usage scenario: 1) communication bridge between different languages; 2) configuration file
- How to parse XML? (XML = element + attribute + text value)
1. Reading of XML
//Parsing and reading of XML public class Test { public static void main(String[] args) throws DocumentException { String path="D:/person.xml"; //1. Load the ml file into memory to form a file object File file=new File(path); //2. Parsing xml: the classes in JDK; dom4j.jar is a third-party jar package //Initialize Dom4j Core parsing class in jar SAXReader reader=new SAXReader(); //3. Call the read () method to read the ml file Document document=reader.read(file); System.out.println(document.asXML()); //4. Get the root element through Document Element rootElement=document.getRootElement(); //5. Get the attributes in the root element through the root element List<javax.management.Attribute> list =rootElement.attributes(); //6. Iterate out the attribute object in the list for (int i = 0; i < list.size(); i++) { Attribute attribute = (Attribute) list.get(i); System.out.println(attribute.getName()+"\t"+attribute.getValue()); } } }
2. Writing XML
public class Test2 { //Writing XML public static void main(String[] args) throws IOException { //1. Create a Document org.dom4j.Document document=DocumentHelper.createDocument(); //2. Add the first element based on document, which is actually the root element Element rootElement=document.addElement("person"); //2.1 adding attributes to root elements rootElement.addAttribute("sex", "man"); //3. Add other elements based on the root element Element brainElement=rootElement.addElement("brain"); //3.1 adding attributes to brain elements brainElement.addAttribute("size", "36"); //3.2 add text value to brain element brainElement.setText("head"); Element leftEyesElement=rootElement.addElement("eyes"); leftEyesElement.addAttribute("du", "1.0"); leftEyesElement.setText("left eye"); Element rightEyesElement=rootElement.addElement("eyes"); rightEyesElement.addAttribute("du", "2.0"); rightEyesElement.setText("right eye"); //4. Set output format OutputFormat format=OutputFormat.createPrettyPrint();//Write and wrap format.setEncoding("UTF-8");//Set the output format to UTF-8 System.out.println(document.asXML()); //5. Write the successfully created xml file with content in memory to the hard disk //Set the path and name of the file String path="D:/person02.xml"; //create a file FileWriter writer=new FileWriter(path); //To write the document in memory to D: / person02 XML file XMLWriter xmlWriter=new XMLWriter(writer, format); xmlWriter.write(document); xmlWriter.close(); writer.close(); } }
2. Writing and reading excel
1. Reading excel
public class Test1 { //Reading excel public static void main(String[] args) throws BiffException, IOException { String path="D:/123.xlsx"; File file=new File(path); //1. Obtain workbooks Workbook workbook=Workbook.getWorkbook(file); //2. Get sheet from Workbook Sheet sheet=workbook.getSheet(0); //3. Get the cell object through sheet Cell cell=sheet.getCell(0, 0); //4. Get the contents in the cell through the cell System.out.println(cell.getContents()); workbook.close(); } }
2. Writing excel
public class Test2 { //Writing excel file public static void main(String[] args) throws IOException, RowsExceededException, WriteException { String path="D:/789.xls"; File file=new File(path); //1. Create a workBook object WritableWorkbook workbook=Workbook.createWorkbook(file); //2. Create a sheet on the first page based on workBook WritableSheet sheet=workbook.createSheet("first page", 0); //3. Cyclic write for (int i=1;i<9;i++) { Label label=new Label(i,i,i+"-"+i+"="+(i*i)); sheet.addCell(label); //4.workBook writing workbook.write(); //5. Close the workBook object workbook.close(); } } }
II. Network programming
public class Cilent { //client public static void main(String[] args) throws UnknownHostException, IOException { //1. Initialize the core class of the client Socket socket=new Socket("127.0.0.1", 9999); //2. Console input data System.out.println("Please enter data:"); Scanner cin=new Scanner(System.in); String sendInfo=cin.nextLine(); //3. Obtain an output stream object through the socket object OutputStream outputStream = socket.getOutputStream(); //4. Send the input data from the client to the server PrintStream printStream=new PrintStream(outputStream); printStream.println(sendInfo); //5. Read the data sent from the server InputStream InputStream = socket.getInputStream(); InputStreamReader inputStreamReader=new InputStreamReader(InputStream); BufferedReader bufferedReader=new BufferedReader(inputStreamReader); String getStrFormServer = bufferedReader.readLine(); System.out.println("Obtain the data sent from the server at the client:"+getStrFormServer); } }
public class Server { //Server of network programming public static void main(String[] args) throws IOException { //1. Initialize the core class of the server ServerSocket server=new ServerSocket(9999); System.out.println("The server starts waiting for the client to connect"); //2. Call the accept () method to monitor the client connection Socket serverSocket = server.accept(); System.out.println("Connection successful"); //3. Read the data sent by the client InputStream intInputStream=serverSocket.getInputStream(); InputStreamReader inputStreamReader=new InputStreamReader(intInputStream); BufferedReader bufferedReader=new BufferedReader(inputStreamReader); String getInfo = bufferedReader.readLine(); System.out.println("getInfo:"+getInfo); //4. Send data from the server to the client System.out.println("The server inputs on the console:"); Scanner cin=new Scanner(System.in); String strFromServer=cin.nextLine(); OutputStream outputStream=serverSocket.getOutputStream(); PrintStream printStream=new PrintStream(outputStream); printStream.println(strFromServer); } }
3, Reflection
1. Three methods of obtaining objects
- Method 1: object getClass() method
- Method 2: category class attribute
- Method 3: class forname()
//Student class public class Student { public String name; public int age; public String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Studemt [name=" + name + ", age=" + age + ", address=" + address + "]"; } public Student() { System.out.println("Student Class"); } }
public class Test { public static void main(String[] args) throws ClassNotFoundException { Student stu=new Student(); //Method 1: object getClass() method Class<? extends Student> ca = stu.getClass(); System.out.println(ca); //Method 2: category class attribute Class<Student> ca02 = Student.class; System.out.println(ca02); //Method 3: class forname() Class<?> ca03 = Class.forName("fss.fs01.Student"); System.out.println(ca03); } }
2. Get properties and methods in the reflection class
public class Test { //Get properties and methods in the reflection class public static void main(String[] args) { Student stu=new Student(); //1. Get class object Class<? extends Student> student01 = stu.getClass(); //2. Get the short name and full name of the class System.out.println("Abbreviation of class:"+student01.getSimpleName()); System.out.println("Full name of class:"+student01.getName()); //3. Get all the attributes in the class Field[] fields = student01.getFields(); for (Field field : fields) { System.out.println("Type of property in class:"+field.getType()+"\t Name of property in class:"+field.getName()); } //4. Get all methods in the class Method[] methods = student01.getMethods(); for (Method method : methods) { System.out.println("Name of method in class:"+method.getName()+"\t The return value type of the method in the class"+method.getReturnType()); } } }
3. Constructor in reflection get class
public class Test { //Constructor in reflection get class public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { //1. Get class object Class<?> student01 = Class.forName("fss.fs03.Student"); //Get student2 in the constructor Constructor<?>[] constructors = student01.getConstructors(); //3. Take out all constructors in the class (provided they are public modified) for (Constructor<?> constructor : constructors) { //System.out.println(constructor); //The call of newInstance() constructor can have multiple parameters. It must be successfully matched with the constructor in the class, or an error will be reported System.out.println("Constructor call"+constructor.newInstance("")); //Gets the type of the parameter of each constructor Class<?>[] parameterTypes = constructor.getParameterTypes(); for (Class<?> parameter : parameterTypes) { System.out.println(parameter.getName()+"\t"); } System.out.println(); } } }
4. Wrapper class Method of the Method in the reflection acquisition class
public class Test { //The test obtains the wrapper class Method of the Method in the class through reflection public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException { //1. Get class object Class<Student> ownerClass = Student.class; //2. Instantiate Student class Student student = ownerClass.newInstance(); //Execute newInstance() method, and the effect is student student new student(); same //3. Method method = ownerClass.getMethod("sayHi", String.class); String result = (String)method.invoke(student, "Jack"); } }
5. Basic use of Properties class
public class Test { //The basic use of the Properties class is to obtain the content in the configuration file public static void main(String[] args) throws IOException { //1. Initialize Properties Properties properties=new Properties(); //2. Load configuration file FileReader fileReader=new FileReader("dbconfig.txt"); //3. Load configuration file properties.load(fileReader); //4. Get the value of an item in the configuration file String username = properties.getProperty("username"); System.out.println("username:"+username); } }
6. Get the content in the reflection + properties configuration file
public class Hero { public void run(String attributes) { if (attributes.equals("Meatshield ")) { System.out.println(attributes+": You can jog"); } else if(attributes.equals("Shooter")){ System.out.println(attributes+": You can shoot and run"); } else { System.out.println("Can run normally"); } } }
public class Test { //The test uses reflection + properties to get the content in the configuration file public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { //1. Initialization Properties properties=new Properties(); //2. Load configuration file FileReader fileReader = new FileReader("src/config/playerlist.txt"); //3. Load configuration file properties.load(fileReader); //4. Get the value in the configuration file String className = properties.getProperty("className"); System.out.println("className:"+className); String methodName = properties.getProperty("methodName"); System.out.println("methodName:"+methodName); //5. Use reflection to obtain Hero's class object Class<?> cla = Class.forName(className); //6. Get parameterless constructor Constructor<?> constructor = cla.getConstructor(); //7. Initialization of constructor Object hero = constructor.newInstance(); //8. Use reflection to obtain the wrapper class of the method in the class object Method method = cla.getMethod(methodName, String.class); //9. Function callback method.invoke(hero, "Meatshield "); } }
7. Use reflection + properties to modify the content in the configuration file without modifying the source code to expand the function of the program
public class Devil { public void run(String attributes) { if (attributes.equals("boss")) { System.out.println(attributes+": You can jog"); } else if(attributes.equals("littleboss")){ System.out.println(attributes+": You can shoot and run"); } else { System.out.println("Can run normally"); } } }
public class Test { //The test uses reflection + properties to modify the content in the configuration file without modifying the source code to expand the function of the program public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { //1. Initialization Properties properties=new Properties(); //2. Load configuration file FileReader fileReader = new FileReader("src/config/playerlist.txt"); //3. Load configuration file properties.load(fileReader); //4. Get the value in the configuration file String className = properties.getProperty("className"); System.out.println("className:"+className); String methodName = properties.getProperty("methodName"); System.out.println("methodName:"+methodName); //5. Use reflection to obtain Hero's class object Class<?> cla = Class.forName(className); //6. Get parameterless constructor Constructor<?> constructor = cla.getConstructor(); //7. Initialization of constructor Object hero = constructor.newInstance(); //8. Use reflection to obtain the wrapper class of the method in the class object Method method = cla.getMethod(methodName, String.class); //9. Function callback method.invoke(hero, "boss"); } }
4, There are two ways to implement multithreading:
Method 1: inherit THread class
//Calculator class -- implement multithreading by inheriting thread public class JiSuanQi extends Thread { @Override public void run() { //System.out.println("JiSuanQi:run()"); //System.out.println("name of current thread:" + thread. Currentthread() getName()); //System.out.println("name of current thread:" + getName()); for (int i = 0; i < 10; i++) { System.out.println("Name of current thread:"+getName()+"In the implementation of the second paragraph"+(i+1)+"second"); } } public JiSuanQi(String name) { super(name); System.out.println("name:"+name); } }
public class Test { //The test implements multithreading by inheriting the Thread class public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.println("Name of current thread:"+Thread.currentThread().getName()); } //System. out. Current thread name ("printlnthread()):" getName()); JiSuanQi jiSuanQi=new JiSuanQi("Thread Name: computer thread"); jiSuanQi.start();//When the start () method is called, JVM automatically calls the run() method. System.out.println("Main function thread print: 002"); System.out.println("Main function thread print: 003"); System.out.println("Main function thread print: 004"); } }
Method 2: implement Runnable interface
public class Prims implements Runnable { //Multithreading is realized by implementing the Punnable interface @Override public void run() { System.out.println("Name of current thread:"+Thread.currentThread().getName()); while (1>0) { try { Thread.sleep(2000); System.out.println("Current thread:"+Thread.currentThread().getName()); } catch (InterruptedException e) { System.out.println("New thread"+Thread.currentThread().getName()+"It was interrupted for some reason"); } } } }
public class Test { public static void main(String[] args) { System.out.println("Main thread print: 001"); Prims prims=new Prims(); Thread thread=new Thread(prims); thread.start(); System.out.println("Main thread print: 002"); } }
Difference: the difference between implementing runnable interface and inheriting Thread class:
- High coupling degree of inheriting THread class,
- Low coupling of Runnable interface
Advantages of implementing runnable interface and inheriting Thread class:
- It is suitable for multiple threads of the same program code to process the same resource
- It can avoid the limitation of singleton inheritance in Java
- Increase the robustness of the program, the code can be shared by multiple threads, and the code and data are independent
- The Thread pool can only put threads that implement Runnable or callable classes, not directly into classes that inherit threads
*Method 3: simply write it to enable multithreading through anonymous classes
Thread thread=new Thread(new Runnable() { @Override public void run() { System.out.println("Name of the new thread:"+Thread.currentThread().getName()); } }); thread.start(); System.out.println("Main function thread: 002"); }
5, Thread pool
1. Singlethreaded pool -- singleThreadPool
This thread has only one thread working, which is equivalent to a single thread executing all tasks in series. If this unique thread ends because of a field, a new thread will replace it. This thread pool ensures that the execution order of all tasks is executed according to the submission order of tasks
public class MyThread implements Runnable { @Override public void run() { try { Thread.sleep(2000); System.out.println("Name of current thread:"+Thread.currentThread().getName()); //System.out.println(2/0); } catch (InterruptedException e) { System.out.println("Interrupt exception"); } } }
public class Test { //Singlethreaded pool -- singleThreadPool public static void main(String[] args) { //1. Obtain the singleton thread pool through Executors ExecutorService singleThreadPool = Executors.newSingleThreadExecutor(); //2. Create 5 threads MyThread t1=new MyThread(); MyThread t2=new MyThread(); MyThread t3=new MyThread(); MyThread t4=new MyThread(); MyThread t5=new MyThread(); //3. Load the created multithread into the thread pool and execute singleThreadPool.execute(t1); singleThreadPool.execute(t2); singleThreadPool.execute(t3); singleThreadPool.execute(t4); singleThreadPool.execute(t5); //4. Close thread pool singleThreadPool.shutdown(); } }
2. Cacheable thread pool -- CachedThreadPool
public static void main(String[] args) throws InterruptedException { //1. Create a cacheable thread pool ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); //2. Use cache thread pool for (int i = 0; i < 6; i++) { if (! cachedThreadPool.isShutdown()) { Thread.sleep(1000); cachedThreadPool.execute(new Runnable() { @Override public void run() { System.out.println("Name of current thread:"+Thread.currentThread().getName()); } }); } } //3. Close thread pool cachedThreadPool.shutdown(); } }
3. Thread pool with fixed length and supporting periodic scheduling -- newScheduledThreadPool
public class Test { //Thread pool with fixed length and supporting periodic scheduling public static void main(String[] args) throws InterruptedException { ScheduledExecutorService schedulThreadPool = Executors.newScheduledThreadPool(5); schedulThreadPool.scheduleAtFixedRate(new Runnable() { @Override public void run() { System.out.println("Name of current thread:"+Thread.currentThread().getName()); } }, 1, 2, TimeUnit.SECONDS); Thread.sleep(6000); schedulThreadPool.shutdown(); } }
4. Timer:
public class MyTimerTask extends TimerTask { @Override public void run() { System.out.println("Hello"); } }
public class Test { //Test timer & TimerTask public static void main(String[] args) throws InterruptedException { //1. Timer initialization Timer timer = new Timer(); //2. Initialization of scheduled tasks MyTimerTask timerTask = new MyTimerTask(); //3. Timer execution scheduling timer.schedule(timerTask, 0, 2000); Thread.sleep(4000);//Cancel in 4 seconds //4. Cancel timer timer.cancel(); } }
6, Callable and Future/FutureTask create multithreading
1. Use Callable+Future to get execution results
//Implementation class of Callable interface public class Callablelmpl implements Callable<Integer> { public int sum=0;//Simulate an accumulation and summation variable. The purpose is to demonstrate the multithreading of the callable interface in the future, and get the return value after executing the thread task @Override public Integer call() throws Exception { System.out.println("The name of the current thread is:"+Thread.currentThread().getName()); System.out.println("callable The new thread opened by the interface starts to execute the calculation"); Thread.sleep(2000);//Simulate the time-consuming operation of the calculation process for (int i = 0; i < 100; i++) { sum+=i; } System.out.println("callable The new thread opened by the interface starts to execute the calculation: end"); return sum; } }
public class Test { //The test implements multithreading through callable and Future, and obtains the results after execution public static void main(String[] args) throws InterruptedException, ExecutionException { //1. Create a singleton thread pool ExecutorService singleThreadPool = Executors.newSingleThreadExecutor(); //2. Instantiate the implementation class of the callable interface Callablelmpl callableImplTask = new Callablelmpl(); //3. Add a new thread to the thread pool Future<Integer> future=singleThreadPool.submit(callableImplTask); //4. Close thread pool singleThreadPool.shutdown(); //5. Time consuming operation of main thread Thread.sleep(2000); if ((future.get())!=null) { System.out.println("The results after execution are:"+future.get()); } else { System.out.println("future.get()The execution result is null"); } System.out.println("End of main function thread execution"); } }
2. Use Callable+Future to get results and throw exceptions
public class MyCallable implements Callable<String> { public int flag=0;//A variable is defined for identification. Its purpose is to demonstrate the situation of different threads (exceptions can be demonstrated) @Override public String call() throws Exception { System.out.println("The name of the current thread is:"+Thread.currentThread().getName()); if (this.flag==0) { return "flag==0"; } if (this.flag==1) { try { while (1>0) { System.out.println("Dead cycle......"); Thread.sleep(2000); } } catch (InterruptedException e) { System.out.println("Interrupt exception"); return "false"; } } else { throw new Exception("Your input is incorrect"); } } public MyCallable(int flag) { super(); this.flag = flag; } }
public class Test { //An exception is thrown when testing callable and future to obtain data public static void main(String[] args) throws InterruptedException, ExecutionException { //1. Instantiate three callableTask task classes MyCallable task0=new MyCallable(0); MyCallable task1=new MyCallable(1); MyCallable task2=new MyCallable(2); //3. Create a fixed number of thread pools ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3); //4. Load into the thread pool one by one Future<String> future0 = fixedThreadPool.submit(task0); System.out.println("future0:"+future0.get()); Future future1 = fixedThreadPool.submit(task1); //System.out.println("future1:"+future1.get()); //In order to demonstrate the third case later, we think to stop task 2 after 5s, because task 2 is an endless loop Thread.sleep(5000); System.out.println( future1.cancel(true)); try { Future<String> future2 = fixedThreadPool.submit(task2); System.out.println(future2.get()); } catch (Exception e) { System.out.println(e.getMessage()); } } }
3. Use Callable+FutureTask to get execution results
public class Callablelmpl implements Callable<Integer> { public int sum=0;//Simulate an accumulation and summation variable. The purpose is to demonstrate the multithreading of the callable interface in the future, and get the return value after executing the thread task @Override public Integer call() throws Exception { System.out.println("The name of the current thread is:"+Thread.currentThread().getName()); System.out.println("callable The new thread opened by the interface starts to execute the calculation"); Thread.sleep(2000);//Simulate the time-consuming operation of the calculation process for (int i = 0; i < 100; i++) { sum+=i; } System.out.println("callable The new thread opened by the interface starts to execute the calculation: end"); return sum; } }
public class Test { // Test callable+futureTask to realize multithreading and obtain results public static void main(String[] args) throws InterruptedException, ExecutionException { //1. Create thread pool ExecutorService singleThreadPool = Executors.newSingleThreadExecutor(); //2. Instantiation of implementation class of callable interface Callablelmpl callablelmpl = new Callablelmpl(); //3. Pass the instantiation object of the implementation class of the callable interface into the constructor of FutureTask to realize the instantiation of FutureTask FutureTask<Integer> futureTask = new FutureTask<Integer>(callablelmpl); //4. Load the new thread into the thread pool singleThreadPool.submit(futureTask); //5. Close thread pool singleThreadPool.shutdown(); Thread.sleep(3000); System.out.println("Simulate that the main thread does not end"); //6. Take out the calculation result of the sub thread System.out.println(futureTask.get()); System.out.println("The main thread is over"); } }
VII. URL
Through the URL class, Java programs can easily operate network resources.
1. Basic use of URL
public class Test { //Basic usage of URL class public static void main(String[] args) throws MalformedURLException { //1. Specify the network resource address String urlpath="https://so.youku.com/search_video/q_%E9%92%A2%E9%93%81%E4%BE%A0?searchfrom=1"; //2. Initialize URL class URL realUrl=new URL(urlpath); //3. Get some network information through URL class System.out.println("The host is:"+realUrl.getHost()); System.out.println("The agreement is:"+realUrl.getProtocol()); System.out.println("The default port is:"+realUrl.getDefaultPort()); System.out.println("Request parameters:"+realUrl.getQuery()); } }
2.URL application example
public class Test02 { //Save web page as URL public static void main(String[] args) throws IOException { //1. Specify network resources String urlPath="http://www.baidu.com"; //2. Initialize URL class URL url=new URL(urlPath); //3. Get an input stream object through url InputStream inputStream = url.openStream(); //4.IO read / write InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String path="E:/std/baidu.html"; File file=new File(path); PrintWriter printWriter = new PrintWriter(file); String hang=""; while ((hang=bufferedReader.readLine())!=null) { printWriter.write(hang); printWriter.flush(); //5. Close flow related objects printWriter.close(); bufferedReader.close(); inputStreamReader.close(); inputStream.close(); } } }
3. Use URLConnection to obtain the source code of the web page
public class Test03 { //Use URLConnection to obtain the source code of the web page public static void main(String[] args) throws IOException { //1. Create URL object URL url = new URL("https://search.51job.com/list/010000,000000,0000,00,9,99,java,2,1.html?lang=c&stype=&postchannel=0000&workyear=99&cotype=99°reefrom=99&jobterm=99&companysize=99&providesalary=99&lonlat=0%2C0&radius=-1&ord_field=0&confirmdate=9&fromType=&dibiaoid=0&address=&line=&specialarea=00&from=&welfare="); //2. Create URLConnection object through openConnection() method in URL object URLConnection connection = url.openConnection(); //3. Call the connect method provided by the URLConnection object to connect to the remote service connection.connect(); //4. After connecting to the server, you can query the header information Map<String,List<String>> headerMap = connection.getHeaderFields(); Set<String> keySet = headerMap.keySet(); Iterator<String> it = keySet.iterator(); while (it.hasNext()) { String key = it.next(); List<String> list = headerMap.get(key); StringBuffer sb=new StringBuffer(); for (int i = 0; i <list.size(); i++) { if(i>0) { sb.append(","); } String str = list.get(i); sb.append(str); } //System.out.println(key+":"+sb); } //6. Get the input stream and read the resource data from it InputStream inputStream = connection.getInputStream(); InputStreamReader reader=new InputStreamReader(inputStream); BufferedReader bufferedReader=new BufferedReader(reader); String line=""; while ((line=bufferedReader.readLine())!=null) { System.out.println(line); } //7. Close the flow object bufferedReader.close(); reader.close(); inputStream.close(); } }
4.URLConnection application example to realize image download
public class Test04 { //Use UrlConnection to crawl pictures on Web pages public static void main(String[] args) throws IOException { //1. Create URL object URL url = new URL("https://imgsa.baidu.com/forum/w%3D580/sign=a6b7ab9a10dfa9ecfd2e561f52d1f754/48c7a7efce1b9d16a99e53e7f2deb48f8d5464d8.jpg"); //2. Create URLConnection object through openConnection() method in URL object URLConnection connection = url.openConnection(); //3. Call the connect method provided by the URLConnection object to connect to the remote service // Set the request method. The default is GET connection.setRequestProperty("method", "GET"); // Set character encoding connection.setRequestProperty("Charset", "UTF-8"); connection.connect(); int fileLength = connection.getContentLength();//Gets the size of the file //4. Establish an input stream between the client (Test04.java) and the server (web page) InputStream inputStream = connection.getInputStream(); //5. Turn the input flow into a buffer flow BufferedInputStream bin = new BufferedInputStream(inputStream); //6. Set the path to save the picture String path = "D:\\zp\\uc\\1.jpg"; File file = new File(path);//Open up a memory file according to the path //If the path does not exist, create a path if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } //Create an output stream OutputStream out = new FileOutputStream(file); int size = 0; int len = 0; byte[] buf = new byte[1024];//Build a buffer block while ((size = bin.read(buf)) != -1) //Read line by line { len += size; out.write(buf, 0, size);//write in // Print download percentage System.out.println("Downloaded-------> " + len * 100 / fileLength +"%\n"); } //Close flow object bin.close(); out.close(); inputStream.close(); } }
VIII commons-io
1. It is a toolkit for processing IO streams. It encapsulates many methods for processing IO streams and files, which can greatly simplify our code for processing IO streams and operation files. It is mainly divided into tool classes, tail classes, line iterators, file filters, file comparators and extension streams. In short: it is a jar produced by the Apache foundation that is more convenient for I/O operation.
2. Tool classes include FileUtils, IOUtils, FilenameUtils and filesystematutils. The methods of the first three are not much different, but the objects of operation are different.
- FileUtils: mainly operate File class; FileUtils: handles the opening, moving, reading and judging of files
- IOUtils: main operation IO stream
- FilenameUtils: is the operation file name
- File system utils: contains some practical methods for accessing file systems that are not provided by JDK
1. The test uses commons io Tool class of operation file built by jar
//Using commons io Jar tool class for creating operation files public class FileTools { /** * @desc 1.Read every line in the file * @param pathname * @throws IOException */ public void getLinesByRead(String pathname) throws IOException{ File file=new File(pathname); List<String> list = FileUtils.readLines(file, "GBK"); for (String every : list) { System.out.println(every); } } /** * @desc 2.Write string to file * @param pathname * @param str * @throws IOException */ public void strWriteToFile(String pathname,String str) throws IOException { File file=new File(pathname); FileUtils.writeStringToFile(file, str, "GBK", true); System.out.println("The string was written successfully"); } /** * @desc 3.Write to the file line by line, but the effect will be the copy of the file * @param srcPath * @param purposePath * @throws IOException */ public void strWriteToFile2(String srcPath,String purposePath) throws IOException { File file =new File(srcPath); List<String> line = FileUtils.readLines(file, "GBK");//Line by line reading File file2=new File(purposePath); FileUtils.writeLines(file2, line); System.out.println("Write file line by line succeeded"); } /** * @desc 4.Copy file * @param srcPath * @param purposePath * @throws IOException */ public void fileCopy(String srcPath,String purposePath) throws IOException { File srcFile=new File(srcPath); File purposeFile=new File(purposePath); FileUtils.copyFile(srcFile, purposeFile); System.out.println("File copy succeeded"); } /** * @desc 5.Assign a value according to the URL, and the result is equivalent to saving as * @param url * @param pathname * @throws Exception */ public void urlSaveAsFile(String url,String pathname) throws Exception { URL urlHtml=new URL(url); File file=new File(pathname); FileUtils.copyURLToFile(urlHtml, file); System.out.println("Save as succeeded"); } /** * @desc 6.Delete files and folders under the path * @param pathname * @throws Exception */ public void delete(String pathname) throws Exception { File file=new File(pathname); FileUtils.deleteDirectory(file); } }
public class Test { public static void main(String[] args) throws Exception { FileTools fts=new FileTools(); //fts.getLinesByRead("D:/123.txt"); //fts.strWriteToFile("E:/123.txt", "desert boat"); //fts.strWriteToFile2("D:/123.txt", "E:/123.txt"); // fts.fileCopy("D:/123.txt", "D:/cp/666.txt"); //fts.urlSaveAsFile("https://d-ring.i4.cn/audio/2019/09/02/15/1567407708580_446168.mp3", "D:/cp/mp3/123.mp3"); fts.delete("D:/cp"); } }