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

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

当前回答

请注意,当使用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等多字节字符编码。

其他回答

基于扫描仪的非常精简的解决方案:

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

或者,如果要设置字符集:

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

或者,使用trywithresources块,它将为您调用scanner.close():

try (Scanner scanner = new Scanner( new File("poem.txt"), "UTF-8" )) {
    String text = scanner.useDelimiter("\\A").next();
}

请记住,Scanner构造函数可以引发IOException。不要忘记导入java.io和java.util。

来源:Pat Niemeyer的博客

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

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

用户java.nio.Files读取文件的所有行。

public String readFile() throws IOException {
        File fileToRead = new File("file path");
        List<String> fileLines = Files.readAllLines(fileToRead.toPath());
        return StringUtils.join(fileLines, StringUtils.EMPTY);
}
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

Java 7

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

Java 11

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

这一个使用RandomAccessFile.readFully方法,它似乎可以从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
        }
    }
}