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

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

当前回答

您可以尝试扫描程序和文件类,几行解决方案

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

其他回答

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

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

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

如果您正在寻找不涉及第三方库(例如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();
    }
}

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

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

此外,如果您的文件恰好位于jar中,您也可以使用此选项:

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

例如,如果您的jar是

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

然后你想这样调用它:

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

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

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的博客