Java复习(全)

package com.test.java;

import org.apache.commons.io.FileUtils;
import org.junit.Test;

import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;

public class Day03 {

    /**
     * 一、文件File
     * 1. creatNewFile:
     * - 仅用于创建文件,而且文件所在根目录必须是存在的,不然会报错
     * - 如果文件已经存在,则返回false。不会创建新文件
     * 2. mkdir/mkdirs:
     * - mkdir创建指定的目录,但是待创建的目录前一层级目录结构必须是已经存在的,不然创建不成功
     * - 所以,建议使用mkdirs,创建全路径,不管存在不存在
     * 3. listFiles():
     * - 返回file封装路径下的所有子文件和文件夹的File对象 ,是全路径
     * - 只查找一层
     *
     * @throws IOException
     */
    @Test
    public void testFile() throws IOException {
        File file = new File("D:/Test/1.txt");
        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();

//        file = new File("D:/Test/a/b/");
//        file.mkdir();
//        file.mkdirs();

        file = new File("D:/Test");
        File[] files = file.listFiles();
        for (File i : files) {
            System.out.println(i.getAbsolutePath());
        }
    }

    /**
     * 二、listFiles + 过滤器Filter
     * 1. 继承FileFilter接口,实现accept方法
     */
    @Test
    public void testFilter() {
        File file = new File("D:/Test");
        File[] files = file.listFiles(new FileFilter() {

            @Override
            public boolean accept(File pathname) {
//                System.out.println(pathname.getAbsolutePath());
                String regex = ".+\\.txt";
                return pathname.toString().matches(regex);
            }
        });
        for (File i : files) {
            System.out.println(i.getAbsolutePath());
        }
    }


    /**
     * 三、流
     * 1. InputStream 字节输入流 抽象类
     * -- FileInputStream
     * -- BufferedInputStream
     * -- DataInputStream
     * -- ObjectInputStream
     * -- StringBufferInputStream
     * -- ByteArrayInputStream
     * 

* 2. OutputStream 字节输出流 抽象类 * -- FileOutputStream * -- BufferedOutputStream * -- DataOutputStream * -- ObjectOutputStream * -- StringBufferOutputStream * -- ByteArrayOutputStream *

* 3. Reader 字符输入流 * -- FileReader * -- BufferedReader * -- InputStreamReader *

* 4. Writer 字符输出流 * -- FileWriter * -- BufferedWriter * -- OutputStreamWriter *

* 1.规律整理:什么时候使用什么流 * 首先,要明确是操作字符还是字节; * 如果是操作字符,那么就是Reader和Writer类及其子类 FileReader和FileWriter(快捷流,使用默认编码)、OutputStreamWriter和InputStreamReader(转换流,使用自定义编码)、BufferedReader和BufferedWriter(缓冲流,使用默认编码);最后通过具体的功能,是快捷,还是指定编码,还是高效,选择使用对应的子类流。 * 如果是操作字节,那么就是InputStream和OutputStream类及其子类 FileInputStream和FileOutputStream(普通字节流,一般作为转换流和高效字节流的构造参数)、BufferedInputStream和BufferedOutputStream(高效字节流);最后通过具体的功能,选择普通还是高效。 *

* 2.类整理 * 字节流 * 字节输入流InputStream * FileInputStream:普通字节输入流 * BufferedInputStream:高效的字节输入流,构造函数需要传入字节输入流 * 字节输出流OutputStream * FileOutputStream:普通的字节输出流 * BufferedOutputStream:高效的字节输出流,构造函数需要传入字节输出流 *

* 字符流 * 字符输入流Reader * FileReader:快捷的字符输入流,使用默认编码 * InputStreamReader:转换流,可以自定义编码 * BufferedReader:缓冲流,高效读取,使用默认编码 * 字符输出流Writer * FileWriter:快捷的字符输出流,使用默认编码 * InputStreamWriter:转换流,可以自定义编码 * BufferedWriter:缓冲流,高效输出,使用默认编码 */ @Test public void testIO() { String path = "d:/Test/1.json"; File file = new File(path); StringBuilder sb = new StringBuilder(); // FileInputStream fileInputStream = new FileInputStream(path); // FileInputStream FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(file); int len = 0; byte[] buf = new byte[1024]; while ((len = fileInputStream.read(buf)) != -1) { sb.append(new String(buf, 0, len)); } System.out.println(sb); } catch (Exception e) { e.printStackTrace(); } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } // // // FileOutputStream System.out.println("--------------------------------------"); OutputStream outputStream = null; try { outputStream = new FileOutputStream(file, true); outputStream.write("\r\n".getBytes()); outputStream.write(sb.toString().getBytes()); outputStream.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } // // BufferedInputStream // FileInputStream fileInputStream = null; // BufferedInputStream bufferedInputStream = null; // try { // fileInputStream = new FileInputStream(file); // bufferedInputStream = new BufferedInputStream(fileInputStream); //// bufferedInputStream.read() // } catch (FileNotFoundException e) { // e.printStackTrace(); // } // // // BufferedOutputStream // BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(); // bufferedOutputStream.write(); // // FileReader System.out.println("--------------------------------------"); FileReader fileReader = null; try { fileReader = new FileReader(file); char[] cbuf = new char[1024]; int len = 0; while ((len = fileReader.read(cbuf)) != -1) { sb = new StringBuilder(); sb.append(new String(cbuf, 0, len)); } System.out.println(sb); } catch (Exception e) { e.printStackTrace(); } finally { if (fileReader != null) { try { fileReader.close(); } catch (IOException e) { e.printStackTrace(); } } } // // FileWriter System.out.println("--------------------------------------"); FileWriter fileWriter = null; try { fileWriter = new FileWriter(file); fileWriter.write(sb.toString()); } catch (Exception e) { e.printStackTrace(); } finally { try { fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } // BufferedReader System.out.println("--------------------------------------"); BufferedReader bufferedReader = null; try { fileReader = new FileReader(file); bufferedReader = new BufferedReader(fileReader); int len = 0; char[] cbuf = new char[1024]; // bufferedReader.readLine() while ((len = bufferedReader.read(cbuf)) != -1) { sb = new StringBuilder(); sb.append(new String(cbuf, 0, len)); } System.out.println(sb); } catch (Exception e) { e.printStackTrace(); } // // BufferedWriter System.out.println("--------------------------------------"); BufferedWriter bufferedWriter = null; try { fileWriter = new FileWriter(file); bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(sb.toString()); bufferedWriter.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (bufferedWriter != null) { try { bufferedWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } // InputStreamReader // InputStreamReader inputStreamReader = new InputStreamReader(); // inputStreamReader.read() // // OutputStreamWriter // new OutputStreamWriter().write(); } /** * 四、Properties类 * 1. Properties是一个集合,存储键值对。实现map接口;没有泛型,键值都是字符串,可用于持久化储存数据。 * 2. void setProperties(String key , String value); //存入键值对,相当于put * String getProperties(String key); //取出键值对,相当于get * Set stringPropertyNames(); //用于遍历集合,得到所有键的set集合 * load(InputStream in); :读取指定的文件,将读取到的键值对保存到properties集合中 * load(Reader);重载 * store(OutputStream out , commons); //将键值对永久保存到文件中,commons代表描述信息,就是注释 * store(Writer); //重载 */ @Test public void testProp() throws Exception { Properties properties = new Properties(); File file = new File("D:/Test/a.prop"); // properties.setProperty("id","111"); // properties.setProperty("name","ggg"); // FileWriter fileWriter = new FileWriter(file); // BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); // properties.store(bufferedWriter,"nothing"); // System.out.println(properties.getProperty("name")); FileReader fileReader = new FileReader(file); properties.load(fileReader); System.out.println(properties.getProperty("name")); } /** * 五、序列化与反序列化 * 1. 序列化流将Java中的对象,基本数据类型,引用类型等写入到文件中,进行持久化保存 * 反序列化流,可以将序列化保存的文件,再次读取到内存中 * 序列化构造方法:ObjectOutputStream(OutputStream out); * 反序列化构造方法:ObjectInputStream(InputStream in); * 写方法: void writeObject(Object obj); * 读方法:object readObject(); * 瞬态关键字:transient,对成员变量进行保护,防止其被序列化 */ @Test public void testSe() throws Exception { Person person = new Person("xoa", 17); ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("d:/Test/p.obj"))); objectOutputStream.writeObject(person); objectOutputStream.flush(); objectOutputStream.close(); // ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(new File("d:/Test/p.obj"))); Person o = (Person) objectInputStream.readObject(); System.out.println(o.toString()); } /** * 六、 打印流 * 打印流一共有2个:字节打印流printStream 和 字符打印流 printWriter; * 就是将字符输出到指定的文件,仅仅是为了方便打印和输出,不抛出io异常,但是可能会抛出其他异常 * printStream(File / StringName / OutputStream); * printWriter(File / StringName / OutputStream / Writer); * 如果传入的是流~可以开启自刷新功能printWriter(OutputStream out,true); */ @Test public void testPrintStream() throws Exception { PrintStream printStream = new PrintStream("d:/Test/1.log"); printStream.print("xxxxx"); printStream.println("mmmmm"); PrintWriter printWriter = new PrintWriter("d:/Test/1.log"); printWriter.println("vvvvv"); printStream.close(); printWriter.close(); } /** * 七、数组 */ @Test public void testArray() { int[] array = {1, 4, 6, 2, 3, 8, 6, 7, 9}; // 排序 Arrays.sort(array); // 查找 System.out.println(Arrays.binarySearch(array, 5)); ArrayList list = new ArrayList<>(); Integer i = new Integer(3); list.add(1); list.add(i); list.add(6); list.add(2); list.add(4); // 反转 Collections.reverse(list); // 查找 Collections.sort(list); System.out.println(Collections.binarySearch(list, new Integer(3))); // 数组转List String[] a = {"a", "b"}; ArrayList strings = new ArrayList<>(Arrays.asList(a)); Integer[] in = {1, 2}; ArrayList integers = new ArrayList<>(Arrays.asList(in)); int[] inn = {1, 2}; ArrayList ints = new ArrayList<>(Arrays.asList(inn)); // list 转数组 Object[] objects = integers.toArray(); // 数组填充 array = new int[5]; Arrays.fill(array, 50); Arrays.fill(array, 2, 3, 88); // 数组拷贝 int[] ll = {1, 2, 3}; array = new int[5]; System.arraycopy(ll, 0, array, 0, 2); System.out.println(array); // 计算差集,removeAll boolean b = list.removeAll(list); System.out.println(list); // 计算交集 boolean b1 = list.retainAll(list); // 包含 list.contains(5); // 判断数组是否相等 list.equals(list); } /** * 八、方法 */ public void testFunc() { EE ee = EE.aa; switch (ee) { case aa: break; case bb: break; case cc: break; case dd: break; } } /** * 九、目录操作 */ @Test public void testDir() { // 删除目录 deleteDir(new File("D:\\Test\\out1.json")); // 获取目录大小 getDirSize("D:\\HIVE_CLIENT-configs"); // 遍历目录 getListDir(new File("D:\\HIVE_CLIENT-configs")); } // 递归删除 public void deleteDir(File dir) { if (dir.isDirectory()) { Arrays.asList(dir.list()).forEach(x -> { deleteDir(new File(dir, x)); }); } dir.delete(); } // 获取目录的大小 public void getDirSize(String path) { long l = FileUtils.sizeOfDirectory(new File(path)); System.out.printf("size is %d", l); } // 遍历目录 public void getListDir(File file) { System.out.println(file.getAbsolutePath()); if (file.isDirectory()) { Arrays.asList(file.list()).forEach(x -> { getListDir(new File(file, x)); }); } } /** * 十、链表 */ public void testLinkedList() { // 删除链表元素 LinkedList strings = new LinkedList<>(); strings.add("1"); strings.add("2"); strings.add("3"); String re = strings.removeFirst(); List strings1 = strings.subList(2, 4); // 元素查找 strings.indexOf("3"); // 获取最大元素 Collections.max(strings); // 修改链表 strings.set(2, "cc"); // 旋转链表 Collections.swap(new ArrayList(), 2, 3); } /** * 十一、集合 */ @Test public void testCollection() { // 遍历map HashMap hashMap = new HashMap<>(); hashMap.keySet().forEach(x -> { System.out.printf("key is %s, value is %s \r\n", x, hashMap.get(x)); }); Iterator iterator = hashMap.keySet().iterator(); while (iterator.hasNext()) { String key = iterator.next(); String value = hashMap.get(key); System.out.printf("key is %s, value is %s \r\n", key, value); } // 打乱集合顺序 Collections.shuffle(new ArrayList<>()); // 遍历 HashSet set = new HashSet<>(); Iterator iterator1 = set.iterator(); while (iterator1.hasNext()) { iterator1.next(); } set.forEach(x -> { System.out.println(x); }); // 只读集合 List list = Arrays.asList(new Integer[]{1, 2, 3, 4}); List list1 = Collections.unmodifiableList(list); list1.add(1); // 部分对调 -- dis > 0 表示第一个元素 往后挪几个位置 // -- dis < 0 表示最后一个元素,往前挪几个位置 List list2 = Arrays.asList("one two three four five".split("\\s+")); Collections.rotate(list2, -4); list2.forEach(x -> System.out.println(x)); // 查找最大值最小值 Collections.max(list2); Collections.min(list2); Hashtable table = new Hashtable<>(); table.put("1", "one"); table.put("2", "two"); table.put("3", "three"); Enumeration keys = table.keys(); while (keys.hasMoreElements()) { Object o = keys.nextElement(); System.out.println(table.get(o.toString()).toString()); } // 元素替换 List list3 = Arrays.asList("1,1,2,3,3,3,3".split(",")); Collections.replaceAll(list3, "88", "cc"); list.forEach(x -> System.out.print(x)); System.out.println(""); // 查看一个列表是否在另一个列表中 int index = Collections.indexOfSubList(list, Arrays.asList(new String[]{"3", "3"})); System.out.println("index is :" + index); int index1 = Collections.lastIndexOfSubList(list, Arrays.asList(new String[]{"3", "3"})); System.out.println("last index is :" + index1); } /** * 十二、Socket */ @Test public void testSocket() throws Exception { // getHosts("www.baidu.com"); // isPortUsed(); // crawl("http://www.baidu.com"); // getHeadInfo("http://www.runoob.com"); // anylizeURL("http://www.runoob.com");a } // 获取 hosts public void getHosts(String url) throws Exception { InetAddress byName = InetAddress.getByName(url); String hostName = byName.getHostName(); String hostAddress = byName.getHostAddress(); System.out.println(hostName + "-" + hostAddress); } // 查看端口是否占用 public void isPortUsed() { Socket Skt; String host = "localhost"; for (int i = 0; i < 1024; i++) { try { System.out.println("查看 " + i); Skt = new Socket(host, i); System.out.println("端口 " + i + " 已被使用"); } catch (UnknownHostException e) { System.out.println("Exception occured" + e); break; } catch (IOException e) { } } } // 判断主机端口 public static boolean isSocketAliveUitlitybyCrunchify(String hostName, int port) { boolean isAlive = false; // 创建一个套接字 SocketAddress socketAddress = new InetSocketAddress(hostName, port); Socket socket = new Socket(); // 超时设置,单位毫秒 int timeout = 2000; log("hostName: " + hostName + ", port: " + port); try { socket.connect(socketAddress, timeout); socket.close(); isAlive = true; } catch (SocketTimeoutException exception) { System.out.println("SocketTimeoutException " + hostName + ":" + port + ". " + exception.getMessage()); } catch (IOException exception) { System.out.println( "IOException - Unable to connect to " + hostName + ":" + port + ". " + exception.getMessage()); } return isAlive; } private static void log(String string) { System.out.println(string); } private static void log(boolean isAlive) { System.out.println("是否真正在使用: " + isAlive + "\n"); } // 获取本机主机名和ip public void getLocalHostName() throws UnknownHostException { InetAddress localHost = InetAddress.getLocalHost(); String hostName = localHost.getHostName(); String hostAddress = localHost.getHostAddress(); } // 获取远程文件的大小 public void getRemoteFileSize() throws IOException { int size; URL url = new URL("http://www.runoob.com/wp-content/themes/runoob/assets/img/newlogo.png"); URLConnection conn = url.openConnection(); size = conn.getContentLength(); if (size < 0) System.out.println("无法获取文件大小。"); else System.out.println("文件大小为:" + size + " bytes"); conn.getInputStream().close(); } // 查看最终修改时间 public void getLastModifiedTime() throws IOException { URL u = new URL("http://127.0.0.1/test/test.html"); URLConnection uc = u.openConnection(); SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); uc.setUseCaches(false); long timestamp = uc.getLastModified(); System.out.println("test.html 文件最后修改时间 :" + ft.format(new Date(timestamp))); } // 网页抓取 public void crawl(String path) throws IOException { URL url = new URL(path); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); BufferedWriter writer = new BufferedWriter(new FileWriter(new File("data.html"))); String line = null; while ((line = reader.readLine()) != null) { System.out.println(line); writer.write(line); writer.newLine(); } reader.close(); writer.close(); } // 获取URL响应头的日期 public void getHeadDate(String path) throws IOException { URL url = new URL(path); URLConnection urlConnection = url.openConnection(); long date = ((HttpURLConnection) urlConnection).getDate(); System.out.printf("Data is %s\r\n", new Date(date)); } // 获取URL响应头信息 public void getHeadInfo(String path) throws IOException { URL url = new URL(path); URLConnection urlConnection = url.openConnection(); Map> fields = urlConnection.getHeaderFields(); fields.forEach((x, y) -> { System.out.println(x); y.forEach(z -> { System.out.println(z); }); }); } // 解析URL public void anylizeURL(String path) throws MalformedURLException { URL url = new URL(path); System.out.println("URL 是 " + url.toString()); System.out.println("协议是 " + url.getProtocol()); System.out.println("文件名是 " + url.getFile()); System.out.println("主机是 " + url.getHost()); System.out.println("路径是 " + url.getPath()); System.out.println("端口号是 " + url.getPort()); System.out.println("默认端口号是 " + url.getDefaultPort()); } // 服务端 @Test public void server() throws IOException { ServerSocket serverSocket = new ServerSocket(8888); System.out.println("启动服务器"); Socket accept = serverSocket.accept(); InetAddress clientAddr = accept.getInetAddress(); InetAddress localHost = clientAddr.getLocalHost(); System.out.printf("客户端连接:%s - %s\r\n", localHost.getHostName(), localHost.getHostAddress()); BufferedReader reader = new BufferedReader(new InputStreamReader(accept.getInputStream())); String msg = reader.readLine(); System.out.println("客户端:" + msg); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(accept.getOutputStream())); bw.write(msg + "\n"); bw.flush(); } // 客户端 @Test public void client() throws IOException { Socket s = new Socket("localhost", 8888); //构建IO InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os)); //向服务器端发送一条消息 bw.write("测试客户端和服务器通信,服务器接收到消息返回到客户端\n"); bw.flush(); //读取服务器返回的消息 BufferedReader br = new BufferedReader(new InputStreamReader(is)); String mess = br.readLine(); System.out.println("服务器:" + mess); } /** * 十三、多线程 */ @Test public void testThread() { Thread thread1 = new Thread(new Runnable() { @Override public void run() { // 获取当前线程名称 Thread t = Thread.currentThread(); t.getId(); // 获取所有线程 t.getThreadGroup(); // 获取线程状态 t.getState(); // 查看线程的优先级 t.getPriority(); try { // 线程挂起 t.join(); // 线程终止 t.interrupt(); t.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("thread is" + t.getName()); } }); Thread thread2 = new Thread(new Runnable() { @Override public void run() { System.out.println("thread is" + Thread.currentThread()); } }); thread1.start(); // 查看线程是否存活 System.out.printf("thread is %s\r\n", thread1.isAlive()); thread2.start(); } /** * 十四、反射 */ @Test public void testReflect() throws Exception { RePerson tom = new RePerson("tom", 11); Class rePerson = Class.forName("com.test.java.RePerson"); // 通过反射获取实例 RePerson o = (RePerson) rePerson.newInstance(); o.name = "tom"; o.age = 11; o.eat(); System.out.println(o.age); System.out.println(o.name); System.out.println(rePerson.getName()); System.out.println(tom.getClass().getName()); System.out.println(rePerson.hashCode()); System.out.println(RePerson.class.hashCode()); // 通过反射获取方法 Method func = rePerson.getDeclaredMethod("func", int.class); Object invoke = func.invoke(o, 5); // 通过反射获取指定的构造器,通过构造器获取对象 Constructor constructor = rePerson.getDeclaredConstructor(String.class, int.class); RePerson tomm = (RePerson) constructor.newInstance("tomm", 188); tomm.eat(); // 通过发射获取字段 Field name = rePerson.getDeclaredField("name"); name.set(tomm, "xxxxxxxxx"); tomm.eat(); } } /** * 十五、多线程避免死锁 */ class Jar { private Integer remain = new Integer(0); private final int MAX = 10; public void add(int i) { synchronized (this) { while (remain + i > MAX) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } remain += i; System.out.printf("add %d, remain %d\r\n", i, remain); notify(); } } public void cost(int i) { synchronized (this) { while (i > remain) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } remain -= i; System.out.printf("cost %d, remain %d\r\n", i, remain); notify(); } } } class Eat extends Thread { private Jar j; public Eat(Jar j) { this.j = j; } @Override public void run() { while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } j.cost(2); System.out.println("消耗2"); } } } class Bee extends Thread { private Jar j; public Bee(Jar j) { this.j = j; } @Override public void run() { while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } j.add(1); System.out.println("add 1"); } } } /** * 单例模式 */ class Dog1 { private com.test.java.Dog1 instance = null; private final Object lock = new Object(); private Dog1() { } public com.test.java.Dog1 getInstance() { if (instance == null) { synchronized (lock) { if (instance == null) { instance = new com.test.java.Dog1(); } } } return instance; } } enum EE {aa, bb, cc, dd} class Person implements Serializable { private String name; private int age; 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 Person(String name, int age) { this.name = name; this.age = age; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Person)) return false; Person person = (Person) o; return getAge() == person.getAge() && getName().equals(person.getName()); } @Override public int hashCode() { return Objects.hash(getName(), getAge()); } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } } class RePerson { String name; int age; public RePerson(String name, int age) { this.name = name; this.age = age; } public RePerson() { } public void eat() { System.out.println(name + "==" + age); } public void func(int i) { System.out.println(name + "vvvvvvvvvvvvvvvvvvv" + age + "/"+ i); } }

 

你可能感兴趣的:(大数据,Java)