温馨提示×

java怎么从文件读取数据

小亿
93
2023-10-24 17:09:28
栏目: 编程语言

在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替换为要读取的实际文件路径。这些代码将逐行读取文件的内容并将其打印到控制台上。

0