java 读取字符串文件_Java读取文件为字符串

有时在处理文件时,我们需要将文件读取为Java中的String。下面学习如何将文件读取到Java中的String的几种方法。

将文件读取到String

有很多方法可以在Java中将文件读取到String。在本教程中学习以下几种方法。

使用BufferedReader将文件读取到字符串;

使用FileInputStream将文件读取到字符串;

使用Files类将文件读取到字符串;

使用Scanner类将文件读取到字符串;

使用Apache Commons IO FileUtils类将文件读取到字符串;

现在让我们看看这些类是如何将文件读取到字符串的。

方法1: 使用BufferedReader将文件读取到字符串

使用BufferedReader类的readLine()方法逐行读取文件。将文件内容附加到带有换行符的StringBuilder对象。下面是使用BufferedReader将文件读取到字符串的代码片段。

BufferedReader reader = new BufferedReader(new FileReader(fileName)); StringBuilder stringBuilder = new StringBuilder(); String line = null; String ls = System.getProperty("line.separator"); while ((line = reader.readLine()) != null) { stringBuilder.append(line); stringBuilder.append(ls); } // 删除最后一个新行分隔符 stringBuilder.deleteCharAt(stringBuilder.length() - 1); reader.close(); String content = stringBuilder.toString();

还有另一种使用BufferedReader和char数组将文件读取到String的方法,如下代码所示 –

BufferedReader reader = new BufferedReader(new FileReader(fileName)); StringBuilder stringBuilder = new StringBuilder(); char[] buffer = new char[10]; while (reader.read(buffer) != -1) { stringBuilder.append(new String(buffer)); buffer = new char[10]; } reader.close(); String content = stringBuilder.toString();

方法2: 使用FileInputStream将文件读取到字符串

使用FileInputStream和byte数组将文件读取到字符串。应该使用此方法来读取非基于字符的文件,如图像,视频等。

FileInputStream fis = new FileInputStream(fileName); byte[] buffer = new byte[10]; StringBuilder sb = new StringBuilder(); while (fis.read(buffer) != -1) { sb.append(new String(buffer)); buffer = new byte[10]; } fis.close(); String content = sb.toString();

方法3: 使用Files类将文件读取到字符串

可以使用Files实用程序类在一行代码中将所有文件内容读取为字符串。

String content = new String(Files.readAllBytes(Paths.get(fileName)));

方法4: 使用Scanner类将文件读取到字符串

Scanner类是在java中读取文本文件的快速方法。参考以下代码 –

Scanner scanner = new Scanner(Paths.get(fileName), StandardCharsets.UTF_8.name()); String content = scanner.useDelimiter("\A").next(); scanner.close();

方法4:使用Apache Commons IO FileUtils类将文件读取到字符串

如果在项目中使用Apache Commons IO,那么这是一种在java中将文件读取为字符串的简单快捷方式。参考以下代码 –

String content = FileUtils.readFileToString(new File(fileName), StandardCharsets.UTF_8);

Java读取文件字符串示例

这是一个示例程序,具有适当的异常处理,并显示了将文件读取到字符串的上面几个方法。

import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Scanner; import org.apache.commons.io.FileUtils; public class JavaReadFileToString { /** * 此类显示将完整文件内容读取到String的不同方法 * * @param args * @throws IOException */ public static void main(String[] args) { String fileName = "D:/users/maxsu/myfile.txt"; String contents = readUsingScanner(fileName); System.out.println("*****Read File to String Using Scanner*****n" + contents); contents = readUsingApacheCommonsIO(fileName); System.out.println("*****Read File to String Using Apache Commons IO FileUtils*****n" + contents); contents = readUsingFiles(fileName); System.out.println("*****Read File to String Using Files Class*****n" + contents); contents = readUsingBufferedReader(fileName); System.out.println("*****Read File to String Using BufferedReader*****n" + contents); contents = readUsingBufferedReaderCharArray(fileName); System.out.println("*****Read File to String Using BufferedReader and char array*****n" + contents); contents = readUsingFileInputStream(fileName); System.out.println("*****Read File to String Using FileInputStream*****n" + contents); } private static String readUsingBufferedReaderCharArray(String fileName) { BufferedReader reader = null; StringBuilder stringBuilder = new StringBuilder(); char[] buffer = new char[10]; try { reader = new BufferedReader(new FileReader(fileName)); while (reader.read(buffer) != -1) { stringBuilder.append(new String(buffer)); buffer = new char[10]; } } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } return stringBuilder.toString(); } private static String readUsingFileInputStream(String fileName) { FileInputStream fis = null; byte[] buffer = new byte[10]; StringBuilder sb = new StringBuilder(); try { fis = new FileInputStream(fileName); while (fis.read(buffer) != -1) { sb.append(new String(buffer)); buffer = new byte[10]; } fis.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (fis != null) try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } private static String readUsingBufferedReader(String fileName) { BufferedReader reader = null; StringBuilder stringBuilder = new StringBuilder(); try { reader = new BufferedReader(new FileReader(fileName)); String line = null; String ls = System.getProperty("line.separator"); while ((line = reader.readLine()) != null) { stringBuilder.append(line); stringBuilder.append(ls); } // delete the last ls stringBuilder.deleteCharAt(stringBuilder.length() - 1); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } return stringBuilder.toString(); } private static String readUsingFiles(String fileName) { try { return new String(Files.readAllBytes(Paths.get(fileName))); } catch (IOException e) { e.printStackTrace(); return null; } } private static String readUsingApacheCommonsIO(String fileName) { try { return FileUtils.readFileToString(new File(fileName), StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); return null; } } private static String readUsingScanner(String fileName) { Scanner scanner = null; try { scanner = new Scanner(Paths.get(fileName), StandardCharsets.UTF_8.name()); // 可以使用Delimiter正则表达式 "\A", "\Z" or "\z" String data = scanner.useDelimiter("\A").next(); return data; } catch (IOException e) { e.printStackTrace(); return null; } finally { if (scanner != null) scanner.close(); } } }

可以使用上述任何方法将文件内容读取到字符串。但是,如果文件很大,则不建议使用,因为可能会遇到内存不足错误。

¥ 我要打赏 纠错/补充 收藏

哥,这回真没有了

public static String loadAFileToStringDE1(File f) throws IOException { long beginTime = System.currentTimeMillis(); InputStream is = null; String ret = null; try { is = new BufferedInputStream( new FileInputStream(f) ); long contentLength = f.length(); ByteArrayOutputStream outstream = new ByteArrayOutputStream( contentLength > 0 ? (int) contentLength : 1024); byte[] buffer = new byte[4096]; int len; while ((len = is.read(buffer)) > 0) { outstream.write(buffer, 0, len); } outstream.close(); ret = outstream.toString(); //byte[] ba = outstream.toByteArray(); //ret = new String(ba); } finally { if(is!=null) {try{is.close();} catch(Exception e){} } } long endTime = System.currentTimeMillis(); System.out.println("方法1用时"+ (endTime-beginTime) + "ms"); return ret; } public static String loadAFileToStringDE2(File f) throws IOException { long beginTime = System.currentTimeMillis(); InputStream is = null; String ret = null; try { is = new FileInputStream(f) ; long contentLength = f.length(); byte[] ba = new byte[(int)contentLength]; is.read(ba); ret = new String(ba); } finally { if(is!=null) {try{is.close();} catch(Exception e){} } } long endTime = System.currentTimeMillis(); System.out.println("方法2用时"+ (endTime-beginTime) + "ms"); return ret; } public static String loadAFileToStringDE3(File f) throws IOException { long beginTime = System.currentTimeMillis(); BufferedReader br = null; String ret = null; try { br = new BufferedReader(new FileReader(f)); String line = null; StringBuffer sb = new StringBuffer((int)f.length()); while( (line = br.readLine() ) != null ) { sb.append(line).append(LINE_BREAK); } ret = sb.toString(); } finally { if(br!=null) {try{br.close();} catch(Exception e){} } } long endTime = System.currentTimeMillis(); System.out.println("方法3用时"+ (endTime-beginTime) + "ms"); return ret; } 3个方法去读取一个大于50M的文件,当不设置jvm参数时都OutofMemery,当设置-Xmx128M时。只有方法3 可以通过,设置到-Xmx256M时也只有方法3可以通过,干脆设置512M,都可以了,运行时间如果正常的话一般都在4~5S
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值