整个文本文件到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更多推荐
发布评论