一、按字节去读

 String file = "src/main/resources/database.json";
        InputStream is = null;
        try {
            is = new FileInputStream(file);//操作
            byte[] bytes = new byte[200];//数组容量超级大,一次能将中英混合文本全部读取完
            int len = -1;
            while ((len = is.read(bytes)) != -1) {
                String str = new String(bytes, 0, len, "UTF-8");
                System.out.print(str);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {//释放资源
            try {
                if (null != is) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

二、按行去读

 FileReader f = new FileReader(file);
            BufferedReader b = new BufferedReader(f);
            String s;
            while ((s = b.readLine()) != null) {
                all=all+s;
            }
            b.close();
            f.close();

 file是文件路径

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐