关闭

JavaIO总结(二)

208人阅读 评论(0) 收藏 举报

19.将中文字符串按照指定编码表写入到一个文本文件。Java识别的字符数据使用的都是Unicode码表,但是FileWriter写入本地文件使用的是本地编码,也就是GBK码表。而OutputStreamWriter可使用指定的编码将要写入的字符编码成字节。
20.带编码:

public class IODemo{
    public static void main(String[] args) throws Exception {
        //FileWriter默认是GBK编码
        String s = "中国";
        FileWriter fw = new FileWriter("2.txt");
        System.out.println(fw.getEncoding().toString());
        fw.write(s);
        fw.flush();
        fw.close();
        //带编码的读取输出
        BufferedWriter bw = 
                new BufferedWriter(
                new OutputStreamWriter(
                new FileOutputStream("555.txt"),"utf-8"));
        bw.write("天地有正气");
        bw.flush();
        bw.close();
        BufferedReader br = 
                new BufferedReader(
                new InputStreamReader(
                new FileInputStream("555.txt"),"utf-8"));
        String line = br.readLine();
        System.out.println(line);
        br.close();
    }
}

21.使用转换流需要注意:1.源或者目的设备是字节流,但是操作的确实文本数据,可以使用转换流作为桥梁,提高对文本操作的便捷。2.一旦操作涉及到具体指定的编码时,必须使用转换流。
22.文件的操作,File类:

public class FileDemo{
    public static void main(String[] args) throws Exception {
        File file = new File("G:"+File.separator +"1.txt");
        //File file = new File("G:"+File.separator + "study"+File.separator+"1.txt");
        boolean b = file.createNewFile();
        System.out.println(b);
        System.out.println(file.getName());
        System.out.println(file.getAbsolutePath());
        System.out.println(file.getPath());
        System.out.println(file.getTotalSpace());
        System.out.println(file.length());
        System.out.println((new File(file.getParent())).list()[2]);
        System.out.println(file.isFile());
        System.out.println(file.isDirectory());
        File fileDemo = new File("g:"+File.separator+"Study"+File.separator+"Demo");
        b = fileDemo.mkdirs();
        System.out.println(b);
        fileDemo.renameTo(new File("g:"+File.separator+"Study"+File.separator+"1111"));
    }
}

23.获取隐藏文件

public class Demo2 {
    public static void main(String[] args) {
        //获取C盘目录下的隐藏文件
        File file = new File("D:\\");
        String[] s = file.list();
        System.out.println(s.length);
        File[] files = file.listFiles(new FileterByHidden());
        for (int i = 0; i < files.length; i++) {
            System.out.println(files[i]);
        }
        System.out.println(files.length);
    }
}
class FileterByHidden implements FilenameFilter{
    @Override
    public boolean accept(File dir, String name) {
        return (dir.isHidden());
    }

}

24.递归一个文件夹:

//递归一个文件夹
public class Demo2 {
    public static void main(String[] args) {
        File file = new File("G:\\Study");
        if (!file.exists())
            System.out.println("文件不存在");
        int num = 0;
        ListAll(file, num);
    }
    public static void ListAll(File file, int num) {
        sysFun(num);
        System.out.println(file.getAbsolutePath());
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                ListAll(files[i], ++num);
            }
            sysFun(num);
            System.out.println(file.getAbsolutePath());
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public static void sysFun(int num){
        StringBuilder sb = new StringBuilder();
        sb.append("|");
        for (int i = 0; i < num; i++) {
            sb.append("-");
        }
        System.out.print(sb.toString());
    }
}

25.求某一个数的二进制:

public class Demo2{
    public static void main(String[] args) {
        int num = 2;
        toBin(num);
    }
    public static void toBin(int num){
        if(num>0){
            toBin(num/2);
            System.out.print(num%2);
        }
    }
}

26.递归求和:

public class Demo2{
    public static void main(String[] args) {
        System.out.println(getSum(5));
    }
    public static int getSum(int num){
        if(num == 0)
            return 0;
        return num+getSum(--num);
    }
}

27.删除一个带内容的目录:

public class Demo2 {
    public static void main(String[] args) {
        File file = new File("G:\\Deo");
        deleteFile(file, 1);
    }
    public static void deleteFile(File file, int num) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                deleteFile(files[i], ++num);
            }
            sysFun(num);
            System.out.println("||||"+file.getAbsolutePath());
            file.delete();
        }

        sysFun(num);
        System.out.println("***"+file.getAbsolutePath());
        file.delete();

    }

    public static void sysFun(int num) {
        StringBuilder sb = new StringBuilder();
        sb.append("|");
        for (int i = 0; i < num; i++) {
            sb.append("-");
        }
        System.out.print(sb.toString());
    }
}

28.Properties类的基本增删改及与流的结合使用,模仿Load方法:

public class Demo2 {
    public static void main(String[] args) throws Exception{
        // Properties
        //增加
        Properties p = new Properties();
        p.setProperty("1", "1");
        p.setProperty("2", "2");
        p.setProperty("3", "3");
        p.setProperty("4", "4");
        p.setProperty("5", "5");
        p.setProperty("6", "6");
        //修改
        p.setProperty("1", "11");
        //迭代
        Set<String> names = p.stringPropertyNames();
        for (String obj : names) {
            System.out.println(obj + "=" + p.getProperty(obj));
        }
        //Properties集合和流对象的结合
        p.list(System.out);
        p.list(new PrintStream(new FileOutputStream("1.txt")));
        p.store(new FileWriter("2.txt"), "num+num");
        //读取
        p.load(new FileInputStream("2.txt"));
        p.list(System.out);
        p.load(new FileReader("1.txt"));
        p.list(System.out);
        //读取已有的配置文件到内存 修改给定值 然后重新存储
        p.setProperty("1", "11111111111111111");
        p.setProperty("3", "8888888888");
        p.store(new FileWriter("1.txt"), "num+num");
        p = myLoad(new FileReader("555.txt"));
        p.list(System.out);

    }
    //模拟Load方法
    public static Properties myLoad(Reader r) throws Exception{
        Properties prop = new Properties();
        int ch;
        String line = new String();
        StringBuilder sb = new StringBuilder();
        while((ch = r.read())!=-1){
            if(ch == '\r')
                continue;
            if(ch == '\n'){
                line = sb.toString();
                sb.delete(0, sb.length());
                if(line.split("=").length == 1)
                    continue;
                prop.setProperty(line.split("=")[0], line.split("=")[1]);
            }
            sb.append((char)ch);
        }
        return prop;
    }
}

29.软件计数器的使用;

public class Demo2 {
    public static void main(String[] args) throws Exception {
        //创建指向属性文件的
        File file = new File("1.ini");
        //第一次使用时候文件不存在 创建文件
        if (!file.exists())
            file.createNewFile();
        //读取属性
        Properties prop = new Properties();
        prop.load(new FileReader(file));
        String time = prop.getProperty("time");
        int count = 0;
        //非零说明使用过
        if (time != null) {
            count = Integer.parseInt(time);
            if (count == 3)
                throw new RuntimeException("试用次数已到,请注册交费,继续使用");
        }
        count++;
        //修改使用次数
        prop.setProperty("time", "" + count);
        //存储
        prop.store(new FileWriter("1.ini"), null);
    }
}

30.深度遍历一个文件夹,将其中固定后缀的文件路径写入一个文件中

public class Demo3 {
    public static void main(String[] args) throws Exception {
        // 文件
        File file = new File("G:\\Java");
        // 输出流
        FileWriter fw = new FileWriter("jilu.ini");
        diedai(file, fw);
        fw.close();
    }
    public static void diedai(File file, Writer w) throws Exception {
        File[] files = null;
        if (file.isDirectory()) {
            files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                diedai(files[i], w);
            }
        } else {
            if (file.getName().endsWith(".class")) {
                w.write(file.getAbsolutePath()+"\n");
                w.flush();
            }
        }
    }
}

31.PrintStream,PrintWriter可以直接操作输入流和文件,PrintStream为其他输出流添加了功能,使他们能够方便的打印各种数据值表示形式。PrintStream永远不会抛出IOException,而是,异常情况仅设置可通过checkError方法测试的内部标志。PrintStream打印的所有字符都是用平台默认字符编码转换为字节。在需要写入字符而不是写入字节的情况下,应该使用PrintWriter。示例:

public class Demo3 {
    public static void main(String[] args) throws Exception {
        // 打印流
        PrintStream ps = new PrintStream("1.txt");
        ps.write(97);
        ps.write('\n');
        ps.print(97);
        // 结合文件的读取打印
        PrintWriter pw = new PrintWriter(new FileWriter("2.txt"), true);
        PrintWriter pw2 = new PrintWriter(System.out, true);
        BufferedReader br = new BufferedReader(new InputStreamReader(
                new FileInputStream("555.txt")));
        String line = null;
        while ((line = br.readLine()) != null) {
            pw.println(line);
            pw2.println(line.toUpperCase());
        }
        pw.close();
        pw2.close();
    }
}

32.序列流:SequenceInputStream:对多个流进行合并。

public class Demo3{
    public static void main(String[] args) throws Exception{
        //多个读取文件的流
        List<FileInputStream> list = new ArrayList<FileInputStream>();
        list.add(new FileInputStream("1.ini"));
        list.add(new FileInputStream("1.txt"));
        list.add(new FileInputStream("2.txt"));
        list.add(new FileInputStream("555.txt"));
        Enumeration<FileInputStream> en = Collections.enumeration(list);
        SequenceInputStream sis = new SequenceInputStream(en);
        //输出流:
        BufferedOutputStream bis = new BufferedOutputStream(new FileOutputStream("new.txt"));
        byte[] buf = new byte[1024];
        int len = 0;
        while((len = sis.read(buf))!=-1){
            bis.write(buf, 0, len);
        }
        bis.close();
        sis.close();
    }
}

33.文件切割器:文件合成器。

public class Demo3 {
    private static int SIZE = 1024 * 1024 * 2;

    public static void main(String[] args) throws Exception {
        // //待切割文件
        // File file = new File("将军令.mp3");
        // //读取流
        // BufferedInputStream bis = new BufferedInputStream(new
        // FileInputStream(file));
        // BufferedOutputStream bos = null;
        // //缓冲
        // byte[] buf = new byte[SIZE];
        // int len = 0;
        // int count = 0;
        // while((len = bis.read(buf))!=-1){
        // count++;
        // bos = new BufferedOutputStream(new
        // FileOutputStream("part"+count+".part"));
        // bos.write(buf, 0, len);
        // bos.flush();
        // }
        // bos.close();
        // bis.close();
        // 合并文件
        File file = new File("G:\\Java\\C-S_Java\\Collection");
        FilenameFilter filenameFilter = new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                // TODO Auto-generated method stub
                return name.endsWith(".part");
            }
        };
        File[] files = file.listFiles(filenameFilter);
        List<FileInputStream> list = new ArrayList<FileInputStream>();
        for (int i = 0; i < files.length; i++) {
            list.add(new FileInputStream(files[i]));
        }
        Enumeration<FileInputStream> en = Collections.enumeration(list);
        SequenceInputStream sis = new SequenceInputStream(en);
        // 输出
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream("JJL.mp3"));
        byte[] buf = new byte[SIZE];
        int len = 0;
        while((len = sis.read(buf))!=-1){
            bos.write(buf, 0, len);
            bos.flush();
        }
        bos.close();
        sis.close();
    }
}

34.操作对象:ObjectInputStream,ObjectOutputStream。PS:操作的对象需要实现Serializable接口。通过实现java.io.Serializable接口以启用序列化功能,Serializable只是一个标记接口。未实现此接口的类将无法使其任何状态序列化或反序列化,可序列化的所有子类型都是可序列化的。要允许不可序列化的子类型序列化,可以假定该子类型复制保存和恢复超类型的公用,受保护的,可访问包字段的状态。仅在子类型扩展的类有一个可访问的无参数构造方法来初始化该类的状态,才可以假定子类型有此职责,如果不是这种情况,则声明一个类为可序列化类是错误的。在反序列化时,将使用该类的公用的或受保护的无参数构造方法初始化不可序列化的类的字段。序列化时不能写入所有超类的瞬态变量,静态变量。不希望被序列化的可以使用关键字transient。

class Person implements Serializable {
    private static final long serialVersionUID = 456789623;
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = 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 class ObjectStreamDemo {

    public static void main(String[] args) throws Exception {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
                "object.object"));
        oos.writeObject(new Person("大雄",18));
        oos.writeObject(new Person("胖虎", 21));
        oos.writeObject(null);
        oos.close();
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
                "object.object"));
        Person p = null;
        Object obj = null;
        while((obj = ois.readObject())!= null){
            p = (Person)obj;
            System.out.println(p.getName()+"--------"+p.getAge());
        }
        ois.close();
    }
}

35.RandomAccessFile:随机访问文件,自身具备读写方法。通过skipBytes(int x),seek(int x)等方法达到随机访问。该对象既能读又能写,内部维护了一个byte数组,并通过指针可以操作数组中的元素,可以通过getFilePointer方法获取指针的位置,通过seek方法设置指针的位置。相当于对字节输入流和输出流进行了封装。该对象的源或者目的都只能是文件。

public class IODemo {
    public static void main(String[] args) throws Exception {
        // RandomAccessFile输入和读取要对应 否则会独处错误的数据
        // 如果文件不存在则创建
        RandomAccessFile raf = new RandomAccessFile("1.txt", "rw");
        raf.write("大雄".getBytes());
        raf.writeChar('\n');
        raf.writeInt(55);
        raf.writeBoolean(false);
        raf.writeDouble(1.1);
        raf.close();
        //读取
        RandomAccessFile raf2 = new RandomAccessFile("1.txt", "rw");
        byte[] buf = new byte[4];
        raf2.read(buf);
        System.out.println(raf2.length());
        System.out.println(new String(buf));
        System.out.println(raf2.readChar());
        System.out.println(raf2.readInt());
        System.out.println(raf2.readBoolean());
        System.out.println(raf2.readDouble());
        raf2.close();
    }
}

36.管道流PipedInputStream和PipedOutputStream:输入输出可以直接进行连接,通过结合线程使用。

public class IODemo {
    public static void main(String[] args) throws Exception {
        // 管道流
        PipedInputStream pis = new PipedInputStream();
        PipedOutputStream pos = new PipedOutputStream();
        //输出流输出到管道里,输入流读取管道里面的内容进行处理
        pis.connect(pos);
        new Thread(new pisThread(pis)).start();
        new Thread(new posThread(pos)).start();
    }
}

class pisThread implements Runnable {
    private PipedInputStream pis;

    public pisThread(PipedInputStream pis) {
        this.pis = pis;
    }

    @Override
    public void run() {
        try {
            int num = 1;
            while (num<100) {
                num++;
                byte[] buf = new byte[1024];
                int len = pis.read(buf);

                String s = new String(buf, 0, len);
                System.out.println("s===" + s);
            }
            pis.close();
        } catch (Exception e) {
        } finally {
            try {
                if (pis != null)
                    pis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

class posThread implements Runnable {
    private PipedOutputStream pos;

    public posThread(PipedOutputStream pos) {
        this.pos = pos;
    }

    @Override
    public void run() {
        try {
            int num = 1000;
            while(num>0){
                pos.write("大雄来了".getBytes());
                num--;
                Thread.sleep(300);
            }
            pos.close();
        } catch (Exception e) {
        } finally {
            try {
                if (pos != null)
                    pos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

37.操作基本数据类型:DataInputStream,DataOutputStream。操作字节数组:ByteArrayInputStream,ByteArrayOutputStream.关闭字节数组输入输出流是无效的,因为它们没有调用系统底层资源,所有的操作都是在内存中完成。示例:

public class IODemo{
    public static void main(String[] args) throws Exception{
        //操作数据
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("2.txt"));
        dos.writeUTF("您好,我是哆啦A梦");
        dos.close();
        DataInputStream dis = new DataInputStream(new FileInputStream("2.txt"));
        String s = dis.readUTF();
        System.out.println(s);
        dis.close();
        //操作直接数组
        //没发现意义所在
        ByteArrayInputStream bais = new ByteArrayInputStream("大雄的伟大梦想".getBytes());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len = 0;
        while((len = bais.read(buf))!=-1){
            baos.write(buf,0,len);
        }
        System.out.println(baos.toString());
    }
}

38.编码表:常见的有:ASCII:美国标准信息交换码,用一个字节的7位可表示。ISO8859-1:拉丁码表。欧洲码表,用一个字节的8位表示。GB2312:中国的中文编码表。GBK:中国的中文编码表的升级,融合了更多的中文文字符号。Unicode:国际标准码,融合了多种文字。所有文字都用两个字节来表示,Java语言使用的就是Unicode。UTF-8:最多用三个字节来表示一个字符。

public class IODemo {
    public static void main(String[] args) throws Exception {
        String s = "哆啦A梦";
        // 编码
        byte[] buf = s.getBytes("gbk");
        System.out.println(new String(buf));
        buf = s.getBytes("utf-8");
        System.out.println(new String(buf));
        System.out.println(new String(buf,"utf-8"));
    }
}

39.将“联通”写入.txt的文件,经过gbk编码以后是11000001、10101010、11001101、10101000。正好符合utf-8的编码规则,所以记事本按照utf-8进行解码,从而出现了乱码现象。正确读取一串字符串。示例:gbk编码字符串,汉字的编码一般是两个字节都是负值,特殊的情况下,两个中的第二个会是正值,但是从最后一个开始读的话,碰到正值就结束,正好解决这样的情况,可以得到正确的结果。

public class IODemo {
    public static void main(String[] args) throws Exception {
        byte[] buf = "abc大雄jildj你好ls!".getBytes("gbk");
        System.out.println(buf.length);
        for (int i = 0; i < buf.length; i++) {
            int count = 0;
            for (int j = i; j>=0; j--) {
                if (buf[j] < 0)
                    count++;
                else
                    break;
            }
            if (count % 2 == 0)
                System.out.println("截取到第" + (i+1) + "个字符的正确答案是:"
                        + new String(buf, 0, i+1, "gbk"));
            else
                System.out.println("截取到第" +(i+1)+ "个字符的正确答案是:"
                        + new String(buf, 0, i, "gbk"));
        }
    }
}

40.定义一个使用最大字节数来读取子串,使用utf-8编码:代码如下:

public class IODemo {
    public static void main(String[] args) throws Exception {
        byte[] buf = "iiifkd我不知道sp大雄jfs来了!".getBytes("utf-8");
        System.out.println(new String(buf, 0, 1, "utf-8"));
        for (int i = 0; i < buf.length; i++) {
            int count = 0;
            for (int j = i; j >= 0; j--) {
                if (buf[j] < 0)
                    count++;
                else
                    break;
            }
            // System.out.println(new String(buf,0,i+1,"utf-8"));
            // 最后一个为正或者是多个连续的3或多个连续的2
            if (count % 3 == 0)
                System.out.println("截取到第" + (i + 1) + "个字符的正确答案是:"
                        + new String(buf, 0, i + 1, "utf-8"));
            // 两个连续的2
            else if (count % 3 == 1)
                System.out.println("截取到第" + (i + 1) + "个字符的正确答案是:"
                        + new String(buf, 0, i, "utf-8"));
            //
            else
                System.out.println("截取到第" + (i + 1) + "个字符的正确答案是:"
                        + new String(buf, 0, i - 1, "utf-8"));
        }
    }
}

——————It’s All.————————————–

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2444次
    • 积分:139
    • 等级:
    • 排名:千里之外
    • 原创:12篇
    • 转载:0篇
    • 译文:0篇
    • 评论:1条