jdk7一些功能

一、try_with_resources

    try (Scanner in = new Scanner(Paths.get("F:/aaa.txt"));PrintWriter out = new PrintWriter("F:/temp.txt")){
            while (in.hasNext())
                out.print(in.next().toLowerCase());
        }

这是try_with_resources的最简洁形式,如果代码块中出现异常,都会调用close()方法,就像finally一样。

二、Objects类

如果两个字符串都为null,则返回true,否则按照正常的equals方法比较,不存在空指针异常的问题。

    String s1 = null;
    String s2 = "";
    boolean b = Objects.equals(s1, null);
    System.out.println(b);

计算哈希码、哈希值。

    //null值返回0
    Objects.hashCode(null);
    Objects.hash(null);
    //多个对象,哈希码自动组合
    int i = Objects.hash(null, "asa", 2);

检测对象是否是null值,如果是null值,可以在异常输出位置查看。

    Objects.requireNonNull(null, "可以在异常输出中看见位置");

三、比较数值

    int i = Integer.compare(0, 1);
    System.out.println(i);

    int j = new Integer(1464616131234134).compareTo(46416);
    System.out.println(j);

Integer.compare()比较两个int数值;但是如果数值过大,可以使用new Integer().compareTo()来比较,会自动装箱/拆箱两个过大整数对象。结果是前者大于后者返回1,反之返回-1。

四、Path,Files使用

Path是一个含有多个或一个目录名称的序列,也可以带文件名。

    Path path = Paths.get("F:","/","test","/","aaa.txt");
    path.getParent();//获得上一级路径
    path.getRoot();//获得根路径
    path.getFileName();//获得文件名
    path.getNameCount();//获得目录级数

Files类可以快速的实现一些常用的文件操作,快速的读取文件的全部内容。

    Path path = Paths.get("F:/aaa.txt");
    //读取为字符串
    byte[] bytes = Files.readAllBytes(path);
    String string = new String(bytes, StandardCharsets.UTF_8);
    //按照行读取文件
    List<String> list = Files.readAllLines(path, StandardCharsets.UTF_8);
    System.out.println(list);
    //反之写入文件
    Files.write(path, string.getBytes(StandardCharsets.UTF_8));
    Files.write(path, list, StandardCharsets.UTF_8, StandardOpenOption.APPEND);

还可以快速的写入文件或读取文件。

    InputStream in = Files.newInputStream(path, StandardOpenOption.WRITE);
    OutputStream out = Files.newOutputStream(path, StandardOpenOption.WRITE);
    BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
    BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.WRITE);

复制、拷贝文件

    //复制,还可以使用输入输出流
    Files.copy(path, path2, StandardCopyOption.REPLACE_EXISTING);
    //移动,重命名
    Files.move(path, path2, StandardCopyOption.ATOMIC_MOVE);
    //如果存在即删除
    Files.deleteIfExists(path);

猜你喜欢

转载自blog.csdn.net/zajiayouzai/article/details/78963649