java中如何获取文件内容?

发布于 2024-10-31 14:08:26 字数 328 浏览 2 评论 0原文

为了获取txt文件的内容,我通常使用扫描仪并迭代每一行来获取内容:

Scanner sc = new Scanner(new File("file.txt"));
while(sc.hasNextLine()){
    String str = sc.nextLine();                     
}

java api是否提供了一种通过一行代码获取内容的方法,例如:

String content = FileUtils.readFileToString(new File("file.txt"))

to get the content of a txt file I usually use a scanner and iterate over each line to get the content:

Scanner sc = new Scanner(new File("file.txt"));
while(sc.hasNextLine()){
    String str = sc.nextLine();                     
}

Does the java api provide a way to get the content with one line of code like:

String content = FileUtils.readFileToString(new File("file.txt"))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

遗弃M 2024-11-07 14:08:26

不是内置 API - 但 Guava 可以,还有其他宝藏。 (这是一个很棒的库。)

String content = Files.toString(new File("file.txt"), Charsets.UTF_8);

有类似的方法可以读取任何 Readable,或者将二进制文件的全部内容加载为字节数组,或者将文件读入字符串列表等。

请注意,此方法现已弃用。新的等价物是:

String content = Files.asCharSource(new File("file.txt"), Charsets.UTF_8).read();

Not the built-in API - but Guava does, amongst its other treasures. (It's a fabulous library.)

String content = Files.toString(new File("file.txt"), Charsets.UTF_8);

There are similar methods for reading any Readable, or loading the entire contents of a binary file as a byte array, or reading a file into a list of strings, etc.

Note that this method is now deprecated. The new equivalent is:

String content = Files.asCharSource(new File("file.txt"), Charsets.UTF_8).read();
嗼ふ静 2024-11-07 14:08:26

Java 7 中有一个符合这些原则的 API。

Files.readAllLines(路径路径,字符集cs)

With Java 7 there is an API along those lines.

Files.readAllLines(Path path, Charset cs)

嘿嘿嘿 2024-11-07 14:08:26

commons-io 具有:

IOUtils.toString(new FileReader("file.txt"), "utf-8");

commons-io has:

IOUtils.toString(new FileReader("file.txt"), "utf-8");
夕色琉璃 2024-11-07 14:08:26
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public static void main(String[] args) throws IOException {
    String content = Files.readString(Paths.get("foo"));
}

来自 https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html#readString(java.nio .文件.路径)

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public static void main(String[] args) throws IOException {
    String content = Files.readString(Paths.get("foo"));
}

From https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html#readString(java.nio.file.Path)

身边 2024-11-07 14:08:26

您可以将 FileReader 类与 BufferedReader 一起使用来读取文本文件。

File fileToRead = new File("file.txt");

try( FileReader fileStream = new FileReader( fileToRead ); 
    BufferedReader bufferedReader = new BufferedReader( fileStream ) ) {

    String line = null;

    while( (line = bufferedReader.readLine()) != null ) {
        //do something with line
    }

    } catch ( FileNotFoundException ex ) {
        //exception Handling
    } catch ( IOException ex ) {
        //exception Handling
}

You could use the FileReader class together with the BufferedReader to read the text file.

File fileToRead = new File("file.txt");

try( FileReader fileStream = new FileReader( fileToRead ); 
    BufferedReader bufferedReader = new BufferedReader( fileStream ) ) {

    String line = null;

    while( (line = bufferedReader.readLine()) != null ) {
        //do something with line
    }

    } catch ( FileNotFoundException ex ) {
        //exception Handling
    } catch ( IOException ex ) {
        //exception Handling
}
南烟 2024-11-07 14:08:26

经过一些测试,我发现 BufferedReader 和 Scanner 在各种情况下都有问题(前者经常无法检测新行,后者经常删除空格,例如,由 org.json 库导出的 JSON 字符串)。还有其他可用的方法,但问题是它们仅在某些 Java 版本之后才受支持(例如,这对 Android 开发人员来说很糟糕),并且您可能不想仅出于这样的单一目的使用 Guava 或 Apache commons 库。因此,我的解决方案是将整个文件作为字节读取并将其转换为字符串。下面的代码取自我的一个爱好项目:

    /**
     * Get byte array from an InputStream most efficiently.
     * Taken from sun.misc.IOUtils
     * @param is InputStream
     * @param length Length of the buffer, -1 to read the whole stream
     * @param readAll Whether to read the whole stream
     * @return Desired byte array
     * @throws IOException If maximum capacity exceeded.
     */
    public static byte[] readFully(InputStream is, int length, boolean readAll)
            throws IOException {
        byte[] output = {};
        if (length == -1) length = Integer.MAX_VALUE;
        int pos = 0;
        while (pos < length) {
            int bytesToRead;
            if (pos >= output.length) {
                bytesToRead = Math.min(length - pos, output.length + 1024);
                if (output.length < pos + bytesToRead) {
                    output = Arrays.copyOf(output, pos + bytesToRead);
                }
            } else {
                bytesToRead = output.length - pos;
            }
            int cc = is.read(output, pos, bytesToRead);
            if (cc < 0) {
                if (readAll && length != Integer.MAX_VALUE) {
                    throw new EOFException("Detect premature EOF");
                } else {
                    if (output.length != pos) {
                        output = Arrays.copyOf(output, pos);
                    }
                    break;
                }
            }
            pos += cc;
        }
        return output;
    }

    /**
     * Read the full content of a file.
     * @param file The file to be read
     * @param emptyValue Empty value if no content has found
     * @return File content as string
     */
    @NonNull
    public static String getFileContent(@NonNull File file, @NonNull String emptyValue) {
        if (file.isDirectory()) return emptyValue;
        try {
            return new String(readFully(new FileInputStream(file), -1, true), Charset.defaultCharset());
        } catch (IOException e) {
            e.printStackTrace();
            return emptyValue;
        }
    }

您可以简单地使用 getFileContent(file, "") 来读取文件的内容。

After a bit of testing, I find BufferedReader and Scanner both problematic under various circumstances (the former often fails to detect new lines and the latter often strips spaces, for instance, from a JSON string exported by org.json library). There are other methods available but the problem is they are only supported after certain Java versions (which is bad for an Android developer, for example) and you might not want to use Guava or Apache commons library just for a single purpose like this. Hence, my solution is to read the whole file as bytes and convert it to string. The code below are taken from one of my hobby projects:

    /**
     * Get byte array from an InputStream most efficiently.
     * Taken from sun.misc.IOUtils
     * @param is InputStream
     * @param length Length of the buffer, -1 to read the whole stream
     * @param readAll Whether to read the whole stream
     * @return Desired byte array
     * @throws IOException If maximum capacity exceeded.
     */
    public static byte[] readFully(InputStream is, int length, boolean readAll)
            throws IOException {
        byte[] output = {};
        if (length == -1) length = Integer.MAX_VALUE;
        int pos = 0;
        while (pos < length) {
            int bytesToRead;
            if (pos >= output.length) {
                bytesToRead = Math.min(length - pos, output.length + 1024);
                if (output.length < pos + bytesToRead) {
                    output = Arrays.copyOf(output, pos + bytesToRead);
                }
            } else {
                bytesToRead = output.length - pos;
            }
            int cc = is.read(output, pos, bytesToRead);
            if (cc < 0) {
                if (readAll && length != Integer.MAX_VALUE) {
                    throw new EOFException("Detect premature EOF");
                } else {
                    if (output.length != pos) {
                        output = Arrays.copyOf(output, pos);
                    }
                    break;
                }
            }
            pos += cc;
        }
        return output;
    }

    /**
     * Read the full content of a file.
     * @param file The file to be read
     * @param emptyValue Empty value if no content has found
     * @return File content as string
     */
    @NonNull
    public static String getFileContent(@NonNull File file, @NonNull String emptyValue) {
        if (file.isDirectory()) return emptyValue;
        try {
            return new String(readFully(new FileInputStream(file), -1, true), Charset.defaultCharset());
        } catch (IOException e) {
            e.printStackTrace();
            return emptyValue;
        }
    }

You can simply use getFileContent(file, "") to read the content of a file.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文