【学习笔记】Java入门之API复习小结

本文详细探讨了Java中的字符串(String)、BigDecimal对象的创建和使用,以及StringBuffer与StringBuilder的对比,涉及字符序列操作和IO流的基础知识,包括文件操作、线程、集合和文件流处理。

目录

0.Integer

1.BigDecimal

2.String 

1.基本特点:

2.String中有一个属性:(这个挺重要的)

 3.String的创建方式

 4.练习:很有意思

 5.String的常用方法

 3.StringBuffer

1.一些属性:

2.StringBuffer和String的区别:(很重要!!!!!)

3.StringBuffer的一些方法和练习

4.StringBuilder

5.String,StringBuffer,StringBuilder的区别

 6.Arrays

7.集合

1. collection 接口的常用方法​

2.Collection接口遍历元素的方式

1.Iterator 

2.增强for循环

2.List接口的方法

3.ArrayList底层源码剖析(难!) 

 4.Vector 

5. LinkedList

6.HashSet

equals和hashcode

7.Map的6大遍历方式

8.Map小练习

9.Collection 总结

8.线程

1.两种创建方式:

2.线程插队:

3.守护线程:

4.线程的七大状态 

5. 线程同步机制-Synchronized

6.线程小练习:

9.IO流

1.文件

1.文件创建方式

2.常用的文件操作

2.IO流原理及流的分类

1.IO流原理:

2.流的分类:

3.几个输入输出流:

1.FileInputStream

2.FileOutPutStream

3.FileReader,FileWriter

4.BufferedReader,BufferedWriter

5.BufferedInputStream,BufferedOutputStream:

6.ObjectInputStream,ObjectOutputStream


0.Integer

1.封箱和拆箱
package API;
/*下面全是精华,慢慢的细节~~~~~*/
public class sealBox {
    public static void main(String[] args) {
        int n1=100;
        //手动封箱
        Integer i1 = new Integer(n1);
        Integer i3 = new Integer(n1);
        System.out.println(i1==i3);
        //在-128~127范围内,相同的数据只会存一次,后续再存都是使用之前存过的数据*
        /*这个重要!!!!!!!!!!!!!!*/
        Integer i2 = Integer.valueOf(n1);
        Integer i4 = Integer.valueOf(n1);
        System.out.println(i2==i4);//true
        //满足高效效果的3个条件:Integer valueOf() -128~127
        n1=300;
        Integer i5 = Integer.valueOf(n1);
        Integer i6 = Integer.valueOf(n1);
        System.out.println(i5==i6);//false
        /*只要有八大基本数据类型,就是比较数值是否相等*/
        int A=127;Integer a1=127;
        System.out.println(A==a1);
        int B=128;Integer a2=128;
        System.out.println(B==a2);

        char c='a';Character cc='a';
        System.out.println(c==cc);

        //只有Integer才有高效效果,Double没有
        Double d2 =  Double.valueOf(3.14);
        Double d22 = Double.valueOf(3.14);
        System.out.println(d2 == d22);//false
        //自动封箱拆箱
        Integer a=3;
        int i=a;
        //输出1.0,注意
        Object o=true?new Integer(1):new Double(2.0);
        System.out.println(o);//1.0,
    }
}

1.BigDecimal

使用方式:

BigDecimal(String val)
将String类型字符串的形式转换为BigDecimal,通常后面拼接个空字符串就行了

 使用代码:

package BigDecimal;

import java.math.BigDecimal;
import java.util.Scanner;

public class BigDecimalTest {
    public static void main(String[] args) {
        System.out.println("input1");
        double d1=new Scanner(System.in).nextDouble();
        System.out.println("input2");
        double d2=new Scanner(System.in).nextDouble();

        BigDecimal b1 = new BigDecimal(d1 + "");
        BigDecimal b2 = new BigDecimal(d2 + "");
        BigDecimal b3;
        b3=b1.add(b2);
        System.out.println(b3);
        b3=b1.divide(b2,3);
          /*divide(m,n,o)
        m是要除以哪个对象,n指要保留几位,o指舍入方式(比如四舍五入)*/
        System.out.println(b3);
        b3=b1.subtract(b2);
        System.out.println(b3);
        b3=b1.multiply(b2);
        System.out.println(b3);
        System.out.println("*****下面不精准*********");
        System.out.println(d1+d2);
        System.out.println(d1-d2);
        System.out.println(d1*d2);
        System.out.println(d1/d2);
    }
}

2.String 

1.基本特点:

注:

一个字符不管是字母还是汉字都是占2个字节。char也是两个字节。

 CharSequence:String可以串型化,在网络上传输。

Comparable:字符串可以比较大小

String还有很多构造器

2.String中有一个属性:(这个挺重要的)

存放字符串内容,所以String底层是char,注意是final类型,不可修改:指的是value不能指向新的地址,但是单个字符的内容是可以变化的。

final类型的value已经指向了一块内存空间的数据,不能再指向新的地址

如果不是final类型就可以赋值了

 3.String的创建方式

韩顺平的课讲的真好 

 4.练习:很有意思

1.

        String s1="hsp";
        String s2="hsp";
        String s3=new String("hsp");
        System.out.println(s1==s2);//true
        System.out.println(s1==s3.intern());//true,intern返回常量池中的地址
        System.out.println(s3==s3.intern());//false,s3指向的是堆,后面那个指向的是常量池中的地址

2. 

        Person p1 = new Person();
        p1.name="hsp";
        Person p2 = new Person();
        p2.name="hsp";
        System.out.println(p1.name.equals(p2.name));//true
        System.out.println(p1.name==p2.name);//true 都指向常量池中的hsp
        System.out.println(p1.name=="hsp");//true 都指向常量池中的hsp

        String s1=new String("hsp");
        String s2=new String("hsp");
        System.out.println(s1==s2);//false

3. 

        String a="hello";
        String b="abc";
        String c= a + b;//c执行过程中又创建了一个对象,这个对象的值指向“helloabc”
        System.out.println(c == "helloabc");//false,c指向的是一个对象,看底层源码
        //对象的值再指向常量池,“helloabc”直接在常量池中所以不一样
        String d="hello"+"abc";//d直接指向常量池
        System.out.println(c==d);//false
        System.out.println(d=="helloabc");//true.常量比较的时候直接看常量池

4.

 5.String的常用方法

import java.util.Arrays;

/*本类用来测试String类的常用方法*/
public class TestString2 {
    public static void main(String[] args) {
        //1.创建字符串
        String s1 = "abc";

        char[] values = {'a','b','c'};
        String s2 = new String(values);

        //2.测试常用方法
        /*String重写了hashCode(),是根据字符串的内容生成哈希码值,而不是根据地址值生成
        * 所以虽然s1与s2一个在堆的常量池中,一个在堆中,它两的哈希码值一样*/
        System.out.println(s1.hashCode());//96354
        System.out.println(s2.hashCode());//96354

        System.out.println(s1.equals(s2));//true,重写了,比较的是具体内容

        System.out.println(s1.toString());//不需要写,底层会自动调用s1对象的toString()
        System.out.println(s1);//abc,String重写了toString(),直接打印的是串的具体内容

        System.out.println(s1.length());//3,查看当前字符串的长度
        System.out.println(s1.toUpperCase());//ABC,将本字符串转为全大写
        System.out.println(s1.toLowerCase());//abc,将本字符串转为全小写
        System.out.println(s1.startsWith("a"));//true,判断本字符串是否以指定元素a开头
        System.out.println(s2.endsWith("a"));//false,判断本字符串是否以指定元素a结尾

        System.out.println(s1.charAt(0));//a,根据下标获取本字符串中对应的元素

        String s3 = "abcbdbba";
        System.out.println(s3.indexOf("b"));//1,返回本字符串中指定元素第一次出现的下标
        System.out.println(s3.lastIndexOf("b"));//6,返回本字符串中指定元素最后一次出现的下标

        System.out.println(s2.concat("cxy"));//abccxy,将指定字符串拼接到本字符串的结尾
        System.out.println(s2);//abc,说明上面的拼接是临时的,不会改变原串的内容

        String s4 = s2.concat("aaa");//如果想要多次使用拼接后的结果,需要定义一个字符串来保存结果
        System.out.println(s4);//abcaaa

        String s5 = "afbfcfdfe";
        //返回值类型是String[],所以需要使用Arrays.toString()打印
        //以指定字符作为分割符,分割当前的字符串
        //我们只是直接打印了split()的结果,没有使用变量保存
        System.out.println(Arrays.toString(s5.split("f")));//[a, b, c, d, e]

        //由于split()的返回值类型是String[],所以我们执行这个方法,可以拿到这个方法的返回值
        //所以a数组就是这个方法执行以后得到的结果,只不过我们保存下来了
        String[] a = s5.split("f");
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }

        String s6 = "       hh hhh      ";//去除本字符串首尾两端的空格
        System.out.println(s6.trim());//hh hhh

        String s7 = "abcdefgh";
        System.out.println(s7.substring(3));//defgh,从指定下标处截取子字符串[3,结束]
        System.out.println(s7.substring(3,6));//def,从指定下标处截取子字符串[3,6)含头不含尾

        System.out.println(String.valueOf(10));//10,将int类型的参数10转为String类型
        System.out.println("20"+10);//2010,String与int拼接
        System.out.println(20+10);//30,int与int相加
        System.out.println(String.valueOf(80)+10);//8010,将int类型的参数80转为String类型,所以拼接

        byte[] bs = s7.getBytes();//将指定字符串转为byte[]
    }

 3.StringBuffer

1.一些属性:

1.StringBuffer继承父类:AbstractStringBuilder, 有属性 char[] value, 不是final类型,所以建立出的变量存在堆中,不是常量池中。同时是个fianl类不可以被继承。

2.StringBuffer和String的区别:(很重要!!!!!)

3.StringBuffer的一些方法和练习

package StringBufferTest;

import java.util.Scanner;

public class BufferTest {
    public static void main(String[] args) {
        String s2="abc";
        StringBuffer s1 = new StringBuffer(s2);
        //增
        System.out.println(s1.append(","));
        System.out.println(s1.append("123"));
        System.out.println(s1.append(true));
        System.out.println(s1.append(100));
        //删
        System.out.println(s1.delete(10,12));//删除[10.12)的数据
        //改
        System.out.println(s1.replace(0,2,"我还行"));//调换
        //查
        System.out.println(s1.indexOf("我还行"));//查找第一次出现的地方
        System.out.println(s1.indexOf("1"));
        System.out.println(s1.length());
        //插
        System.out.println(s1.insert(0,"还可以哦"));//在第0位插入,后面自动保留
        /*小练习,很有意思!!!!*/
        String str1=null;
        StringBuffer str2 = new StringBuffer();
        System.out.println(str2.append(str1));//底层是创建了个'n''u''l''l'数组.所以下面是4
        System.out.println(str2.length());//
        //System.out.println(str1.length());//这样写会报错
        System.out.println(str2);//null
        System.out.println(str1);//null
        //StringBuffer str3 = new StringBuffer(str1);//底层代码:super(str.length() + 16);
        //抛出空指针异常                             // str长度为空所以这边会报错跟上面注释的那一行一样
        /*又一个小练习,很有意思!!!!!!!!!!!
        * 要求:1234.56-->1,234.56
        *所以要用StringBuffer中的insert,接受一个string转成StringBuffer
        * */
        System.out.println("input");
        String str=new Scanner(System.in).nextLine();
        StringBuffer sb = new StringBuffer(str);
        //找到小数点,向前移动三位即可
//        int i=sb.lastIndexOf(".");
//        while(i-3>0) {
//            i = i - 3;
//            sb = sb.insert(i, ",");
//        }
        for(int i=sb.lastIndexOf(".");i-3>0;i=i-3){
            sb=sb.insert(i-3,",");
        }
        System.out.println(sb);
    }
}

4.StringBuilder

StringBuilder是StringBuffer的一个简易替换,但不是线程安全,多线程使用时有风险,所以单线程优先使用StringBuilder,比StringBuffer快。

主要操作append和insert方法。

5.String,StringBuffer,StringBuilder的区别

韩顺平老师写的真好

 6.Arrays

用一个匿名内部类进行排序

package ArraysTest;

import java.util.Arrays;
import java.util.Comparator;

public class bookdemo {
    public static void main(String[] args) {
        Book[] book=new Book[4];
        book[0]=new Book("红楼梦",100);
        book[1]=new Book("西游记",120);
        book[2]=new Book("三国演义",10);
        book[3]=new Book("java从入门到如土",230);

        //sort(book);
        Arrays.sort(book, new Comparator<Book>() {
            @Override
            public int compare(Book o1, Book o2) {
                double price=o1.getName().length()-o2.getName().length();
                if (price>0)//正负值决定正序和倒叙,看底层源码
                    return 1;
                else if(price<0)
                    return -1;
                else
                    return 0;
            }
        });
        System.out.println(Arrays.toString(book));
    }

//    private static void sort(Book[] book) {
//        double t;
//        for (int i = 0; i < book.length-1; i++) {
//            for (int j = 0; j < book.length-i-1; j++) {
//                if (book[j].price>book[j+1].price){
//                    t=book[j].price;
//                    book[j].price=book[j+1].price;
//                    book[j+1].price=t;
//                }
//            }
//        }
//    }
}
class Book{
     private String name;
     private double price;

    public Book(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}

7.集合

数组:1.长度指定不能更改 2.保存的元素为同一类型3.增删麻烦

在这里插入图片描述

 Collection 和List都是接口,接口不能实例化,所以一般多态形式

1. collection 接口的常用方法

2.Collection接口遍历元素的方式

1.Iterator 

collection继承了iterator接口

public class IteratorDemo {
    public static void main(String[] args) {
        Collection c=new ArrayList();
        c.add(new Book("红楼梦","曹雪芹",12.8));
        c.add(new Book("西游记","吴承恩",19.9));
        c.add(new Book("balabala","wowowo",112.9));
        c.add(new Book("xibaxiba","mimim",1230.9));
        Iterator i = c.iterator();
//        while(i.hasNext()){
//            System.out.println(i.next());
//        }
        //快捷键 itit+回车
        while (i.hasNext()) {
            Object next =  i.next();
            System.out.println(next);
        }
        System.out.println(i.hasNext());
        //当退出while循环后,这时iterator指向最后的元素
        //如果希望再次遍历需要重置迭代器--》  Iterator i = c.iterator();
    }
}

2.增强for循环

底层就是个迭代器,也可以在数组上使用

for (Object book:c) {
    System.out.println(book);
}
/*普通数组*/
int[] n={1,23,3,4,5};
for (int m:n) {
    System.out.println(m);
}

2.List接口的方法

3.ArrayList底层源码剖析(难!) 

看代码,这边走的是ArrayList的无参构造,没有初始化容量,所以elementDate赋值为0

看上面,从ArrayList建立第一个元素开始即:list.add(0):自动装箱转成Integer

  

 size一开始是0,miniCapacity是1,是需要的最小容量,这一步需要去判断一下容量是否够

先去计算一下最小容量,一般初始从0开始时才会用到

 如果element为空,则把miniCapacity赋值为10,即:将一开始所需要的最小容量变为10,即使只有一个元素也最低需要10。这边就是初始化的时候才会执行

 如果需要的最小容量-当前数据长度>0,说明当前数据长度不够,要扩容,去执行扩容方法

当前elementDate.length为0,赋值为oldCapacity,然后扩容1.5倍给new的,但此时还是0,

所以赋值为10,第一次执行比较特殊。再用copyof方法扩容。

 

 4.Vector 

5. LinkedList

LindedList的全面说明:

1.LindedList底层实现了双向链表和双端队列的特点,

2.可以添加任意元素(元素可以重复),包括null;

3.线程不安全,没有实现同步

妈的 下面的笔记没保存 丢了;我去 写了一天了 没了 哭死 QAQ

6.HashSet

底层是个HashMap,添加数据的时候会去比较 用equals方法见下面代码 

        Set s=new HashSet();
        System.out.println(s.add("hsp"));//t
        System.out.println(s.add("hsp"));//f
        System.out.println("******");
        Dog dog1 = new Dog("jack");//t
        Dog dog2 = new Dog("jack");//t->f重写equals会变成 f

equals和hashcode

hashmap底层添加元素的时候会先拿地址值获取一个hashcode

如果添加相同的对象,属性值也一样的话,这个时候不重写hashcode,就是两个地址值,会在table里开辟两块地方取存放加入的k-v,重写之后,就在第一个table里的链表后面再加,这个时候再判断equals比较内容是否相同。

我觉得不存在什么为什么重写equals也要重写hashcode,我觉得这两个重写没有先后顺序,是一体的,非要说顺序,我认为也是重写hashcode在前,equals在后

7.Map的6大遍历方式

第一组 取出key,通过ke点出value 
第二组 取value
第三组 取出Entry 再一一获取 key-value
        Map map=new HashMap();
        map.put("no1","hsp");
        map.put("no2","hspn");
        map.put("no3","hspnb");
        Set keySet = map.keySet();
        //第一组 取出key,通过ke点出value 1.增强for
        System.out.println("1111111111");
        for (Object key: keySet) {
            System.out.println(key+"-"+map.get(key));
        }
        //2.迭代器
        System.out.println("2222222222222");
        Iterator iterator = keySet.iterator();
        while (iterator.hasNext()){
            Object key = iterator.next();
            System.out.println(key+"-"+map.get(key));
        }
        System.out.println("3333333333333333");
            //第二组 取value
        // 3.把value取出
        Collection valuesSet = map.values();//这边可以使用所有collection方式
        for (Object value: valuesSet) {
            System.out.println(value);
        }
        System.out.println("444444444444");
        //4.value取出
        Iterator iterator1 = valuesSet.iterator();
        while (iterator1.hasNext()) {
            Object next =  iterator1.next();
            System.out.println(next);
        }
        System.out.println("55555555555");
        //第三组取出 Entry 再一一获取 key-value
        // 5.EntrySet获取
        Set set = map.entrySet();
        for (Object entry:set) {
            //把entry转成Map.Entry 这个类里面才有getValue()方法
            Map.Entry entry1 = (Map.Entry) entry;
            Object value = entry1.getValue();
            Object key = entry1.getKey();
            System.out.println("key="+key+",value="+value);
        }
        //6.Entry 迭代器
        System.out.println("666666666666");
        Iterator iterator2 = set.iterator();
        while (iterator2.hasNext()) {
            Object entry =  iterator2.next();
            Map.Entry entry3=(Map.Entry)entry;
            System.out.println(entry3.getKey()+"-"+entry3.getValue());
        }

8.Map小练习

HashMap hashMap = new HashMap();
employ e1 = new employ(1, "hsp",182);
employ e2 = new employ(2, "hspnbnb",1900);
employ e3 = new employ(3, "hspnb",2000);

hashMap.put(e1.getId(),e1);
hashMap.put(e2.getId(),e2);
hashMap.put(e3.getId(),e3);
Collection values = hashMap.values();
//直接取value
for (Object o:values) {
    employ e=(employ) o;
    if (e.getSalary()>1800){
        System.out.println(e);
    }
}
//迭代器
Iterator iterator = values.iterator();
while (iterator.hasNext()) {
    Object next =  iterator.next();
    employ ee=(employ) next;
    if (ee.getSalary()>1800)
    System.out.println(ee);
}
System.out.println("==========");
//entry
Set entrySet = hashMap.entrySet();
Iterator iterator1 = entrySet.iterator();
while (iterator1.hasNext()) {
    Object entry =  iterator1.next();
    Map.Entry mapEntry=(Map.Entry) entry;
    employ e = (employ) mapEntry.getValue();
    if ( e.getSalary()>1800){
        System.out.println(e);
    }
}

9.Collection 总结

8.线程

1.两种创建方式:

1.继承Thread 2.实现Runnable接口

2.线程插队:

        Thread t1 = new Thread(new Son());
        for (int i = 0; i < 10; i++) {
            System.out.println("hi~"+i+Thread.currentThread().getName());
            Thread.sleep(1000);
            if (i==5){
                t1.start();
                t1.join();//将其插入main线程中,执行完再执行main
            }
        }

3.守护线程:

主线程结束后,把子线程也给结束

Thread t1 = new Thread(new Son());
t1.setDaemon(true);//设置为守护线程

4.线程的七大状态 

 Runnable中还有Ready和Running两种状态

5. 线程同步机制-Synchronized

保证数据在任何同一时刻,最多有一个线程访问,以保证数据的完整性。

也可以这样理解:

线程同步:即当有一个线程对内存地址进行操作时,其他线程都不可以对这个内存地址进行操作,直到该线程完成操作,其他线程才能对这个内存地址进行操作。

 具体实现方法:

6.线程小练习:

1. 

    public static void main(String[] args) throws InterruptedException {
        RanNumber number = new RanNumber();
        Thread thread = new Thread(number);
        thread.start();
        B b = new B(number);
        b.start();
    }

class RanNumber implements Runnable{
    int ranNum;
    private boolean flag=true;

    public void setFlag(boolean flag) {
        this.flag = flag;
    }
    @Override
    public void run() {
        while (flag){
            System.out.println((int)(Math.random()*100 + 1));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class B extends Thread{
    private RanNumber a;

    public B(RanNumber a) {
        this.a = a;
    }
    @Override
    public void run() {
        //接受用户收入
        while (true) {
            System.out.println("input,Q-exit:");
            char input = new Scanner(System.in).next().toUpperCase().charAt(0);
            if (input=='Q'){
                a.setFlag(false);
                break;
            }
        }
    }
}

2.

        AB ab = new AB();
        Thread thread = new Thread(ab);
        Thread thread1 = new Thread(ab);
        thread.start();
        thread1.start();
class AB implements Runnable{
     int money = 10000;
     Object o=new Object();

    @Override
    public void run() {
        while (true) {
            synchronized (o) {
                if (money <= 0) {
                    System.out.println("no");
                    break;}
                money -= 1000;
                System.out.println(Thread.currentThread().getName() + "取1000,余额" + money);
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

9.IO流

1.文件

文件在java内存中以流的形式存在

1.文件创建方式

1.File(String pathname) 

new File()时,只是在内存中创建了一个file对象,没有存入内存,createNewFile是将文件写入磁盘中。

1.第一种方式
String filePath="e:\\news1.txt";
File file = new File(filePath);
try {
    System.out.println(file.createNewFile());
} catch (IOException e) {
    e.printStackTrace();
}
2.第二种方式
new File("e:\\1.txt").createNewFile();

2.File(File parent, String child)

 File ParentFile = new File("e:\\");
 String child="new2.txt";
 new File(ParentFile,child).createNewFile();

3.File(String parent, String child)

new File("e:\\","new3.txt").createNewFile();

2.常用的文件操作

基本操作:

//获取文件信息
File file = new File("e:\\news1.txt");
System.out.println(file.getName());//获取文件名
System.out.println(file.getAbsoluteFile());//绝对路径
System.out.println(file.getParentFile());//父目录
System.out.println(file.length());//文件大小,
// UTF-8:一个英文字母一个字节,一个汉子3个字节
System.out.println(file.exists());//是否存在
System.out.println(file.isFile());//是否文件
System.out.println(file.isDirectory());//是否目录

常用文件操作

//判断 "d:\\news1.txt"是否存在,存在就删除
//后缀名去掉就是目录,对目录进行操作
String filePath="d:\\news1.txt";
File file = new File(filePath);
file.createNewFile();
System.out.println(file.exists());
if (file.exists()){
    System.out.println(file.delete());
}
System.out.println(file.exists());

2.IO流原理及流的分类

1.IO流原理:

1.Input,Output是非常实用的技术,用于数据传输,读写文件,和网络通讯等。

2.java程序中,对数据输入输出操作,以“流(Stream)”的形式存在。

3.java.io包下提供了各种流和接口,

4.输入,从磁盘读入到内存

5.输出,从内存输出到磁盘

2.流的分类:

字节流:

字节输入流:InputStream

字符输入流:OutputStream

字符流:

字符输入流:Reader

字符输出流:Writer

img

3.几个输入输出流:

1.FileInputStream

关系继承图:

两种使用方法:

1.效率不高

int| read()

从此输入流中读取一个数据字节。返回:下一个数据字节;如果已到达文件末尾,则返回 -1

即:每次只读取一个字节,返回值就为读取到的那个字节?

    String filePath = "e:\\hello.txt";
    int readDate = 0;
    FileInputStream fileInputStream = null;
    try {
       fileInputStream = new FileInputStream(filePath);
        //返回-1表示读取完毕
        while ((readDate = fileInputStream.read()) != -1) {
            System.out.print((char) readDate);
        }
    }finally {
            fileInputStream.close();
    }
}

2.高效:

int|read(byte[] b)

从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。返回值为读取长度,字节数

即:将读取的数据放入byte数组中,一次最多度b.length个字节,再将每次读取的长度返回

String filePath = "e:\\hello.txt";
FileInputStream fileInputStream = null;
byte[] buf=new byte[8];
int length=0;
try {
   fileInputStream = new FileInputStream(filePath);
    //返回-1表示读取完毕
    //返回读取到的长度,一次读取8个字节,
    while ((length=fileInputStream.read(buf)) != -1) {
        System.out.println(new String(buf,0,length));
    }

两者区别就是一个一次读取一个字节,一个一次读取指定数组长度的字节数。返回值一个为读取到的字节,一个为每次读取到的字节长度。

2.FileOutPutStream

创建文件,并将内容写入

fileOutputStream = new FileOutputStream(filePath);
//此时写入文件每次都会覆盖掉上一次建立好的文件
//fileOutputStream = new FileOutputStream(filePath,true);
//上面这样写的话,会在上一次写好的文件后面追加
fileOutputStream.write('a');
String str="hello world";//会在a后面接着写
//输出 ahello world
fileOutputStream.write(str.getBytes(StandardCharsets.UTF_8));

copy文件:

思路:先读入在写出

String filePath="C:\\Users\\Administrator\\Desktop\\1.jpg";
String filePath1="C:\\Users\\Administrator\\Desktop\\11.jpg";
FileOutputStream fileOutputStream=null;
FileInputStream fileInputStream=null;
byte[] buf=new byte[1024];
int readLen=0;
​
try {
     fileInputStream = new FileInputStream(filePath);//初始化一个流,从路径读取
     fileOutputStream = new FileOutputStream(filePath1);//初始一个流,准备输出到路径
    while ((readLen=fileInputStream.read(buf))!=-1){//可能一次读取不完所以用循环
        //读取完就写入,边读边写
        fileOutputStream.write(buf,readLen);
    }
    System.out.println("success");
} catch (IOException e) {
    e.printStackTrace();
}finally {//关流 释放资源
    if (fileInputStream!=null){
        try {
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (fileOutputStream!=null){
        try {
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3.FileReader,FileWriter

FileReader:

字符读入:跟上面的差不多

    
FileReader fileReader;
    char[] c=new  char[800];//一次读取800个字符
    int readLen=0;
    try {
         fileReader = new FileReader("e:\\hello.txt");
         while ((readLen=fileReader.read(c))!=-1){
             System.out.println(new String(c,0,readLen));
             //System.out.println(c);
         }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

FileWriter:

4.BufferedReader,BufferedWriter

按照字符操作,所以不要去操作二进制文件{声音,视频,doc,pdf等},否则可能造成文件损坏。

BufferedReader:

   
 String filePath="e:\\hello.txt";
    BufferedReader bufferedReader=null;
    try {
        bufferedReader= new BufferedReader(new FileReader(filePath));
        String s ;
        while ((s= bufferedReader.readLine())!=null){
            System.out.println(s);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        try {
            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

BufferedWriter:

追加时,在new FileWriter(filePath,true)里面加true:

    
String filePath="e:\\abc.txt";
    BufferedWriter bufferedWriter = null;
    try {
        bufferedWriter = new BufferedWriter(new FileWriter(filePath,true));
        bufferedWriter.write("abc");
    } catch (IOException e) {
        e.printStackTrace();
    }
    finally {
        try {
            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

copy:

String file1="e:\\hello.txt";
String file2="e:\\hello2.txt";
BufferedReader bufferedReader = null;
BufferedWriter bufferedWriter = null;
​
try {
    bufferedReader = new BufferedReader(new FileReader(file1));
    bufferedWriter = new BufferedWriter(new FileWriter(file2));
    String s=null;
    while( (s=bufferedReader.readLine())!=null){//读取到流
        bufferedWriter.write(s);//从流里输出
        bufferedWriter.newLine();
    }//插入换行符,默认不会换行

5.BufferedInputStream,BufferedOutputStream:

copy:

String filePath1="C:\\Users\\Administrator\\Desktop\\n.jpg";
String filePath2="C:\\Users\\Administrator\\Desktop\\nnn.jpg";
BufferedInputStream bufferedInputStream=null;
BufferedOutputStream bufferedOutputStream=null;
byte [] b=new byte[1024];
int len=0;
​
try {
     bufferedInputStream = new BufferedInputStream(new FileInputStream(filePath1));
     bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(filePath2));
     //len返回的是读取到的长度,一次读取多少次,就写入多少
    while ((len=bufferedInputStream.read(b))!=-1){
        bufferedOutputStream.write(b,0,len);
    }finally{}//记得要关流!!!!!

6.ObjectInputStream,ObjectOutputStream

序列化:在保存数据时,保存数据的值和数据类型。

反序列化:恢复数据时,恢复值和数据类型。

能被序列化:要实现Serializable接口(标记接口,无方法)

序列化:写入文件,output

ObjectOutputStream

String filePath="e:\\data.txt";
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
//序列化到 filePath="e:\\data.txt"
oos.write(123); 
oos.writeUTF("王海鑫");
oos.writeObject(new Dog("we",12));
oos.close();//关流

反序列化:将文件中数据传输到java内存,input

ObjectInputStream 注意顺序一致

String filePath="e:\\data.txt";
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));
//读取,反序列化顺序需要与序列化顺序一致
System.out.println(ois.readInt());
System.out.println(ois.readUTF());
try {
    Object o = ois.readObject();
    System.out.println(o.getClass());
    System.out.println(o);
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}
ois.close();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值