java IO读取文件


 

    public byte[] getFileContent(String path) {
        try (FileInputStream in = new FileInputStream(path);
             ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ) {
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) != -1) {
                bos.write(buf, 0, len);
            }
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

  
    public String getWholeFile(String path) {
        String line;
        StringBuilder sb = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path)))) {
            while ((line = br.readLine()) != null) {
                sb.append(line).append("/r/n");
            }
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    
    public String getPartFile(String path, int skipLine, int limit) {
        StringBuilder sb = new StringBuilder();
        final File file = new File(path);
        if (file.exists() && file.isFile()) {
            try (Stream<String> lines = Files.lines(Paths.get(path))) {
                final List<String> list = lines.skip(skipLine).limit(limit).collect(Collectors.toList());
                for (String line : list) {
                    sb.append(line).append("/r/n");
                }
                return sb.toString();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

 

原创文章,作者:306829225,如若转载,请注明出处:https://blog.ytso.com/275567.html

(0)
上一篇 2022年7月20日
下一篇 2022年7月20日

相关推荐

发表回复

登录后才能评论