java怎么从文件读取数据

   2025-02-15 8530
核心提示:在Java中,你可以使用java.io包中的FileInputStream或BufferedReader类来从文件中读取数据。使用FileInputStream类的示例代码如

在Java中,你可以使用java.io包中的FileInputStreamBufferedReader类来从文件中读取数据。

使用FileInputStream类的示例代码如下:

import java.io.FileInputStream;import java.io.IOException;public class ReadFileExample {    public static void main(String[] args) {        try {            FileInputStream fileInputStream = new FileInputStream("path/to/file.txt");            int data;            while ((data = fileInputStream.read()) != -1) {                System.out.print((char) data);            }            fileInputStream.close();        } catch (IOException e) {            e.printStackTrace();        }    }}

使用BufferedReader类的示例代码如下:

import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;public class ReadFileExample {    public static void main(String[] args) {        try {            BufferedReader bufferedReader = new BufferedReader(new FileReader("path/to/file.txt"));            String line;            while ((line = bufferedReader.readLine()) != null) {                System.out.println(line);            }            bufferedReader.close();        } catch (IOException e) {            e.printStackTrace();        }    }}

在这两个示例中,你需要将path/to/file.txt替换为要读取的实际文件路径。这些代码将逐行读取文件的内容并将其打印到控制台上。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言