javase部分重点,易出错的笔记

1.集合详解

https://blog.csdn.net/ZhengXinMing1998/article/details/104958234

2.多线程

2.1创建多线程的方式:
①继承Thread
②实现Runnable接口
实现Runnable接口创建多线程的好处:
a.避免了单继承的局限性。
b.增强了程序的扩展性,降低了程序的耦合性(解耦)。
2.2线程同步
①同步代码块:
synchronized (this){
}
②同步方法:
public synchronized void methodName(){
//锁对象默认是this
}
③静态同步方法
public static synchronized void methodName(){
//锁对象是本类的class属性
}
④Lock锁
Lock l = new ReentrantLock();
l.lock();

l.unlock();
2.3线程状态
new(新建) runnable(可运行) blocked(锁阻塞) waitting(无限等待) timed waitting(计时等待) terminated(死亡状态)
2.4线程池的两种创建方式及销毁

 ExecutorService es = Executors.newFixedThreadPool(2);
        ExecutorService es2 = new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                60L, TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>());
        es2.submit(new RunnableImpl());
        es2.submit(new RunnableImpl());
        es2.submit(new RunnableImpl());

        es2.shutdown();

2.4Lambda表达式

 new Thread(()-> System.out.println(Thread.currentThread().getName()+"创建了多线程")).start();

省略规则:a.小括号内参数类型可省略;
b.若小括号内有且仅有一个参,则小括号可省略;
c.若大括号有且仅有一个语句,则无论是否有返回值,都可省略大括号、returen关键字及语句分号(注意:要省略{},return,分号必须一起省略)。
Lambda的使用前提:a.使用Lambda必须有接口,且要要求接口中有且仅有一个抽象方法。
b.使用Lambda必须具有上下文推断。也就是方法的参数或局部变量类型必须为Lambda对应的接口类型。

3.IO流

3.1字节流:

/**
 * 字节流
 * 若进行汉字传输会出现乱码
 */
public class ZiJieDemo {
    public static void main(String[] args) throws IOException {
        File file = new File("d:\\a.txt");
        FileOutputStream fos = new FileOutputStream(file);
        FileInputStream fis = new FileInputStream(file);

        /*fos.write(97);//a
        System.out.println(fis.read());//97
        System.out.println((char)fis.read());//a*/

        byte[] bytes = {65, 66, 67, 68, 69};//一次写多个字节,若写的第一个字节是正数(0-127),那么显示的时候会查询ASCII表;若为负数,那么前两个字节组成一个中文显示,查询系统默认码表(GBK)
        fos.write(bytes);
        fos.write(bytes, 0, 2);//off:数组开始索引 len:写几个字节
        System.out.println(fis.read());

       /* byte[] bytes2 = "您好".getBytes();
        System.out.println(Arrays.toString(bytes2));//[-26, -126, -88, -27, -91, -67]   UTF-8三个字节一个中文,GBK两个字节一个中文
        for (int i = 0; i <11 ; i++) {
            fos.write(bytes2);
            fos.write("\r\n".getBytes());//换行符:windows:\r\n;    linux:/n;mac:/r

        }*/

        byte[] b = new byte[1024];
        int len = 0;
        while ((len = fis.read(b)) != -1) {
            //System.out.print((char) len);
            System.out.println(new String(b,0,len));
        }

        fos.close();
        fis.close();
    }
}

3.2字符流:

**
 * 字符流
 */
public class ZuFuDemo {
    public static void main(String[] args) throws Exception {

        //testReader();
        testWriter();
        testJDK7();
        testJDK9();
    }

    /**
     * JDK9新特性:
     * try的前边可以定义流对象
     * 在try的后边()中可直接引入流对象名称(变量名)
     * 在try代码执行完毕后,流对象也可释放掉,不用再写finally
     */
    private static void testJDK9() throws FileNotFoundException {
        FileReader fr = new FileReader("d:\\a.txt");
        try(fr){
            System.out.println((char)fr.read());
        }catch (IOException e){
            System.out.println(e);
        }
    }

    /**
     * JDK7新特性在try的后边可以增加一个(),在括号中可以定义流对象,那么这个流对象的作用域就在try中有效,
     * try中的代码执行完毕会自动把流对象释放,不用写finally
     * 格式:
     * try(定义流对象;定义流对象...){
     *      可能产生异常的代码
     * }catch(异常类变量 变量名){
     *异常的处理逻辑
     * }
     */
    private static void testJDK7() {
        try( FileReader fr = new FileReader("d:\\a.txt");){
            System.out.println((char)fr.read());
        }catch (IOException e){
            System.out.println(e);
        }

    }

    private static void testWriter(){

        //若文件不存在,会自动创建b.txt
        FileWriter fw = null;//append:续写开关。true:不会创建新的文件覆盖原文件,可续写;false:创建新的文件覆盖原文件
        try {
            fw = new FileWriter("d:\\b.txt",true);
            //fw.write(97);
            char[] c ={'a','b','c','d'};
            fw.write(c);
            fw.write(c,1,2);
            fw.write("\r\n");
            fw.write("ABCD");
            fw.write("ABCD",0,3);

            fw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fw!=null){
                try {
                    fw.close();//释放资源,会先把内存缓冲区中的数据刷新到文件中
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void testReader() throws Exception {
        FileReader fr = new FileReader("d:\\a.txt");
        System.out.println((char)fr.read());

        int len = 0;
        char[] c = new char[1024];
        while ((len=fr.read(c)) != -1){
            System.out.println(new String(c,0,len));
        }
    }

}

3.3拷贝

/**
 * 复制文件
 */
public class CopyDemo {
    public static void main(String[] args) throws Exception {
        //ziJieCopy();//若进行汉字传输会出现乱码
        ziFuCopy();//只适合拷贝文本文件,拷贝图片,音乐等会出错
    }

    private static void ziFuCopy() {
        try (FileReader reader = new FileReader("d:\\2.jpg"); FileWriter writer = new FileWriter("d:\\3.jpg")){
            char[] c = new char[1024];
            int len = 0;
            while ((len=reader.read(c)) != -1){
                writer.write(c,0,len);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    private static void ziJieCopy() {
        try(FileInputStream fis = new FileInputStream("d:\\1.jpg"); FileOutputStream fos = new FileOutputStream("d:\\2.jpg");){
            byte[] b = new byte[1024];
            int len = 0;
            while ((len = fis.read(b)) != -1){
                fos.write(b,0,len);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        //JDK7新特性trycatch后会自动关流
        //fis.close();
        //fos.close();
    }
}

3.4属性集
①Properties 类(HashTable的子类,表示了一个持久的属性集,Properties可保存在流中或从流中加载,属性列表中每个键及其对应值都是一个字符串。)
②Properties集合是一个唯一和IO流相结合的集合。
可使用Properties集合中的方法store,把集合中的临时数据持久化写入到硬盘中存储;
可使用load方法,把硬盘中保存的文件(键值对)读取到集合中使用;

public class Demo01Properties {
    public static void main(String[] args) {
        show03();
    }

    private static void show03() {
        Properties prop = null;
        try (FileReader fr = new FileReader("d:\\prop.txt")){
           prop = new Properties();
           prop.load(fr);
           //遍历properties集合
            Set<String> set = prop.stringPropertyNames();//返回此属性列表中的键集,相当于map集合中的keySet方法
            for (String key : set) {
                String value = prop.getProperty(key);
                System.out.println(key + "=" + value);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private static void show01() {
        Properties prop = new Properties();
        prop.setProperty("熊大", "12");
        prop.setProperty("熊二", "11");
        prop.setProperty("光头强", "22");
        prop.setProperty("翠花", "10");

        Set<String> set = prop.stringPropertyNames();//返回此属性列表中的键集,相当于map集合中的keySet方法
        for (String key : set) {
            String value = prop.getProperty(key);
            System.out.println(key + "=" + value);
        }
    }

    private static void show02() {
        Properties prop = new Properties();
        prop.setProperty("熊大", "12");
        prop.setProperty("熊二", "11");
        prop.setProperty("光头强", "22");
        prop.setProperty("翠花", "10");

        //创建字节/字符输出流对象,构造方法中绑定要输出的目的地
        //使用Properties集合中的方法store,把集合中的临时数据持久化写入到硬盘中存储;
        try(FileWriter fw = new FileWriter("d:\\prop.txt"); FileOutputStream fos = new FileOutputStream("d:\\prop.txt");) {
            prop.store(fw,"zifuliu");//comments:注释
            //prop.store(fos,"zijieliu");//会覆盖上面的
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3.5缓冲流

public class BufferedDemo {
    public static void main(String[] args) {
        //show1();
        show02();
    }

    private static void show02() {
        try (FileReader fr = new FileReader("d:\\3.txt");
             FileWriter fw = new FileWriter("d:\\4.txt");
             BufferedReader br = new BufferedReader(fr);
             BufferedWriter bw = new BufferedWriter(fw);) {
            /*bw.write("吉吉国王");
            bw.newLine();//换行
            bw.write("吉吉国王");
            System.out.println(br.readLine());*/

            /*int len = 0;
            char[] c = new char[1024];
            while ((len=br.read(c))!=-1){
                bw.write(c,0,len);
            }*/
            String line;
            while ((line=br.readLine())!=null){
                bw.write(line);
                bw.newLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void show1() {
        try (FileInputStream fis = new FileInputStream("d:\\1.txt");
             FileOutputStream fos = new FileOutputStream("d:\\2.txt");
             BufferedInputStream bis = new BufferedInputStream(fis);
             BufferedOutputStream bos = new BufferedOutputStream(fos)
             ) {
            //bos.write("郑新明".getBytes());
            byte[] b = new byte[1024];
            int len = 0;
            while ((len = bis.read(b)) != -1) {
                System.out.println(len);
                bos.write(b, 0, len);
            }

            //System.out.println(bis.read());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3.6转换流

/**
 *将GBK编码的文本文件转换为UTF-8编码的文本文件
 */
public class TransDemo {
    public static void main(String[] args) throws IOException {
        InputStreamReader reader = new InputStreamReader(new FileInputStream("d:\\GBK.txt"),"GBK");
        OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream("d:\\UTF-8.txt"),"UTF-8");
        //writer.write("你好");
        char[] c = new char[1024];
        int len = 0;
        while ((len=reader.read(c)) != -1){
            writer.write(c,0,len);
        }

        writer.close();
        reader.close();
    }
}

3.7序列化(被transient关键字修饰的变量不再能被序列化,一个静态变量不管是否被transient修饰,均不能被序列化。)

/**
 * static关键字:静态关键字
 *              静态优先于非静态加载于内存中,被static修饰的成员变量不能被序列化,序列化的都是对象
 *transient关键字:瞬态关键字
 *              被transient修饰的成员变量不能被序列化(无静态含义)
 */
public class XuLieHuaDemo {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //objectCopyTest();
        objectListCopyTest();
}

    private static void objectListCopyTest() throws IOException, ClassNotFoundException {
        ArrayList<Person> list = new ArrayList<>();
        list.add(new Person("熊二",11));
        list.add(new Person("熊二",11));
        list.add(new Person("熊二",11));
        list.add(new Person("熊二",11));

        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d:\\list.txt"));
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("d:\\list2.txt"));
        oos.writeObject(list);
//        System.out.println(ois.readObject());
        oos.writeObject(ois.readObject());

        oos.close();
        ois.close();
    }

    private static void objectCopyTest() throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d:\\person.txt"));
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("d:\\person2.txt"));
        oos.writeObject(new Person("熊大",12));
//        System.out.println(ois.readObject());
        oos.writeObject(ois.readObject());

        oos.close();
        ois.close();
    }
}

4.网络编程

网络通信协议

public class TCPClient {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("192.168.25.1", 8888);
        OutputStream outputStream = socket.getOutputStream();//网络字节输出流
        outputStream.write("你好,服务器".getBytes());

        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(bytes)) != -1){
            System.out.println(new String(bytes,0,len));
        }

        socket.close();
    }
}
public class TCPServer {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(8888);
        Socket socket = server.accept();

        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(bytes)) != -1){
            System.out.println(new String(bytes,0,len));
        }

        OutputStream outputStream = socket.getOutputStream();//网络字节输出流
        outputStream.write("收到谢谢,你好客户端".getBytes());

        socket.close();
        server.close();
    }
}
public class FileUploadTCPClient {
    public static void main(String[] args) throws IOException {
        //复制文件到服务器
        FileInputStream fis = new FileInputStream("d:\\a.txt");
        Socket socket = new Socket("192.168.25.1",8888);
        OutputStream os = socket.getOutputStream();

        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len=fis.read(bytes)) != -1){
            os.write(bytes,0,len);
        }
        socket.shutdownOutput();//(禁用此套接字的输出流)上传完文件,给服务器一个结束标记,解决阻塞问题

        //读取服务器回写的数据
        InputStream is = socket.getInputStream();
        while ((len = is.read(bytes)) != -1){
            System.out.println(new String(bytes,0,len));
        }

        socket.close();
        fis.close();
    }
}
public class FileUploadTCPServer {
    public static void main(String[] args) throws IOException {
        //接收客户端上传的文件
        ServerSocket serverSocket = new ServerSocket(8888);
        /**
         * 让服务器一直处于监听状态(死循环accept方法)
         */
        while (true){
            Socket socket = serverSocket.accept();
            /**
             * 使用多线程技术,提高程序效率
             * 有一个客户端上传文件,就开启一个线程,完成文件的上传
             */
            new Thread(()->{
                try {
                    InputStream is = socket.getInputStream();
                    File file = new File("e:\\upload");
                    if (!file.exists()){
                        file.mkdirs();
                    }
                    /**
                     * 自定义一个文件命名规则,防止同名的文件被覆盖
                     */
                    String fileName ="zxm"+System.currentTimeMillis()+ new Random().nextInt(999999)+".txt";

                    FileOutputStream fos = new FileOutputStream(file+"\\"+fileName);

                    int len = 0;
                    byte[] bytes = new byte[1024];
                    while ((len=is.read(bytes)) != -1){
                        fos.write(bytes,0,len);
                    }

                    //回写数据给客户端
                    OutputStream os = socket.getOutputStream();
                    os.write("上传成功".getBytes());

                    socket.close();
                    fos.close();
                }catch (IOException e){
                    e.printStackTrace();
                }

            }).start();
        }
        //serverSocket.close();
    }
}

*代码执行顺序:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值