如何从文件的内容创建Java字符串?

时间:2022-04-03 07:38:08

I've been using the idiom below for some time now. And it seems to be the most wide-spread, at least on the sites I've visited.

我用下面这个成语已经有一段时间了。这似乎是最广泛的传播,至少在我访问过的网站上是如此。

Is there a better/different way to read a file into a string in Java?

在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();
    }
}

31 个解决方案

#1


1238  

Read all text from a file

Here's a compact, robust idiom for Java 7, wrapped up in a utility method:

下面是Java 7的一个紧凑、健壮的习惯用法,用实用方法包装:

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

Read lines of text from a file

Java 7 added a convenience method to read a file as lines of text, represented as a List<String>. This approach is "lossy" because the line separators are stripped from the end of each line.

Java 7增加了一种方便的方法,以文本行形式读取文件,以列表 表示。这种方法是“有损”的,因为行分隔符是从每一行的末尾剥离的。

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

In Java 8, BufferedReader added a new method, lines() to produce a Stream<String>. If an IOException is encountered while reading the file, it is wrapped in an UncheckedIOException, since Stream doesn't accept lambdas that throw checked exceptions.

在Java 8中,BufferedReader添加了一个新方法lines()来生成一个流 。如果在读取文件时遇到IOException,它将被包装在UncheckedIOException中,因为流不接受抛出已检查异常的lambdas。

try (BufferedReader r = Files.newBufferedReader(path, encoding)) {
  r.lines().forEach(System.out::println);
}

There is also a Files.lines() method which does something very similar, returning the Stream<String> directly. But I don't like it. The Stream needs a close() call; this is poorly documented on the API, and I suspect many people don't even notice Stream has a close() method. So your code would look very similar, like this:

还有一个Files.lines()方法,它做一些非常类似的事情,直接返回流 。但我不喜欢。该流需要一个close()调用;这在API上是很糟糕的文档,我怀疑很多人甚至没有注意到流有一个close()方法。所以你的代码看起来很相似,像这样:

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

The difference is that you have a Stream assigned to a variable, and I try avoid that as a practice so that I don't accidentally try to invoke the stream twice.

不同之处在于,您有一个分配给变量的流,我尽量避免这种做法,这样我就不会意外地两次调用该流。

Memory utilization

The first method, that preserves line breaks, can temporarily require memory several times the size of the file, because for a short time the raw file contents (a byte array), and the decoded characters (each of which is 16 bits even if encoded as 8 bits in the file) reside in memory at once. It is safest to apply to files that you know to be small relative to the available memory.

第一种方法,保留换行符,可以暂时需要几次内存文件的大小,因为在短时间内的原始文件的内容(一个字节数组)和解码字符(每一个都是16位,即使文件编码为8位)驻留在内存中。最安全的方法是将文件应用到相对于可用内存较小的文件。

The second method, reading lines, is usually more memory efficient, because the input byte buffer for decoding doesn't need to contain the entire file. However, it's still not suitable for files that are very large relative to available memory.

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

For reading large files, you need a different design for your program, one that reads a chunk of text from a stream, processes it, and then moves on to the next, reusing the same fixed-sized memory block. Here, "large" depends on the computer specs. Nowadays, this threshold might be many gigabytes of RAM. The third method, using a Stream<String> is one way to do this, if your input "records" happen to be individual lines. (Using the readLine() method of BufferedReader is the procedural equivalent to this approach.)

对于读取大型文件,您需要为您的程序设计不同的设计,该设计从流中读取一段文本,对其进行处理,然后继续进行下一段,重用相同的固定大小的内存块。在这里,“大”取决于计算机规格。现在,这个阈值可能是千兆字节的RAM。第三种方法是使用流 ,如果您的输入“records”恰好是单独的行,那么这是一种方法。(使用BufferedReader的readLine()方法相当于使用这种方法。)

Character encoding

One thing that is missing from the sample in the original post is the character encoding. There are some special cases where the platform default is what you want, but they are rare, and you should be able justify your choice.

在最初的文章中,缺少的一个东西是字符编码。在某些特殊情况下,平台默认值是您想要的,但它们是罕见的,您应该能够证明您的选择是合理的。

The StandardCharsets class define some constants for the encodings required of all Java runtimes:

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

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

The platform default is available from the Charset class itself:

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

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

Note: This answer largely replaces my Java 6 version. The utility of Java 7 safely simplifies the code, and the old answer, which used a mapped byte buffer, prevented the file that was read from being deleted until the mapped buffer was garbage collected. You can view the old version via the "edited" link on this answer.

注意:这个答案在很大程度上替代了我的Java 6版本。Java 7的实用程序安全地简化了代码,而旧的答案(使用映射字节缓冲区)防止删除被读取的文件,直到映射缓冲区被垃圾收集。您可以通过这个答案上的“编辑”链接查看旧版本。

#2


292  

Commons FileUtils.readFileToString:

下议院FileUtils.readFileToString:

public static String readFileToString(File file)
                       throws IOException

Reads the contents of a file into a String using the default encoding for the VM. The file is always closed.

使用VM的默认编码将文件内容读入字符串。文件总是关闭的。

Parameters:

参数:

  • file - the file to read, must not be null
  • 文件-要读取的文件,不能为空

Returns: the file contents, never null

返回:文件内容,不为空

Throws: - IOException - in case of an I/O error

抛出:- IOException -如果发生I/O错误。

Since: Commons IO 1.3.1

自:共用IO 1.3.1

The code used (indirectly) by that class is:

该类(间接)使用的代码是:

IOUtils.java under Apache Licence 2.0.

IOUtils。Apache license 2.0下的java。

public static long copyLarge(InputStream input, OutputStream output)
       throws IOException {
   byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
   long count = 0;
   int n = 0;
   while (-1 != (n = input.read(buffer))) {
       output.write(buffer, 0, n);
       count += n;
   }
   return count;
}

It is very similar to the one used by Ritche_W.

它与Ritche_W使用的非常相似。

#3


157  

From this page a very lean solution:

从这一页,一个非常精简的解决方案:

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

or

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

If you want to set the charset

如果要设置字符集

#4


68  

If you're looking for an alternative that doesn't involve a third-party library (e.g. Commons I/O), you can use the Scanner class:

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

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();
    }
}

#5


63  

Guava has a method similar to the one from Commons IOUtils that Willi aus Rohr mentioned:

Guava有一种方法,类似于威利奥斯·罗尔提到的下议院IOUtils的一种方法:

import com.google.common.base.Charsets;
import com.google.common.io.Files;

// ...

String text = Files.toString(new File(path), Charsets.UTF_8);

EDIT by Oscar Reyes

编辑由奥斯卡雷耶斯

This is the (simplified) underlying code on the cited library:

这是引用库中的(简化)底层代码:

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 );

Edit (by Jonik): The above doesn't match the source code of recent Guava versions. For the current source, see the classes Files, CharStreams, ByteSource and CharSource in com.google.common.io package.

编辑(由Jonik):上面的代码与最近的Guava版本的源代码不匹配。对于当前源,请参见com.google.common.io包中的类文件、CharStreams、ByteSource和CharSource。

#6


50  

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 "";
    }

#7


44  

If you need a string processing (parallel processing) Java 8 has the great Stream API.

如果您需要一个字符串处理(并行处理),Java 8拥有强大的流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

More examples are available in JDK samples sample/lambda/BulkDataOperations that can be downloaded from Oracle Java SE 8 download page

在可以从Oracle Java SE 8下载页面下载的JDK示例/lambda/BulkDataOperations中有更多的示例

Another one liner example

另一个班轮的例子

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

#8


44  

That code will normalize line breaks, which may or may not be what you really want to do.

该代码将使换行符规范化,这可能是您真正想做的事情。

Here's an alternative which doesn't do that, and which is (IMO) simpler to understand than the NIO code (although it still uses java.nio.charset.Charset):

这里有一个替代方法,它没有这么做,而且(在我看来)比NIO代码更容易理解(尽管它仍然使用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 stream
    FileInputStream 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 them
        stream.close();
    }        
}

#9


37  

String content = new String(Files.readAllBytes(Paths.get("readMe.txt")));

since java 7 you can do it this way.

因为java 7可以这样做。

#10


22  

If it's a text file why not use apache commons-io?

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

It has the following method

它有以下方法

public static String readFileToString(File file) throws IOException

If you want the lines as a list use

如果你想让这些行作为列表使用

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

#11


14  

Java attempts to be extremely general and flexible in all it does. As a result, something which is relatively simple in a scripting language (your code would be replaced with "open(file).read()" in python) is a lot more complicated. There doesn't seem to be any shorter way of doing it, except using an external library (like Willi aus Rohr mentioned). Your options:

Java试图在它所做的一切中变得非常通用和灵活。因此,在脚本语言中相对简单的东西(您的代码将被python中的“open(file).read()”替换)要复杂得多。除了使用外部库(如Willi aus Rohr提到的那样)之外,似乎没有任何更短的方法可以完成这一任务。你的选择:

  • Use an external library.
  • 使用一个外部的库。
  • Copy this code into all your projects.
  • 将此代码复制到所有项目中。
  • Create your own mini-library which contains functions you use often.
  • 创建您自己的迷你库,其中包含您经常使用的函数。

Your best bet is probably the 2nd one, as it has the least dependencies.

你最好的选择可能是第2个,因为它的依赖性最小。

#12


14  

To read a File as binary and convert at the end

以二进制形式读取文件并在末尾进行转换

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();
    }
}

#13


12  

With Java 7, this is my preferred option to read a UTF-8 file:

使用Java 7,这是我首选的阅读UTF-8文件的选项:

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

Since Java 7, the JDK has the new java.nio.file API, which provides many shortcuts, so 3rd party libraries are not always required for simple file operations.

从Java 7开始,JDK就有了新的Java .nio。文件API提供了许多快捷方式,因此对于简单的文件操作,第三方库并不总是必需的。

#14


7  

There is a variation on the same theme that uses a for loop, instead of a while loop, to limit the scope of the line variable. Whether it's "better" is a matter of personal taste.

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

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

#15


5  

public static String slurp (final File file)
throws IOException {
    StringBuilder result = new StringBuilder();

    try {
        BufferedReader reader = new BufferedReader(new FileReader(file));

        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();
}

#16


4  

If you do not have access to Files, you do the next:

如果您无法访问文件,则执行下面的操作:

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);
}

#17


4  

A flexible solution using IOUtils from Apache commons-io in combination with StringWriter:

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

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

It works with any reader or input stream (not just with files), for example when reading from a URL.

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

#18


3  

Be aware when using fileInputStream.available() the returned integer does not have to represent the actual file size, but rather the guessed amount of bytes the system should be able to read from the stream without blocking IO. A safe and simple way could look like this

在使用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();
}

It should be considered that this approach is not suitable for multi-byte character encodings like UTF-8.

应该认为这种方法不适合UTF-8这样的多字节字符编码。

#19


3  

This one uses the method RandomAccessFile.readFully, it seems to be available from JDK 1.0 !

这个使用方法RandomAccessFile。有趣的是,它似乎可以从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
        }
    }
}

#20


3  

You can try Scanner and File class, a few lines solution

您可以尝试扫描器和文件类,一些行解决方案

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

#21


3  

Based on @erickson`s answer, you can use:

根据@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()]));
}

#22


2  

After Ctrl+F'ing after Scanner, I think that the Scanner solution should be listed too. In the easiest to read fashion it goes like this:

按Ctrl+F'ing后,我认为扫描仪的解决方案也应该列出。最容易读懂的时尚是这样的:

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;
}

If you use Java 7 or newer (and you really should) consider using try-with-resources to make the code easier to read. No more dot-close stuff littering everything. But that's mostly a stylistic choice methinks.

如果您使用Java 7或更新的(您确实应该这么做),请考虑使用try-with-resources使代码更易于阅读。不要再把所有的东西都乱扔了。但我认为这主要是一种风格上的选择。

I'm posting this mostly for completionism, since if you need to do this a lot, there should be things in java.nio.file.Files that should do the job better.

我主要是为了完成复杂性而发布这篇文章的,因为如果您需要经常这么做,那么应该在java.nio.file中包含一些内容。应该做得更好的文件。

My suggestion would be to use Files#readAllBytes(Path) to grab all the bytes, and feed it to new String(byte[] Charset) to get a String out of it that you can trust. Charsets will be mean to you during your lifetime, so beware of this stuff now.

我的建议是使用file #readAllBytes(Path)来获取所有的字节,并将其提供给新的字符串(byte[] Charset),从中得到一个您可以信任的字符串。在你的一生中,字符集对你来说是很刻薄的,所以现在要注意这些东西。

Others have given code and stuff, and I don't want to steal their glory. ;)

其他人已经给出了代码和东西,我不想窃取他们的荣耀。,)

#23


2  

Using this library, it is one line:

使用这个图书馆,它是一行:

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

#24


2  

Also if your file happens to be inside a jar, you can also use this:

此外,如果您的文件碰巧在jar中,您还可以使用以下方法:

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

The path should start with / for instance if your jar is

路径应该从/(例如,如果您的jar是)开始

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

Then you want to invoke it like this:

然后你想这样调用它:

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

#25


2  

In one line (Java 8), assuming you have a Reader:

在一行(Java 8)中,假设您有一个读者:

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

#26


1  

I cannot comment other entries yet, so I'll just leave it here.

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

One of best answers here (https://*.com/a/326448/1521167):

最佳答案之一(https://*.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();
}
}

still has one flaw. It always puts new line char in the end of string, which may cause some weirds bugs. My suggestion is to change it to:

还有一个不足之处。它总是在字符串的末尾添加新的行char,这可能会导致一些奇怪的bug。我的建议是:

    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();
    }
}

#27


1  

Gathered all the possible ways to read the File as String from Disk or Network.

收集了从磁盘或网络中读取文件的所有可能方法。

  • Guava: Google using classes Resources, Files

    番石榴:谷歌使用类资源、文件

    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 - COMMONS IO using classes IOUtils, FileUtils

    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") );*/
    }
    

  • Java 8 BufferReader using Stream API

    Java 8 BufferReader使用流API。

    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()));
    }
    

  • Scanner Class with regex \A. which matches the beginning of input.

    带regex \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)

    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 using InputStreamReader.

    使用InputStreamReader BufferedReader。

    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();
    }
    

Example with main method to access the above methods.

用主方法访问上述方法的示例。

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();
    }
}

#28


1  

Using Java 8 (java.nio.file package; no external libraries)

使用Java 8(nio。文件包;没有外部库)

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

#29


0  

Use code:

使用代码:

File file = new File("input.txt");
BufferedInputStream bin = new BufferedInputStream(new FileInputStream(
                file));
byte[] buffer = new byte[(int) file.length()];
bin.read(buffer);
String fileStr = new String(buffer);

fileStr contains output in String.

fileStr包含字符串中的输出。

#30


0  

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
/**
 * A simple example program that reads a text file into a String using Files.lines and stream.
 */
public class ReadTextFileExample {
    public static void main(String[] args) throws IOException {
        String contents = Files.lines(Paths.get("c:\\temp\\testfile.txt")).collect(Collectors.joining("\n"));
        System.out.println(contents);
    }
}

#1


1238  

Read all text from a file

Here's a compact, robust idiom for Java 7, wrapped up in a utility method:

下面是Java 7的一个紧凑、健壮的习惯用法,用实用方法包装:

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

Read lines of text from a file

Java 7 added a convenience method to read a file as lines of text, represented as a List<String>. This approach is "lossy" because the line separators are stripped from the end of each line.

Java 7增加了一种方便的方法,以文本行形式读取文件,以列表 表示。这种方法是“有损”的,因为行分隔符是从每一行的末尾剥离的。

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

In Java 8, BufferedReader added a new method, lines() to produce a Stream<String>. If an IOException is encountered while reading the file, it is wrapped in an UncheckedIOException, since Stream doesn't accept lambdas that throw checked exceptions.

在Java 8中,BufferedReader添加了一个新方法lines()来生成一个流 。如果在读取文件时遇到IOException,它将被包装在UncheckedIOException中,因为流不接受抛出已检查异常的lambdas。

try (BufferedReader r = Files.newBufferedReader(path, encoding)) {
  r.lines().forEach(System.out::println);
}

There is also a Files.lines() method which does something very similar, returning the Stream<String> directly. But I don't like it. The Stream needs a close() call; this is poorly documented on the API, and I suspect many people don't even notice Stream has a close() method. So your code would look very similar, like this:

还有一个Files.lines()方法,它做一些非常类似的事情,直接返回流 。但我不喜欢。该流需要一个close()调用;这在API上是很糟糕的文档,我怀疑很多人甚至没有注意到流有一个close()方法。所以你的代码看起来很相似,像这样:

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

The difference is that you have a Stream assigned to a variable, and I try avoid that as a practice so that I don't accidentally try to invoke the stream twice.

不同之处在于,您有一个分配给变量的流,我尽量避免这种做法,这样我就不会意外地两次调用该流。

Memory utilization

The first method, that preserves line breaks, can temporarily require memory several times the size of the file, because for a short time the raw file contents (a byte array), and the decoded characters (each of which is 16 bits even if encoded as 8 bits in the file) reside in memory at once. It is safest to apply to files that you know to be small relative to the available memory.

第一种方法,保留换行符,可以暂时需要几次内存文件的大小,因为在短时间内的原始文件的内容(一个字节数组)和解码字符(每一个都是16位,即使文件编码为8位)驻留在内存中。最安全的方法是将文件应用到相对于可用内存较小的文件。

The second method, reading lines, is usually more memory efficient, because the input byte buffer for decoding doesn't need to contain the entire file. However, it's still not suitable for files that are very large relative to available memory.

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

For reading large files, you need a different design for your program, one that reads a chunk of text from a stream, processes it, and then moves on to the next, reusing the same fixed-sized memory block. Here, "large" depends on the computer specs. Nowadays, this threshold might be many gigabytes of RAM. The third method, using a Stream<String> is one way to do this, if your input "records" happen to be individual lines. (Using the readLine() method of BufferedReader is the procedural equivalent to this approach.)

对于读取大型文件,您需要为您的程序设计不同的设计,该设计从流中读取一段文本,对其进行处理,然后继续进行下一段,重用相同的固定大小的内存块。在这里,“大”取决于计算机规格。现在,这个阈值可能是千兆字节的RAM。第三种方法是使用流 ,如果您的输入“records”恰好是单独的行,那么这是一种方法。(使用BufferedReader的readLine()方法相当于使用这种方法。)

Character encoding

One thing that is missing from the sample in the original post is the character encoding. There are some special cases where the platform default is what you want, but they are rare, and you should be able justify your choice.

在最初的文章中,缺少的一个东西是字符编码。在某些特殊情况下,平台默认值是您想要的,但它们是罕见的,您应该能够证明您的选择是合理的。

The StandardCharsets class define some constants for the encodings required of all Java runtimes:

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

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

The platform default is available from the Charset class itself:

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

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

Note: This answer largely replaces my Java 6 version. The utility of Java 7 safely simplifies the code, and the old answer, which used a mapped byte buffer, prevented the file that was read from being deleted until the mapped buffer was garbage collected. You can view the old version via the "edited" link on this answer.

注意:这个答案在很大程度上替代了我的Java 6版本。Java 7的实用程序安全地简化了代码,而旧的答案(使用映射字节缓冲区)防止删除被读取的文件,直到映射缓冲区被垃圾收集。您可以通过这个答案上的“编辑”链接查看旧版本。

#2


292  

Commons FileUtils.readFileToString:

下议院FileUtils.readFileToString:

public static String readFileToString(File file)
                       throws IOException

Reads the contents of a file into a String using the default encoding for the VM. The file is always closed.

使用VM的默认编码将文件内容读入字符串。文件总是关闭的。

Parameters:

参数:

  • file - the file to read, must not be null
  • 文件-要读取的文件,不能为空

Returns: the file contents, never null

返回:文件内容,不为空

Throws: - IOException - in case of an I/O error

抛出:- IOException -如果发生I/O错误。

Since: Commons IO 1.3.1

自:共用IO 1.3.1

The code used (indirectly) by that class is:

该类(间接)使用的代码是:

IOUtils.java under Apache Licence 2.0.

IOUtils。Apache license 2.0下的java。

public static long copyLarge(InputStream input, OutputStream output)
       throws IOException {
   byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
   long count = 0;
   int n = 0;
   while (-1 != (n = input.read(buffer))) {
       output.write(buffer, 0, n);
       count += n;
   }
   return count;
}

It is very similar to the one used by Ritche_W.

它与Ritche_W使用的非常相似。

#3


157  

From this page a very lean solution:

从这一页,一个非常精简的解决方案:

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

or

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

If you want to set the charset

如果要设置字符集

#4


68  

If you're looking for an alternative that doesn't involve a third-party library (e.g. Commons I/O), you can use the Scanner class:

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

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();
    }
}

#5


63  

Guava has a method similar to the one from Commons IOUtils that Willi aus Rohr mentioned:

Guava有一种方法,类似于威利奥斯·罗尔提到的下议院IOUtils的一种方法:

import com.google.common.base.Charsets;
import com.google.common.io.Files;

// ...

String text = Files.toString(new File(path), Charsets.UTF_8);

EDIT by Oscar Reyes

编辑由奥斯卡雷耶斯

This is the (simplified) underlying code on the cited library:

这是引用库中的(简化)底层代码:

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 );

Edit (by Jonik): The above doesn't match the source code of recent Guava versions. For the current source, see the classes Files, CharStreams, ByteSource and CharSource in com.google.common.io package.

编辑(由Jonik):上面的代码与最近的Guava版本的源代码不匹配。对于当前源,请参见com.google.common.io包中的类文件、CharStreams、ByteSource和CharSource。

#6


50  

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 "";
    }

#7


44  

If you need a string processing (parallel processing) Java 8 has the great Stream API.

如果您需要一个字符串处理(并行处理),Java 8拥有强大的流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

More examples are available in JDK samples sample/lambda/BulkDataOperations that can be downloaded from Oracle Java SE 8 download page

在可以从Oracle Java SE 8下载页面下载的JDK示例/lambda/BulkDataOperations中有更多的示例

Another one liner example

另一个班轮的例子

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

#8


44  

That code will normalize line breaks, which may or may not be what you really want to do.

该代码将使换行符规范化,这可能是您真正想做的事情。

Here's an alternative which doesn't do that, and which is (IMO) simpler to understand than the NIO code (although it still uses java.nio.charset.Charset):

这里有一个替代方法,它没有这么做,而且(在我看来)比NIO代码更容易理解(尽管它仍然使用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 stream
    FileInputStream 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 them
        stream.close();
    }        
}

#9


37  

String content = new String(Files.readAllBytes(Paths.get("readMe.txt")));

since java 7 you can do it this way.

因为java 7可以这样做。

#10


22  

If it's a text file why not use apache commons-io?

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

It has the following method

它有以下方法

public static String readFileToString(File file) throws IOException

If you want the lines as a list use

如果你想让这些行作为列表使用

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

#11


14  

Java attempts to be extremely general and flexible in all it does. As a result, something which is relatively simple in a scripting language (your code would be replaced with "open(file).read()" in python) is a lot more complicated. There doesn't seem to be any shorter way of doing it, except using an external library (like Willi aus Rohr mentioned). Your options:

Java试图在它所做的一切中变得非常通用和灵活。因此,在脚本语言中相对简单的东西(您的代码将被python中的“open(file).read()”替换)要复杂得多。除了使用外部库(如Willi aus Rohr提到的那样)之外,似乎没有任何更短的方法可以完成这一任务。你的选择:

  • Use an external library.
  • 使用一个外部的库。
  • Copy this code into all your projects.
  • 将此代码复制到所有项目中。
  • Create your own mini-library which contains functions you use often.
  • 创建您自己的迷你库,其中包含您经常使用的函数。

Your best bet is probably the 2nd one, as it has the least dependencies.

你最好的选择可能是第2个,因为它的依赖性最小。

#12


14  

To read a File as binary and convert at the end

以二进制形式读取文件并在末尾进行转换

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();
    }
}

#13


12  

With Java 7, this is my preferred option to read a UTF-8 file:

使用Java 7,这是我首选的阅读UTF-8文件的选项:

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

Since Java 7, the JDK has the new java.nio.file API, which provides many shortcuts, so 3rd party libraries are not always required for simple file operations.

从Java 7开始,JDK就有了新的Java .nio。文件API提供了许多快捷方式,因此对于简单的文件操作,第三方库并不总是必需的。

#14


7  

There is a variation on the same theme that uses a for loop, instead of a while loop, to limit the scope of the line variable. Whether it's "better" is a matter of personal taste.

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

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

#15


5  

public static String slurp (final File file)
throws IOException {
    StringBuilder result = new StringBuilder();

    try {
        BufferedReader reader = new BufferedReader(new FileReader(file));

        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();
}

#16


4  

If you do not have access to Files, you do the next:

如果您无法访问文件,则执行下面的操作:

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);
}

#17


4  

A flexible solution using IOUtils from Apache commons-io in combination with StringWriter:

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

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

It works with any reader or input stream (not just with files), for example when reading from a URL.

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

#18


3  

Be aware when using fileInputStream.available() the returned integer does not have to represent the actual file size, but rather the guessed amount of bytes the system should be able to read from the stream without blocking IO. A safe and simple way could look like this

在使用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();
}

It should be considered that this approach is not suitable for multi-byte character encodings like UTF-8.

应该认为这种方法不适合UTF-8这样的多字节字符编码。

#19


3  

This one uses the method RandomAccessFile.readFully, it seems to be available from JDK 1.0 !

这个使用方法RandomAccessFile。有趣的是,它似乎可以从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
        }
    }
}

#20


3  

You can try Scanner and File class, a few lines solution

您可以尝试扫描器和文件类,一些行解决方案

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

#21


3  

Based on @erickson`s answer, you can use:

根据@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()]));
}

#22


2  

After Ctrl+F'ing after Scanner, I think that the Scanner solution should be listed too. In the easiest to read fashion it goes like this:

按Ctrl+F'ing后,我认为扫描仪的解决方案也应该列出。最容易读懂的时尚是这样的:

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;
}

If you use Java 7 or newer (and you really should) consider using try-with-resources to make the code easier to read. No more dot-close stuff littering everything. But that's mostly a stylistic choice methinks.

如果您使用Java 7或更新的(您确实应该这么做),请考虑使用try-with-resources使代码更易于阅读。不要再把所有的东西都乱扔了。但我认为这主要是一种风格上的选择。

I'm posting this mostly for completionism, since if you need to do this a lot, there should be things in java.nio.file.Files that should do the job better.

我主要是为了完成复杂性而发布这篇文章的,因为如果您需要经常这么做,那么应该在java.nio.file中包含一些内容。应该做得更好的文件。

My suggestion would be to use Files#readAllBytes(Path) to grab all the bytes, and feed it to new String(byte[] Charset) to get a String out of it that you can trust. Charsets will be mean to you during your lifetime, so beware of this stuff now.

我的建议是使用file #readAllBytes(Path)来获取所有的字节,并将其提供给新的字符串(byte[] Charset),从中得到一个您可以信任的字符串。在你的一生中,字符集对你来说是很刻薄的,所以现在要注意这些东西。

Others have given code and stuff, and I don't want to steal their glory. ;)

其他人已经给出了代码和东西,我不想窃取他们的荣耀。,)

#23


2  

Using this library, it is one line:

使用这个图书馆,它是一行:

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

#24


2  

Also if your file happens to be inside a jar, you can also use this:

此外,如果您的文件碰巧在jar中,您还可以使用以下方法:

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

The path should start with / for instance if your jar is

路径应该从/(例如,如果您的jar是)开始

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

Then you want to invoke it like this:

然后你想这样调用它:

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

#25


2  

In one line (Java 8), assuming you have a Reader:

在一行(Java 8)中,假设您有一个读者:

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

#26


1  

I cannot comment other entries yet, so I'll just leave it here.

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

One of best answers here (https://*.com/a/326448/1521167):

最佳答案之一(https://*.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();
}
}

still has one flaw. It always puts new line char in the end of string, which may cause some weirds bugs. My suggestion is to change it to:

还有一个不足之处。它总是在字符串的末尾添加新的行char,这可能会导致一些奇怪的bug。我的建议是:

    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();
    }
}

#27


1  

Gathered all the possible ways to read the File as String from Disk or Network.

收集了从磁盘或网络中读取文件的所有可能方法。

  • Guava: Google using classes Resources, Files

    番石榴:谷歌使用类资源、文件

    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 - COMMONS IO using classes IOUtils, FileUtils

    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") );*/
    }
    

  • Java 8 BufferReader using Stream API

    Java 8 BufferReader使用流API。

    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()));
    }
    

  • Scanner Class with regex \A. which matches the beginning of input.

    带regex \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)

    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 using InputStreamReader.

    使用InputStreamReader BufferedReader。

    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();
    }
    

Example with main method to access the above methods.

用主方法访问上述方法的示例。

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();
    }
}

#28


1  

Using Java 8 (java.nio.file package; no external libraries)

使用Java 8(nio。文件包;没有外部库)

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

#29


0  

Use code:

使用代码:

File file = new File("input.txt");
BufferedInputStream bin = new BufferedInputStream(new FileInputStream(
                file));
byte[] buffer = new byte[(int) file.length()];
bin.read(buffer);
String fileStr = new String(buffer);

fileStr contains output in String.

fileStr包含字符串中的输出。

#30


0  

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
/**
 * A simple example program that reads a text file into a String using Files.lines and stream.
 */
public class ReadTextFileExample {
    public static void main(String[] args) throws IOException {
        String contents = Files.lines(Paths.get("c:\\temp\\testfile.txt")).collect(Collectors.joining("\n"));
        System.out.println(contents);
    }
}