zoukankan      html  css  js  c++  java
  • java入门篇12 --- IO操作

    在jiava中InputStream跟OutputStream分别代表输入流跟输出流,接下来来看一下IO的相关操作

    首先来看一下如何操作文件

    import java.io.File;
    import java.io.FilenameFilter;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    
    public class HelloWorld {
        public static void main(String[] args) throws Exception {
            File f = new File("./src/text.txt");
            System.out.println(f.isFile());  // true
            System.out.println(f.getPath());  // 获取构造方法的传入路径 ./src/text.txt
            System.out.println(f.getAbsolutePath());  // 获取绝对路径 /Users/***/Desktop/demo/javaDemo/./src/text.txt
            System.out.println(f.getCanonicalPath());  // 获取规范路径 /Users/***/Desktop/demo/javaDemo/src/text.txt
            File f1 = new File("./src");
            System.out.println(f1.isFile());  // false 判断是否是文件
            System.out.println(f1.exists());  // true  判断是否存在
            System.out.println(f1.isDirectory());  // true  判断是否是文件夹
            System.out.println(f1.getName());  // src  获取名字
            // 可以自定义文件过滤方式
            File[] f2 = f1.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    return name.endsWith(".xml") || name.endsWith(".txt");
                }
            });
            if (f2 != null) {
                for (File ff : f2) {
                    System.out.println(ff);
                }
            }  // ./src/logback.xml  ./src/text.txt
            // Path
            Path p = Paths.get(".", "src");  // 路径拼接
            System.out.println(p.toAbsolutePath());  // /Users/****/Desktop/demo/javaDemo/./src
            File f3 = p.toFile();  // 转化为文件
            System.out.println(f3.isDirectory());  // true
        }
    }

    好了,文件跟路径的一些基本操作输完了,现在来看一下流输入和流输出

    import java.io.*;
    import java.nio.charset.StandardCharsets;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipInputStream;
    import java.util.zip.ZipOutputStream;
    
    public class HelloWorld {
        public static void main(String[] args) throws Exception {
            // 初始化一个流
            InputStream f = new FileInputStream("./src/text.txt");
            for (; ; ) {
                int n = f.read();
                // 如果返回值为-1,证明文件读取完毕
                if (n == -1) {
                    break;
                }
                System.out.println(n);
            }  // 105 32 108 111 118 101 32 99 104 105 110 97
            // 最终我们要把文件关闭,避免造成不必要的内存浪费
            f.close();
            // try finally可以在报错情况下帮我们最终关闭,但是java帮助我们提供了更简洁的写法
            try (InputStream f1 = new FileInputStream("./src/text.txt")) {
                int n;
                // 一个字节一个自己读
                while ((n = f1.read()) != -1) {
                    System.out.println((char) n); // i love china
                    System.out.println(n); // 105 32 108 111 118 101 32 99 104 105 110 97
                }
            }
            // 还有一种复制的方法,当然还有很多方法,但是都大同小异
            try (InputStream f1 = new FileInputStream("./src/text.txt")) {
                int n;
                byte[] b = new byte[10];
                while ((n = f1.read(b)) != -1) {
                    System.out.println(b);  // [B@38af3868  10
                    System.out.println(n);  // 10  2
                }
            }
    
            // OutputStream
            OutputStream o = new FileOutputStream("./src/text.txt");
            o.write(72); // 写入 H,原内容会被删除
            o.write(72);
            o.close();
            InputStream f3 = new FileInputStream("./src/text.txt");
            System.out.println(f3.read());  // 72
            System.out.println(f3.read());  // 72
            System.out.println(f3.read());  // -1 写入了两个字节,读出两个字节
            f.close();
            // 当然也可以一次写入多个字节
            try (OutputStream o1 = new FileOutputStream("./src/text.txt")) {
                o1.write("hello".getBytes(StandardCharsets.UTF_8));
            }
            try (InputStream f1 = new FileInputStream("./src/text.txt")) {
                byte[] b = f1.readAllBytes();
                for (byte b1 : b) {
                    System.out.println((char) b1);  // hello
                }
            }
            // 读写 zip 文件
            try (ZipOutputStream zip = new ZipOutputStream(new FileOutputStream("t.zip"))) {
                File f4 = new File("./src/text.txt");
                zip.putNextEntry(new ZipEntry(f4.getName()));
                zip.write(new FileInputStream("./src/text.txt").readAllBytes());
                zip.closeEntry();
            }
            System.out.println("---");
            try (ZipInputStream zip = new ZipInputStream(new FileInputStream("t.zip"))) {
                ZipEntry ze = null;
                while ((ze = zip.getNextEntry()) != null) {
                    String name = ze.getName();
                    if (!ze.isDirectory()) {
                        int n;
                        while ((n = zip.read()) != -1) {
                            System.out.println((char) n);  // hello
                        }
                    }
                }
            }
        }
    }

    读写配置文件

    import java.io.*;
    import java.util.Properties;
    
    public class HelloWorld {
        public static void main(String[] args) throws Exception {
            // 读取配置文件的一种方法
            Properties p = new Properties();
            Properties p2 = new Properties();
            p.load(new FileInputStream("./src/default.properties"));
            System.out.println(p);  // {a=1, b=2}
            System.out.println(p.getProperty("a"));  // 1
            System.out.println(p.getProperty("not exist", "offer default value")); // offer default value
            // 从 classPath中读取配置信息
            p2.load(HelloWorld.class.getResourceAsStream("/default.properties"));
            System.out.println(p2);  // {a=1, b=2}
            // 写入配置
            Properties p3 = new Properties();
            p3.setProperty("user", "ning");
            p3.store(new FileOutputStream("./src/tt.propertites"), "anno for this");
            p3.load(new FileInputStream("./src/tt.propertites"));
            System.out.println(p3);  // {user=ning}
        }
    }

    根据字符来写入写出文件

    import java.io.*;
    import java.nio.charset.StandardCharsets;
    
    public class HelloWorld {
        public static void main(String[] args) throws Exception {
            //  根据字符流读写文件
            try (Writer w = new FileWriter("./src/text.txt", StandardCharsets.UTF_8)) {
                w.write('h');  // 写入字符
                w.write("hello".toCharArray()); // 写入字符数组
                w.write("hello");  // 写入字符串
                w.write("我爱我家"); // 写入字符串
            }
            //,跟InputStream差不多,也有很多种读取方法,下面只lie了一种
            try (Reader r = new FileReader("./src/text.txt", StandardCharsets.UTF_8)) {
                int n;
                while ((n = r.read()) != -1) {
                    System.out.println((char) n);
                }  // hhellohello我爱我家
            }
    
        }
    }
  • 相关阅读:
    Cheap Kangaroo(求多个数的最大公约数)
    poj 1094 Sorting It All Out(拓扑排序)
    hdu 5695 Gym Class(拓扑排序)
    Cyclic Components (并查集)
    GCD LCM
    And Then There Was One (约瑟夫环变形)
    System Overload(约瑟夫环变形)
    POJ-1639 Picnic Planning 度数限制最小生成树
    Educational Codeforces Round 60 (Rated for Div. 2) E. Decypher the String
    (ACM模板)二分查找
  • 原文地址:https://www.cnblogs.com/yangshixiong/p/12172992.html
Copyright © 2011-2022 走看看