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

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

当前回答

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

private String readFile(String pathname) throws IOException {

    File file = new File(pathname);
    StringBuilder fileContents = new StringBuilder((int)file.length());        

    try (Scanner scanner = new Scanner(file)) {
        while(scanner.hasNextLine()) {
            fileContents.append(scanner.nextLine() + System.lineSeparator());
        }
        return fileContents.toString();
    }
}

其他回答

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

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

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

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

将文件读取为二进制文件并在末尾转换

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

请注意,当使用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();
}

应该考虑的是,这种方法不适用于UTF-8等多字节字符编码。

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

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转换为字符串的方法