zoukankan      html  css  js  c++  java
  • java读取文件(更新jdk7及jdk8)

    以字节的方式读取:

                InputStream inputStream = new FileInputStream(file);
                int temp = -1;
                StringBuilder sb = new StringBuilder();
                while((temp = inputStream.read()) != -1){
                    sb.append((char)temp);
                }
                inputStream.close();

    也可以多个字节一起读取:

                InputStream inputStream = new FileInputStream(file);
                byte[] bytes = new byte[10];
                StringBuilder sb = new StringBuilder();
                int length = -1;
                while((length = inputStream.read(bytes))!= -1){
                    sb.append(new String(bytes,0,length,Charset.forName("utf-8")));
                }
                inputStream.close();

    以字符的方式读取:

                InputStream inputStream = new FileInputStream(file);
                InputStreamReader isr = new InputStreamReader(inputStream,Charset.forName("utf-8"));
                StringBuilder sb = new StringBuilder();
                int temp = -1;
                while((temp = (isr.read()))!= -1){
                    sb.append((char)temp);
                }
                inputStream.close();
                isr.close();

    或者用封装的BufferedReader按行读取,效率更高:

    InputStream inputStream = new FileInputStream(file);
                InputStreamReader isr = new InputStreamReader(inputStream,Charset.forName("utf-8"));
                BufferedReader bufferedReader = new BufferedReader(isr);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while((line = bufferedReader.readLine())!=null){
                    sb.append(line + '
    ');
                }
                inputStream.close();
                isr.close();
                bufferedReader.close();

     -----------------------------------------------以上是jdk7之前一般使用的读取文件方法-------------------------------------------------------------------------------------------------------

    jdk7引入了新的文件api: java.nio.file.Files。 Files.readAllBytes()方法将文件内容全部读入内存,并且确保读取完之后文件是关闭的,也就是说,不用手动调用close方法:

    String path = "C:\test.txt";
    System.out.print(Files.readAllBytes(Paths.get(path)));

    当文件过大时,不建议使用readAllBytes()方法将文件内容一次全部读入到内存里面。

    java8中使用流的方式来读取更高效:

    Files.lines(Paths.get(path),StandardCharsets.UTF_8).forEach(System.out::println);
  • 相关阅读:
    jmeter对数据库进行简单的压测
    数据库语言sql
    (二)变量的概念与分类
    (一)Java关键字与标识符
    socket之远程执行命令
    python文件操作
    UDP基础server与client
    TCP基础server与client
    Python 之 杂谈(迭代器iter)、偏函数
    python 之解决socket 粘包
  • 原文地址:https://www.cnblogs.com/hithlb/p/4135108.html
Copyright © 2011-2022 走看看