• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

关于java:Java中读取文件内容的几种方式

java 搞代码 3年前 (2022-02-19) 23次浏览 已收录 0个评论
文章目录[隐藏]

Java中读取文件中的内容的几种形式如下:

读取磁盘中的文件

第一种形式
private static String text = null;
/**
 * @param fileUrl 文件绝对路径
 * @return String 字符串
 */
public static String buffedInput(String fileUrl) {
    try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileUrl))) {
        byte[] bytes = new byte[2048];
        int fileNumber = 0;
        while ((fileNumber = bis.read(bytes)) != -1) {
            text = new String(bytes, 0, fileNumber, "UTF-8");
        }
    } catch (IOException e) {
        throw new RuntimeException("读取文件内容失败");
    }
    return text;
}
第二种形式
private static String text = null;
/**
 * 将读取文件的字节转化为字符串
 *
 * @param fileUrl 文件绝对路径
 * @return
 * @throws IOException
 */
public static String fileInput(String fileUrl) {
    try {
        text = new String<span style="color:transparent">来源gaodai#ma#com搞*代#码网</span>(Files.readAllBytes(Paths.get(fileUrl)), "UTF-8");
    } catch (Exception e) {
        throw new RuntimeException("读取文件内容失败");
    }
    return text;
}

读取流中的文件

第一种形式
public static String TEXT_CONTENT = "";
/**
 * 高级读取流
 */
public static String buffedInput(InputStream inputStream) {
    try (BufferedInputStream bis = new BufferedInputStream(inputStream)) {
        byte[] bytes = new byte[2048];
        int fileNumber = 0;
        while ((fileNumber = bis.read(bytes)) != -1) {
            TEXT_CONTENT = new String(bytes, 0, fileNumber, "utf-8");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return TEXT_CONTENT;
}

以上内容仅供参考


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:关于java:Java中读取文件内容的几种方式
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址