整个文本文件到Java中的String [英] Whole text file to a String in Java

查看:109
本文介绍了整个文本文件到Java中的String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否Java有一行读取文本文件的指令,就像C#中所使用的那样?



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

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

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

编辑:


我喜欢Java标准库中的一种方式...我不能使用第3派对库..

解决方案

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

  • 流程应由调用者关闭


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, there is no one-liner with standard libraries. 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

这篇关于整个文本文件到Java中的String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆