JAVA中几种读取文件为字符串

本文介绍了四种不同的Java文件读取方法:逐字节读取、FileReader读取、一次性读取全部字节并转码、及使用InputStreamReader加BufferedReader按行读取。每种方法都有其适用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方式一

Java code
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
* 当然也是可以读字符串的。
*/
     /* 貌似是说网络环境中比较复杂,每次传过来的字符是定长的,用这种方式?*/
     public  String readString1()
     {
         try
         {
             //FileInputStream 用于读取诸如图像数据之类的原始字节流。要读取字符流,请考虑使用 FileReader。 
             FileInputStream inStream= this .openFileInput(FILE_NAME);
             ByteArrayOutputStream bos =  new  ByteArrayOutputStream();
             byte [] buffer= new  byte [ 1024 ];
             int  length=- 1 ;
             while ( (length = inStream.read(buffer) != - 1 )
             {
                 bos.write(buffer, 0 ,length);
                 // .write方法 SDK 的解释是 Writes count bytes from the byte array buffer starting at offset index to this stream.
                 //  当流关闭以后内容依然存在
             }
             bos.close();
             inStream.close();
             return  bos.toString();   
             // 为什么不一次性把buffer得大小取出来呢?为什么还要写入到bos中呢? return new(buffer,"UTF-8") 不更好么?
             // return new String(bos.toByteArray(),"UTF-8");       
         }
     }


方式二

Java code
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 有人说了 FileReader  读字符串更好,那么就用FileReader吧
     // 每次读一个是不是效率有点低了?
     private  static  String readString2()
     {
         StringBuffer str= new  StringBuffer( "" );
         File file= new  File(FILE_IN);
         try  {
             FileReader fr= new  FileReader(file);
             int  ch =  0 ;
             while ((ch = fr.read())!=- 1  )
             {
                 System.out.print(( char )ch+ " " ); 
             }
             fr.close();
         catch  (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
             System.out.println( "File reader出错" );
         }
         return  str.toString();
     }


方式三

Java code
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*按字节读取字符串*/
/* 个人感觉最好的方式,(一次读完)读字节就读字节吧,读完转码一次不就好了*/
private  static  String readString3()
{
     String str= "" ;
     File file= new  File(FILE_IN);
     try  {
         FileInputStream in= new  FileInputStream(file);
         // size  为字串的长度 ,这里一次性读完
         int  size=in.available();
         byte [] buffer= new  byte [size];
         in.read(buffer);
         in.close();
         str= new  String(buffer, "GB2312" );
     catch  (IOException e) {
         // TODO Auto-generated catch block
         return  null ;
         e.printStackTrace();
     }
     return  str;
}


方式四

Java code
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*InputStreamReader+BufferedReader读取字符串  , InputStreamReader类是从字节流到字符流的桥梁*/
     /* 按行读对于要处理的格式化数据是一种读取的好方式 */
     private  static  String readString4()
     {
         int  len= 0 ;
         StringBuffer str= new  StringBuffer( "" );
         File file= new  File(FILE_IN);
         try  {
             FileInputStream is= new  FileInputStream(file);
             InputStreamReader isr=  new  InputStreamReader(is);
             BufferedReader in=  new  BufferedReader(isr);
             String line= null ;
             while ( (line=in.readLine())!= null  )
             {
                 if (len !=  0 )   // 处理换行符的问题
                 {
                     str.append( "\r\n" +line);
                 }
                 else
                 {
                     str.append(line);
                 }
                 len++;
             }
             in.close();
             is.close();
         catch  (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
         return  str.toString();
     }




<think>我们正在回答用户关于Java读取txt文件字符串的问题。用户要求提供示例代码。根据引用,我们有多种方法可以实现这个功能。我们将展示几种常见的方法,包括:1.使用ApacheCommonsIO库的FileUtils.readFileToString(需要添加依赖)2.使用BufferedReader逐行读取(标准Java,无需额外依赖)3.使用Java8的Files.lines(生成Stream,然后收集)4.使用Files.readAllBytes(适用于小文件)注意:每种方法都有其适用场景,比如大文件和小文件处理方式不同。我们将分别给出示例代码,并简要说明每种方法的优缺点。另外,根据引用[5],用户还提到了写入文件,但当前问题只涉及读取,所以我们只关注读取。我们将按照以下结构回答:1.使用ApacheCommonsIO(简单快捷,适合项目中已使用该库的情况)2.使用BufferedReader(传统方式,可处理大文件)3.使用Java8的Files类(现代方式,代码简洁)4.使用Files.readAllBytes(适用于小文件)最后,我们将生成相关问题。注意:在代码示例中,我们需要处理异常(IOException),并指定正确的文件路径。</think>### Java读取txt文件字符串的常用方法 以下是几种常用的实现方式,根据场景选择合适的方法: #### 1. 使用Apache Commons IO库(推荐) ```java import org.apache.commons.io.FileUtils; import java.io.File; import java.nio.charset.StandardCharsets; public class ReadFileToString { public static void main(String[] args) { String filePath = "example.txt"; try { // 单行代码完成文件读取 String content = FileUtils.readFileToString( new File(filePath), StandardCharsets.UTF_8 ); System.out.println(content); } catch (IOException e) { e.printStackTrace(); } } } ``` **特点**: - 最简洁的实现方式 - 自动处理字符编码 - 需要添加依赖: ```xml <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.13.0</version> </dependency> ``` [^1] #### 2. 使用BufferedReader(标准Java API) ```java import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class ReadFileToString { public static void main(String[] args) { String filePath = "example.txt"; StringBuilder content = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { String line; while ((line = reader.readLine()) != null) { content.append(line).append("\n"); // 保留换行符 } System.out.println(content.toString()); } catch (IOException e) { e.printStackTrace(); } } } ``` **特点**: - 无需额外依赖 - 适合大文件处理(逐行读取) - 可自定义换行符处理[^2][^3] #### 3. 使用Files类(Java 7+) ```java import java.nio.file.Files; import java.nio.file.Paths; public class ReadFileToString { public static void main(String[] args) { String filePath = "example.txt"; try { // 读取为字节数组后转字符串 byte[] bytes = Files.readAllBytes(Paths.get(filePath)); String content = new String(bytes, "UTF-8"); System.out.println(content); } catch (IOException e) { e.printStackTrace(); } } } ``` **特点**: - 简洁高效 - 适合中小文件(一次性加载到内存) - 需注意字符编码[^3] #### 4. 使用Files.lines(Java 8+) ```java import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Collectors; public class ReadFileToString { public static void main(String[] args) { String filePath = "example.txt"; try { // 使用Stream API处理 String content = Files.lines(Paths.get(filePath)) .collect(Collectors.joining("\n")); System.out.println(content); } catch (IOException e) { e.printStackTrace(); } } } ``` **特点**: - 函数式编程风格 - 适合需要流式处理的场景 - 自动处理资源释放[^4] ### 选择建议: | 方法 | 适用场景 | 优点 | 注意事项 | |--------------------|-------------------------|--------------------------|-----------------------| | Apache Commons IO | 快速开发 | 单行代码完成 | 需添加依赖 | | BufferedReader | 大文件处理 | 内存效率高 | 需手动处理换行符 | | Files.readAllBytes | 小文件快速读取 | 代码简洁 | 不适合超大文件 | | Files.lines | Java 8+流式处理 | 函数式编程,资源自动释放 | 需处理UncheckedIOException | ### 最佳实践: 1. **字符编码**:始终明确指定字符编码(如`StandardCharsets.UTF_8`) 2. **异常处理**:使用try-with-resources确保资源释放 3. **大文件处理**:超过100MB的文件建议使用BufferedReader 4. **路径处理**:使用Paths.get()替代硬编码路径 > **关键提示**:如果文件大小未知,推荐使用BufferedReader方式,它通过缓冲区机制避免内存溢出(OOM)风险[^2][^3]。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值