从 Java 资源中读取文件

Haider Ali 2022年4月27日
从 Java 资源中读取文件

本文将展示如何使用 Java 编程语言从资源中读取文件。你只需要一个源文件路径。

在 Java 中如何从资源中读取文件

你可以通过 Java 编程语言读取任何文本文件。你需要做的就是将源路径存储在字符串中,并使用 try...catch 方法将此路径提供给 BufferedReader。看看下面的代码。

import java.io.*;
public class Main 
{
    public static void main(String[] args) 
    {
        String  sourcePath = "D:\\delftstack.txt";   // source file path To Read..
        try 
        {
            BufferedReader Reader = new BufferedReader(new FileReader(sourcePath));
            //Intializing  Buffer Reader By Providing File path
            String Data;  
            while((Data = Reader.readLine()) != null)
            {
              System.out.println(Data);   //Reading Line By Line.....
            }
            Reader.close();
        } catch(Exception e) {}
    }
}

我们将逐行解释代码。首先,将源文件路径存储在字符串 sourcepath 中,复制你的源路径,然后执行相同操作。我们使用 try...catch 方法,因为它返回一个未处理的异常 FileNotFoundException

我们将源路径的字符串传递给一个名为 BufferedReader 的对象。它从字符输入流中读取文本。在这里了解更多关于 BufferedReader

我们将使用 while 循环将它存储在一个字符串中,无论这个缓冲区将读取什么。所有数据都被逐行读取并存储在一个字符串中。我们只是打印那个字符串。

确保写入正确的源路径和文件名。

Author: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn

相关文章 - Java File