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

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

当前回答

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

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

其他回答

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

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

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

如果您无权访问Files类,则可以使用本机解决方案。

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