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

37次阅读

共计 1087 个字符,预计需要花费 3 分钟才能阅读完成。

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(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;
}

以上内容仅供参考

正文完
 0