我已经在下面使用过一段时间了。 至少在我访问过的网站上,它似乎是分布最广的。

在Java中,是否有更好/不同的方式将文件读取为字符串?

private String readFile(String file) throws IOException {BufferedReader reader = new BufferedReader(new FileReader (file));String         line = null;StringBuilder  stringBuilder = new StringBuilder();String         ls = System.getProperty("line.separator");try {while((line = reader.readLine()) != null) {stringBuilder.append(line);stringBuilder.append(ls);}return stringBuilder.toString();} finally {reader.close();}
}

#1楼

import java.nio.file.Files;

.......

 String readFile(String filename) {File f = new File(filename);try {byte[] bytes = Files.readAllBytes(f.toPath());return new String(bytes,"UTF-8");} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return "";}

#2楼

请注意,在使用fileInputStream.available() ,返回的整数不必表示实际的文件大小,而是系统应该能够在不阻塞IO的情况下从流中读取的猜测字节数。 一种安全而简单的方法如下所示

public String readStringFromInputStream(FileInputStream fileInputStream) {StringBuffer stringBuffer = new StringBuffer();try {byte[] buffer;while (fileInputStream.available() > 0) {buffer = new byte[fileInputStream.available()];fileInputStream.read(buffer);stringBuffer.append(new String(buffer, "ISO-8859-1"));}} catch (FileNotFoundException e) {} catch (IOException e) { }return stringBuffer.toString();
}

应当认为,这种做法是适合多字节字符编码方式,如UTF-8。


#3楼

我还不能评论其他条目,所以我就把它留在这里。

最佳答案之一( https://stackoverflow.com/a/326448/1521167 ):

private String readFile(String pathname) throws IOException {File file = new File(pathname);
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner scanner = new Scanner(file);
String lineSeparator = System.getProperty("line.separator");try {while(scanner.hasNextLine()) {        fileContents.append(scanner.nextLine() + lineSeparator);}return fileContents.toString();
} finally {scanner.close();
}
}

仍然有一个缺陷。 它总是将换行符放在字符串的末尾,这可能会导致一些奇怪的错误。 我的建议是将其更改为:

    private String readFile(String pathname) throws IOException {File file = new File(pathname);StringBuilder fileContents = new StringBuilder((int) file.length());Scanner scanner = new Scanner(new BufferedReader(new FileReader(file)));String lineSeparator = System.getProperty("line.separator");try {if (scanner.hasNextLine()) {fileContents.append(scanner.nextLine());}while (scanner.hasNextLine()) {fileContents.append(lineSeparator + scanner.nextLine());}return fileContents.toString();} finally {scanner.close();}
}

#4楼

public static String slurp (final File file)
throws IOException {StringBuilder result = new StringBuilder();BufferedReader reader = new BufferedReader(new FileReader(file));try {char[] buf = new char[1024];int r = 0;while ((r = reader.read(buf)) != -1) {result.append(buf, 0, r);}}finally {reader.close();}return result.toString();
}

#5楼

番石榴的方法类似于Willi aus Rohr提到的Commons IOUtils的方法:

import com.google.common.base.Charsets;
import com.google.common.io.Files;// ...String text = Files.toString(new File(path), Charsets.UTF_8);

由PiggyPiglet编辑
已弃用Files#toString ,并将于2019年8月将其删除。而应使用Files.asCharSource(new File(path), StandardCharsets.UTF_8).read();

奥斯卡·雷耶斯(Oscar Reyes)编辑

这是引用的库上的(简化)基础代码:

InputStream in = new FileInputStream(file);
byte[] b  = new byte[file.length()];
int len = b.length;
int total = 0;while (total < len) {int result = in.read(b, total, len - total);if (result == -1) {break;}total += result;
}return new String( b , Charsets.UTF_8 );

编辑 (作者:Jonik):上面的内容与Guava最新版本的源代码不匹配。 对于电流源,看到类文件 , CharStreams , ByteSource和CharSource在com.google.common.io包。


#6楼

将文件读取为二进制文件并在末尾进行转换

public static String readFileAsString(String filePath) throws IOException {DataInputStream dis = new DataInputStream(new FileInputStream(filePath));try {long len = new File(filePath).length();if (len > Integer.MAX_VALUE) throw new IOException("File "+filePath+" too large, was "+len+" bytes.");byte[] bytes = new byte[(int) len];dis.readFully(bytes);return new String(bytes, "UTF-8");} finally {dis.close();}
}

#7楼

如果您需要字符串处理(并行处理),则Java 8具有出色的Stream API。

String result = Files.lines(Paths.get("file.txt")).parallel() // for parallel processing .map(String::trim) // to change line   .filter(line -> line.length() > 2) // to filter some lines by a predicate                        .collect(Collectors.joining()); // to join lines

可以从Oracle Java SE 8下载页面下载的JDK示例sample/lambda/BulkDataOperations中提供了更多示例。

另一个班轮的例子

String out = String.join("\n", Files.readAllLines(Paths.get("file.txt")));

#8楼

如果您无权访问Files类,则可以使用本机解决方案。

static String readFile(File file, String charset)throws IOException
{FileInputStream fileInputStream = new FileInputStream(file);byte[] buffer = new byte[fileInputStream.available()];int length = fileInputStream.read(buffer);fileInputStream.close();return new String(buffer, 0, length, charset);
}

#9楼

如果您愿意使用外部库,请查看Apache Commons IO (200KB JAR)。 它包含一个org.apache.commons.io.FileUtils.readFileToString()方法,该方法使您可以用一行代码将整个File读入String

例:

import java.io.*;
import java.nio.charset.*;
import org.apache.commons.io.*;public String readFile() throws IOException {File file = new File("data.txt");return FileUtils.readFileToString(file, StandardCharsets.UTF_8);
}

#10楼

Java尝试在所有方面都变得极为通用和灵活。 结果,在脚本语言中相对简单的事情(您的代码将被python中的“ open(file).read() ”替换)要复杂得多。 除了使用外部库(例如提到的Willi aus Rohr )外,似乎没有什么更短的方法了。 您的选择:

  • 使用外部库。
  • 将此代码复制到您的所有项目中。
  • 创建自己的迷你库,其中包含您经常使用的功能。

您最好的选择可能是第二,因为它具有最少的依赖性。


#11楼

读取文件中的所有文本

Java 11添加了readString()方法以将小的文件读取为String ,从而保留了行终止符:

String content = Files.readString(path, StandardCharsets.US_ASCII);

对于介于Java 7和11之间的版本,这是一个紧凑而健壮的习惯用法,它包装在实用程序方法中:

static String readFile(String path, Charset encoding) throws IOException
{byte[] encoded = Files.readAllBytes(Paths.get(path));return new String(encoded, encoding);
}

从文件中读取文本行

Java 7添加了一种便捷方法,可以将文件读取为文本行,以List<String> 。 这种方法是“有损的”,因为从每行的末端剥去了行分隔符。

List<String> lines = Files.readAllLines(Paths.get(path), encoding);

Java 8添加了Files.lines()方法来生成Stream<String> 。 同样,此方法是有损的,因为剥去了行分隔符。 如果在读取文件时遇到IOException ,则它将包装在UncheckedIOException ,因为Stream不接受引发已检查异常的lambda。

try (Stream<String> lines = Files.lines(path, encoding)) {lines.forEach(System.out::println);
}

Stream确实需要close()调用; 这个在API上的文档很少,我怀疑很多人甚至没有注意到Streamclose()方法。 确保使用如图所示的ARM模块。

如果您使用的不是文件源,则可以使用BufferedReaderlines()方法。

内存利用率

保留换行符的第一种方法可能临时需要占用文件大小几倍的内存,因为在短时间内,原始文件内容(字节数组)和解码后的字符(即使已编码也为16位) (文件中的8位)一次存储在内存中。 将其应用于相对于可用内存较小的文件是最安全的。

第二种方法是读取行,通常可以提高内存效率,因为用于解码的输入字节缓冲区不需要包含整个文件。 但是,它仍然不适用于相对于可用内存而言非常大的文件。

为了读取大文件,您需要为程序提供不同的设计,即从流中读取文本块,对其进行处理,然后再移至下一个,重新使用相同的固定大小的内存块。 在此,“大”取决于计算机规格。 如今,此阈值可能是许多GB的RAM。 如果输入“记录”恰好是单独的行,则使用Stream<String>的第三种方法是执行此操作的一种方法。 (使用BufferedReaderreadLine()方法等效于此方法。)

字符编码

原始帖子的示例中缺少的一件事是字符编码。 在某些特殊情况下,平台默认值是您想要的,但是很少见,您应该可以证明自己的选择合理。

StandardCharsets类为所有Java运行时所需的编码定义了一些常量:

String content = readFile("test.txt", StandardCharsets.UTF_8);

该平台默认值可从Charset类本身获得:

String content = readFile("test.txt", Charset.defaultCharset());

注意:此答案在很大程度上替代了我的Java 6版本。 Java 7的实用程序安全地简化了代码,并且使用映射字节缓冲区的旧答案阻止了读取的文件被删除,直到对映射缓冲区进行垃圾回收为止。 您可以通过此答案上的“已编辑”链接查看旧版本。


#12楼

如果您正在寻找不涉及第三方库的替代方案(例如Commons I / O ),则可以使用Scanner类:

private String readFile(String pathname) throws IOException {File file = new File(pathname);StringBuilder fileContents = new StringBuilder((int)file.length());        try (Scanner scanner = new Scanner(file)) {while(scanner.hasNextLine()) {fileContents.append(scanner.nextLine() + System.lineSeparator());}return fileContents.toString();}
}

#13楼

该代码将规范换行符,这可能是也可能不是您真正想要的。

这是一个不执行此操作的替代方法,它比NIO代码更易于理解(IMO)(尽管它仍然使用java.nio.charset.Charset ):

public static String readFile(String file, String csName)throws IOException {Charset cs = Charset.forName(csName);return readFile(file, cs);
}public static String readFile(String file, Charset cs)throws IOException {// No real need to close the BufferedReader/InputStreamReader// as they're only wrapping the streamFileInputStream stream = new FileInputStream(file);try {Reader reader = new BufferedReader(new InputStreamReader(stream, cs));StringBuilder builder = new StringBuilder();char[] buffer = new char[8192];int read;while ((read = reader.read(buffer, 0, buffer.length)) > 0) {builder.append(buffer, 0, read);}return builder.toString();} finally {// Potential issue here: if this throws an IOException,// it will mask any others. Normally I'd use a utility// method which would log exceptions and swallow themstream.close();}
}

#14楼

在同一主题上有一个变体,它使用for循环而不是while循环来限制line变量的范围。 是否“更好”取决于个人喜好。

for(String line = reader.readLine(); line != null; line = reader.readLine()) {stringBuilder.append(line);stringBuilder.append(ls);
}

#15楼

在扫描仪之后按Ctrl + F后,我认为也应列出扫描仪解决方案。 最容易阅读的方式是这样的:

public String fileToString(File file, Charset charset) {Scanner fileReader = new Scanner(file, charset);fileReader.useDelimiter("\\Z"); // \Z means EOF.String out = fileReader.next();fileReader.close();return out;
}

如果您使用Java 7或更高版本(确实应该),请考虑使用try-with-resources使代码更易于阅读。 不再有点滴杂物乱扔一切。 但这主要是一种风格选择方法。

我主要出于完成主义的目的发布此文档,因为如果您需要做很多事情,那么java.nio.file.Files中应该有一些可以做得更好的事情。

我的建议是使用Files#readAllBytes(Path)来获取所有字节,并将其提供给新的String(byte [] Charset)以从中获得一个值得信任的字符串。 字符集在您的一生中对您很重要,因此请当心此事。

其他人提供了代码和东西,我不想窃取他们的荣耀。 ;)


#16楼

对于Java 7,这是读取UTF-8文件的首选方法:

String content = new String(Files.readAllBytes(Paths.get(filename)), "UTF-8");

从Java 7开始,JDK具有新的java.nio.file API,该API提供了许多快捷方式,因此对于简单的文件操作,并非始终需要第三方库。


#17楼

import java.nio.file.Files;
import java.nio.file.Paths;String content = new String(Files.readAllBytes(Paths.get("readMe.txt")), "UTF-8");

从Java 7开始,您可以使用这种方式。


#18楼

使用此库 ,它是一行:

String data = IO.from(new File("data.txt")).toString();

#19楼

您可以尝试使用Scanner和File类,几行解决方案

 try
{String content = new Scanner(new File("file.txt")).useDelimiter("\\Z").next();System.out.println(content);
}
catch(FileNotFoundException e)
{System.out.println("not found!");
}

#20楼

同样,如果您的文件恰好在罐子里,您也可以使用以下命令:

public String fromFileInJar(String path) {try ( Scanner scanner = new Scanner(getClass().getResourceAsStream(path))) {return scanner.useDelimiter("\\A").next();}
}

路径应以/开头,例如,如果您的jar是

my.jar/com/some/thing/a.txt

然后,您要像这样调用它:

String myTxt = fromFileInJar("/com/com/thing/a.txt");

#21楼

在一行(Java 8)中,假设您具有阅读器:

String sMessage = String.join("\n", reader.lines().collect(Collectors.toList()));

#22楼

根据@erickson的回答,您可以使用:

public String readAll(String fileName) throws IOException {List<String> lines = Files.readAllLines(new File(fileName).toPath());return String.join("\n", lines.toArray(new String[lines.size()]));
}

#23楼

收集了从磁盘或网络以字符串形式读取文件的所有可能方法。

  • 番石榴:Google使用类ResourcesFiles

     static Charset charset = com.google.common.base.Charsets.UTF_8; public static String guava_ServerFile( URL url ) throws IOException { return Resources.toString( url, charset ); } public static String guava_DiskFile( File file ) throws IOException { return Files.toString( file, charset ); } 

  • APACHE-使用类IOUtils,FileUtils的命令IO

     static Charset encoding = org.apache.commons.io.Charsets.UTF_8; public static String commons_IOUtils( URL url ) throws IOException { java.io.InputStream in = url.openStream(); try { return IOUtils.toString( in, encoding ); } finally { IOUtils.closeQuietly(in); } } public static String commons_FileUtils( File file ) throws IOException { return FileUtils.readFileToString( file, encoding ); /*List<String> lines = FileUtils.readLines( fileName, encoding ); return lines.stream().collect( Collectors.joining("\\n") );*/ } 

  • 使用Stream API的 Java 8 BufferReader

     public static String streamURL_Buffer( URL url ) throws IOException { java.io.InputStream source = url.openStream(); BufferedReader reader = new BufferedReader( new InputStreamReader( source ) ); //List<String> lines = reader.lines().collect( Collectors.toList() ); return reader.lines().collect( Collectors.joining( System.lineSeparator() ) ); } public static String streamFile_Buffer( File file ) throws IOException { BufferedReader reader = new BufferedReader( new FileReader( file ) ); return reader.lines().collect(Collectors.joining(System.lineSeparator())); } 

  • 带有正则表达式\\A扫描器类。 匹配输入的开始。

     static String charsetName = java.nio.charset.StandardCharsets.UTF_8.toString(); public static String streamURL_Scanner( URL url ) throws IOException { java.io.InputStream source = url.openStream(); Scanner scanner = new Scanner(source, charsetName).useDelimiter("\\\\A"); return scanner.hasNext() ? scanner.next() : ""; } public static String streamFile_Scanner( File file ) throws IOException { Scanner scanner = new Scanner(file, charsetName).useDelimiter("\\\\A"); return scanner.hasNext() ? scanner.next() : ""; } 

  • Java 7( java.nio.file.Files.readAllBytes

     public static String getDiskFile_Java7( File file ) throws IOException { byte[] readAllBytes = java.nio.file.Files.readAllBytes(Paths.get( file.getAbsolutePath() )); return new String( readAllBytes ); } 

  • BufferedReader使用InputStreamReader

     public static String getDiskFile_Lines( File file ) throws IOException { StringBuffer text = new StringBuffer(); FileInputStream fileStream = new FileInputStream( file ); BufferedReader br = new BufferedReader( new InputStreamReader( fileStream ) ); for ( String line; (line = br.readLine()) != null; ) text.append( line + System.lineSeparator() ); return text.toString(); } 

使用main方法的示例可以访问上述方法。

public static void main(String[] args) throws IOException {String fileName = "E:/parametarisation.csv";File file = new File( fileName );String fileStream = commons_FileUtils( file );// guava_DiskFile( file );// streamFile_Buffer( file );// getDiskFile_Java7( file );// getDiskFile_Lines( file );System.out.println( " File Over Disk : \n"+ fileStream );try {String src = "https://code.jquery.com/jquery-3.2.1.js";URL url = new URL( src );String urlStream = commons_IOUtils( url );// guava_ServerFile( url );// streamURL_Scanner( url );// streamURL_Buffer( url );System.out.println( " File Over Network : \n"+ urlStream );} catch (MalformedURLException e) {e.printStackTrace();}
}

@看到

  • 将InputStream转换为字符串的方法

#24楼

使用JDK 8或更高版本:

没有使用外部库

您可以从文件内容创建一个新的String对象(使用java.nio.file包中的类):

public String readStringFromFile(String filePath) throws IOException {String fileContent = new String(Files.readAllBytes(Paths.get(filePath)));return fileContent;
}

#25楼

从JDK 11开始:

String file = ...
Path path = Paths.get(file);
String content = Files.readString(path);
// Or readString(path, someCharset), if you need a Charset different from UTF-8

#26楼

用户java.nio.Files读取文件的所有行。

public String readFile() throws IOException {File fileToRead = new File("file path");List<String> fileLines = Files.readAllLines(fileToRead.toPath());return StringUtils.join(fileLines, StringUtils.EMPTY);
}

#27楼

基于Scanner非常精简的解决方案:

Scanner scanner = new Scanner( new File("poem.txt") );
String text = scanner.useDelimiter("\\A").next();
scanner.close(); // Put this call in a finally block

或者,如果要设置字符集:

Scanner scanner = new Scanner( new File("poem.txt"), "UTF-8" );
String text = scanner.useDelimiter("\\A").next();
scanner.close(); // Put this call in a finally block

或者,使用try-with-resources块,它将为您调用scanner.close()

try (Scanner scanner = new Scanner( new File("poem.txt"), "UTF-8" )) {String text = scanner.useDelimiter("\\A").next();
}

请记住, Scanner构造函数可以抛出IOException 。 并且不要忘记导入java.iojava.util

资料来源: Pat Niemeyer的博客


#28楼

如果是文本文件,为什么不使用apache commons-io呢?

它具有以下方法

public static String readFileToString(File file) throws IOException

如果要将这些行作为列表使用

public static List<String> readLines(File file) throws IOException

#29楼

这个使用了RandomAccessFile.readFully方法,它似乎可以从JDK 1.0中获得!

public static String readFileContent(String filename, Charset charset) throws IOException {RandomAccessFile raf = null;try {raf = new RandomAccessFile(filename, "r");byte[] buffer = new byte[(int)raf.length()];raf.readFully(buffer);return new String(buffer, charset);} finally {closeStream(raf);}
} private static void closeStream(Closeable c) {if (c != null) {try {c.close();} catch (IOException ex) {// do nothing}}
}

#30楼

结合使用Apache commons-io的 IOUtils和StringWriter的灵活解决方案:

Reader input = new FileReader();
StringWriter output = new StringWriter();
try {IOUtils.copy(input, output);
} finally {input.close();
}
String fileContents = output.toString();

它适用于任何阅读器或输入流(不仅适用于文件),例如,从URL读取时。

如何从文件内容创建Java字符串?相关推荐

  1. java解析string_java读取文件内容为string字符串的方法

    直接就把项目中的方法贴出来吧 /** * 读出城市列表文件 */ private String readCityFile() { File file02 = new File(path_xinfu, ...

  2. java读取string_java读取文件内容为string字符串的方法

    java读取文件内容为string字符串的方法 发布时间:2020-10-02 22:03:04 来源:脚本之家 阅读:67 作者:tmgg 直接就把项目中的方法贴出来吧 /** * 读出城市列表文件 ...

  3. php中读取文件内容的几种方法。(file_get_contents:将文件内容读入一个字符串)...

    php中读取文件内容的几种方法.(file_get_contents:将文件内容读入一个字符串) 一.总结 php中读取文件内容的几种方法(file_get_contents:将文件内容读入一个字符串 ...

  4. Python Pandas 通过读取txt文件内容创建DataFrame

    本文主要介绍Python中,通过读取txt文件内容创建Pandas的DataFrame,创建DataFrame分别使用pd.DataFrame.from_records()和pd.read_csv() ...

  5. Java读取文件内容,返回字符串

    利用cn.hutool工具包内的工具类FileReader(文件读取器),可实现多种文件读取操作. 以下代码实现了读取文件内容,并返回字符串(包括换行符).该操作支持多种文件格式,比如txt.html ...

  6. java 文件内容读取到字符串中,从文本文件中将字符串值读取到Java中的Jav...

    我想通过分割读取字符串值包括从文本文件到存储到Account类的空白.这是我读取文本文件的功能. public ArrayList loadAccount(String fn) throws IOEx ...

  7. idea 创建java文件_idea创建java文件 格式不对

    import java.io.File; import java.io.FileWriter; import java.io.IOException; public class Test { publ ...

  8. 文件内容查找java,java库从文件内容中查找mime类型

    I am searching for a java library which tells you the mime type by looking at the file content(byte ...

  9. Java读取文件的内容到String字符串中

    Java读取文件的内容到String字符串中 将文件读取到String有很多方法可以在Java中将文件读取到String.在本教程中学习以下几种方法. 使用BufferedReader将文件读取到字符 ...

最新文章

  1. 不用Office自动化技术,给Word文档中填充赋值
  2. 给图片加一层半透明_设计半透明风格卡通星球图片的PS教程
  3. 五天学习MySQL数据库(一)1.3MySQL 基本介绍
  4. Docker-Oracle和物理机Oracle数据库性能测试
  5. Scrapy运行时出现的错误 :exception.ImportError No module named win32api
  6. poi下载excel模板
  7. xp计算机u盘重装系统,用U盘给旧电脑重装XP系统,自己摸索的方法:两大步骤、两个关键...
  8. pdf合并成一个pdf软件下载?pdf合并成一个pdf软件合成器工具
  9. 使用 Golang 实现简易的令牌桶算法
  10. win7录屏_win7/win10电脑屏幕录像工具哪款比较好?--QVE屏幕录制
  11. Ubuntu16安装搜狗拼音输入法
  12. IIS如何添加MIME类型.svg/.woff2/.woff
  13. 文件系统管理 之 reiserfs文件系统反删除(Undelete)操作的实践
  14. 从零开始的ZYNQ学习(基于矿卡EBAZ4205)(二)
  15. 有感于李连杰壹基金计划
  16. 人民币转换美金的c语言代码大全,JS实现将人民币金额转换为大写的示例代码
  17. Hazelcast IMDG技术详解
  18. VC程序里判断系统是64位还是32位的正确方法
  19. 电脑会不定时的突然黑屏加显卡风扇狂转,记录一次排查过程
  20. python中的self理解

热门文章

  1. compileReleaseJavaWithJavac
  2. 使用VMware新建Ubuntu虚拟机
  3. 图解 SQL 里的各种 JOIN
  4. swift_044(Swift 计算属性和存储属性的概念以及使用)
  5. android列表集合点击事件,给ListeView列表中的每一个Item添加点击事件
  6. python 地址模糊匹配_使用python处理selenium中的xpath定位元素的模糊匹配问题
  7. PHP开发工具 zend studio
  8. 190401装饰器-高阶函数-闭包
  9. 跟老齐学Python:轻松入门pdf
  10. 解决git did not exit cleanly (exit code 128)