Java中如何按行读取文件及一次性全部读取数据呢?

戚薇 Java经验 发布时间:2023-06-09 23:22:33 阅读数:7039 1
下文笔者讲述使用java代码按行读取文件和一次性读取文件的方法及示例分享,如下所示

读取文件的实现思路

1.一行一行读取文件
   使用readLine()方法

2.一次读取全部文件
   使用read()方法
例:读取文件的示例
一行一行的读取文件

ClassPathResource classPathResource = new ClassPathResource("fileName.txt");
InputStream inputStream =classPathResource.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String txt = "";
while(reader.ready()) {
 
    txt += reader.readLine();
}
 
String s = new String(Base64.encodeBase64(txt.getBytes(UTF_8)), UTF_8);


一次性读取文件
private String getFile(String fileName) throws IOException {

	ClassPathResource classPathResource = new ClassPathResource(fileName);
	File file = classPathResource.getFile();
	FileInputStream in = new FileInputStream(file);
	byte[] fileContent = new byte[(int) file.length()];
	in.read(fileContent);
	String txt = new String(fileContent);

	String pileString = new String(Base64.encodeBase64(txt.getBytes(UTF_8)), UTF_8);
	return pileString;
}
  
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202306/16863242026764.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者