21xrx.com
2024-06-03 01:28:56 Monday
登录
文章检索 我的文章 写文章
Java如何读取当前目录下的文件内容
2023-06-16 18:24:10 深夜i     --     --
Java 读取文件 当前目录 File类 BufferedReader类 文件流

在Java编程中,我们经常需要读取本地文件的内容。如果文件在当前目录下,该怎么办呢?本文将介绍如何使用Java代码读取当前目录下文件的内容。

首先,我们需要获取当前目录的路径。可以使用Java提供的System.getProperty()方法获取当前用户工作目录的路径:


String currentPath = System.getProperty("user.dir");

获取当前目录路径之后,我们便可以使用Java的File类来读取文件。假设我们要读取文件名为example.txt的文件,可以使用如下代码:


File file = new File(currentPath + File.separator + "example.txt");

其中,currentPath + File.separator可获取文件的完整路径。接下来,我们可以使用Java的BufferedReader类来读取文件的内容:


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

String content = "";

String line = null;

while((line = reader.readLine()) != null){

  content += line;

}

reader.close();

这段代码将文件内容读取到一个字符串变量content中。如果需要按行读取文件内容,可以在while循环中逐行读取。读取完成后,切记关闭文件流。

文章

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复