zoukankan      html  css  js  c++  java
  • java读取文件

    public static void readFileByBytes(String fileName) {
            File file = new File(fileName);
            InputStream in = null;
            StringBuffer sb=new StringBuffer();
            try {
    
                if(file.isFile() && file.exists()){ //判断文件是否存在
                    System.out.println("以字节为单位读取文件内容,一次读多个字节:");
                    // 一次读多个字节
                    byte[] tempbytes = new byte[1024];
                    int byteread = 0;
                    in = new FileInputStream(file);
                    ReadFromFile.showAvailableBytes(in);
                    // 读入多个字节到字节数组中,byteread为一次读入的字节数
                    while ((byteread = in.read(tempbytes)) != -1) {
                      //  System.out.write(tempbytes, 0, byteread);
                        String str=new String(tempbytes,0,byteread);
                        sb.append(str);
                    }
                }else{
                    System.out.println("找不到指定的文件,请确认文件路径是否正确");
                }
    
    
                String data = sb.toString() ;
    
              } catch (Exception e) {
                System.out.println("读取文件内容出错");
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e1) {
                    }
                }
            }
    }
       

    /**
    * 显示输入流中的字节数
    */
    private static void showAvailableBytes(InputStream in) {
    try {
    System.out.println("当前字节输入流中的字节数为:" + in.available());
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    public static void main(String[] args) {

    // String fileName = "D:/file/test3.json";
    String fileName = "D:/file/1.json";
    readFileByBytes(fileName);


    }
    
    
  • 相关阅读:
    source insight快捷键及使用技巧
    HTTP 状态码
    select poll epoll三者之间的比较
    服务器程序后台化以及守护进程的编写规范
    Linux 信号表
    Linux下有线无线网络配置------命令模式
    浅谈 qmake 之 pro、pri、prf、prl文件
    Python VUE 基础知识
    VUE 实现tab切换页面效果
    爬虫框架:scrapy
  • 原文地址:https://www.cnblogs.com/JonaLin/p/11016456.html
Copyright © 2011-2022 走看看