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

java 读取字符串文件_Java读取文件为字符串有时在处理文件时,我们需要将文件读取为Java中的String。下面学习如何将文件读取到Java中的String的几种方法。将文件读取到String有很多方法可以在Java中将文件读取到String。在本教程中学习以下几种方法。使用BufferedReader将文件读取到字符串;使用FileInputStream将文件读取到字符串;使用Files类将文件读取到字符串;使用Scanner类将文件读取…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

有时在处理文件时,我们需要将文件读取为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(); } } }

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

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

哥,这回真没有了

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/159351.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • chown和chmod命令用法_chown和chmod的作用

    chown和chmod命令用法_chown和chmod的作用1、chown用法作用:用来更改某个目录或文件的用户名和用户组的格式:chown用户名:组名文件路径(可以是就对路径也可以是相对路径)例1:chownroot:root/tmp/tmp1就是把tmp下的tmp1的用户名和用户组改成root和root(只修改了tmp1的属组).例2:chown-Rroot:root/tmp/tmp1就是把tmp下的tmp1下的所有文件的属组都改成roo…

    2022年10月20日
    2
  • ubuntu安装go语言_go语言web服务器

    ubuntu安装go语言_go语言web服务器来源:微信公众号「编程学习基地」文章目录简介下载go安装包环境配置添加环境变量第一个go语言程序go入门学习简介go语言是一种开源的、语法精简的静态编程语言,它的开源社区比较庞大,应用场景非常广范。可以用于系统监控、容器技术(Docker)、大数据、存储技术、分布式系统(HyperledgerFabric)、消息系统(Kafka客户端)、服务器管理、安全工具、Web工具等。这里介绍在Linux上安装并配置go。下载go安装包到GoLang中国,下载Go语言安装包。解压tar-xzv..

    2022年10月12日
    2
  • 手机cpu控制免root_cpu利用率低但是卡

    手机cpu控制免root_cpu利用率低但是卡想不想让CPU利用率展示成一首优美的旋律,就像弹琴一样。我的意思是,你想让系统以及task的CPU利用率是多少它就是多少,一切都是由你的程序自己来调制演奏。这需要一种自指机制。哈哈,完全可以,本文来演示,或者说,你可以把本文的内容看作一个戏弄运维人员的恶作剧。运维人员经常会遇到各种CPU高的问题,然后成群结队地去排查,想让队伍更大些吗?想让事情更诡异吗?我让你查,我让你查。哈哈。事先声明,若用本文描述的手段实施恶意行为,将会受到谴责,这并不是一个真正工程师该有的行为,更有辱手艺人的探索精神。

    2025年8月24日
    3
  • linux树莓派连接wifi密码,树莓派 连接wifi与路由器ip绑定

    linux树莓派连接wifi密码,树莓派 连接wifi与路由器ip绑定树莓派连接wifi与路由器ip绑定,先推荐几个手机软件1.JuiceSSH橘子ssh软件手机连上路由器就可以控制局域网内的树莓派2.VNCViewer远程桌面软件VNC也是连接局域网的树莓派这几个软件还是很好用的,不想开电脑的时候,也能控制树莓派——————————————————————-…

    2022年5月7日
    53
  • 解决调用未定义 swoole_async_readfile函数问题

    解决调用未定义 swoole_async_readfile函数问题

    2022年2月12日
    51
  • Ajax 培训PPT「建议收藏」

    Ajax 培训PPT「建议收藏」Ajax培训PPT

    2025年10月31日
    4

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号