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

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

当前回答

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

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

其他回答

使用JDK 8或更高版本:

未使用外部库

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

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

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

Guava:Google使用类资源,文件静态字符集字符集=com.google.common.base.Charsets.UTF_8;公共静态字符串guava_ServerFile(URL URL)引发IOException{return Resources.toString(url,charset);}公共静态字符串guava_DiskFile(文件文件)引发IOException{return Files\toString(文件,字符集);}


APACHE-COMMONS IO使用IOUItils、FileUtils类静态字符集编码=org.apache.mons.io.Charsets.UTF_8;公共静态字符串commons_IOUtils(URL URL)引发IOException{java.io.InputStream in=url.openStream();尝试{return IOUtils.toString(in,编码);}最后{IOUItils.close安静(in);}}公共静态字符串commons_FileUtils(文件文件)引发IOException{return FileUtils.readFileToString(文件,编码);/*List<String>lines=FileUtils.readLines(文件名,编码);return lines.stream().collector(Collectors.joining(“\n”))*/}


使用流API的Java 8 BufferReader公共静态字符串streamURL_Buffer(URL URL)引发IOException{java.io.InputStream source=url.openStream();BufferedReader读取器=新的BufferedReader(新的InputStreamReader(源));//List<String>lines=reader.lines().collector(Collectors.toList());return reader.line().collector(Collectors.joining(System.lineSeparator()));}公共静态字符串streamFile_Buffer(文件文件)引发IOException{BufferedReader读取器=新的BufferedReader(新的FileReader(文件));return reader.line().collector(Collectors.joining(System.lineSeparator()));}


带有正则表达式\A的扫描程序类。其匹配输入的开始。静态字符串字符集名称=java.nio.charset.StandardCharsets.UTF_8.toString();公共静态字符串streamURL_Scanner(URL URL)引发IOException{java.io.InputStream source=url.openStream();Scanner Scanner=新扫描仪(源,charsetName)。使用分隔符(“\\A”);return scanner.hasNext()?scanner.next():“”;}公共静态字符串streamFile_Scanner(文件文件)引发IOException{Scanner Scanner=新扫描仪(文件,charsetName)。使用分隔符(“\\A”);return scanner.hasNext()?scanner.next():“”;}


Java 7(Java.nio.file.Files.readAllBytes)公共静态字符串getDiskFile_Java7(文件文件)引发IOException{byte[]readAllBytes=java.nio.file.Files.readAllBytes(Paths.get(file.getAbsolutePath()));返回新字符串(readAllBytes);}


BufferedReader使用InputStreamReader。公共静态字符串getDiskFile_Lines(文件文件)引发IOException{StringBuffer text=新StringBuffer();FileInputStream fileStream=新的FileInputStream(文件);BufferedReader br=新的BufferedReader(新的InputStreamReader(fileStream));for(字符串行;(行=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();
    }
}

@see

将InputStream转换为字符串的方法

如果您需要字符串处理(并行处理),Java8有很棒的StreamAPI。

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

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

另一个单线示例

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

如果您愿意使用外部库,请查看ApacheCommonsIO(200KBJAR)。它包含一个org.apache.commons.io.FileUtils.readFileToString()方法,该方法允许您用一行代码将整个文件读取为字符串。

例子:

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

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

这里有一个替代方案,它没有做到这一点,而且比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 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();
    }        
}