整个文本文件到Java中的String(Whole text file to a String in Java)

系统教程 行业动态 更新时间:2024-06-14 16:59:47
整个文本文件到Java中的String(Whole text file to a String in Java)

Java有一行读取文本文件的指令,就像C#有什么样的?

我的意思是Java中有什么相当的东西吗?

String data = System.IO.File.ReadAllText("path to file");

如果不是...这样做的最佳方式是什么?

编辑: 我喜欢Java标准库中的一种方式...我不能使用第三方库

Does Java has a one line instruction to read to a text file, like what C# has?

I mean, is there something equivalent to this in Java?:

String data = System.IO.File.ReadAllText("path to file");

If not... what is the 'optimal way' to do this...?

Edit: I prefer a way within Java standard libraries... I can not use 3rd party libraries..

最满意答案

AFAIK,没有标准图书馆的单行班。 标准库的典型方法是这样的:

public static String readStream(InputStream is) { StringBuilder sb = new StringBuilder(512); try { Reader r = new InputStreamReader(is, "UTF-8"); int c = 0; while ((c = r.read()) != -1) { sb.append((char) c); } } catch (IOException e) { throw new RuntimeException(e); } return sb.toString(); }

笔记:

为了从文件中读取文本 ,请使用FileInputStream 如果性能很重要,并且您正在读取大文件,则建议将流包装在BufferedInputStream中 该流应由呼叫者关闭

Java 11 adds support for this use-case with Files.readString, sample code:

Files.readString(Path.of("/your/directory/path/file.txt"));

Before Java 11, typical approach with standard libraries would be something like this:

public static String readStream(InputStream is) { StringBuilder sb = new StringBuilder(512); try { Reader r = new InputStreamReader(is, "UTF-8"); int c = 0; while ((c = r.read()) != -1) { sb.append((char) c); } } catch (IOException e) { throw new RuntimeException(e); } return sb.toString(); }

Notes:

in order to read text from file, use FileInputStream if performance is important and you are reading large files, it would be advisable to wrap the stream in BufferedInputStream the stream should be closed by the caller

更多推荐

本文发布于:2023-04-17 09:03:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/440d916f0fb81fea3632bb85e098ec62.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本文件   Java   String   text   file

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!