前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java读取文件的方法

Java读取文件的方法

作者头像
鳄鱼儿
发布2024-05-21 16:22:22
1150
发布2024-05-21 16:22:22
举报

java.io.File

通常,我们可以使用 java.io.File 类来表示文件和目录,然后使用 java.io.FileReader 类来读取文件的内容。

代码语言:javascript
复制
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileExample {
  public static void main(String[] args) {
    // 创建文件对象
    String filePath = "./path/fileTest.txt";
    File file = new File(filePath);

    try (FileReader reader = new FileReader(file)) {
      // 读取文件内容
      int c;
      while ((c = reader.read()) != -1) {
        System.out.print((char)c);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

首先创建了一个 File 对象,该对象表示要读取的文件。然后,我们使用 FileReader 类的构造函数创建了一个 FileReader 对象,该对象允许我们从文件中读取内容。

获取到文件对象后,我们再使用 while 循环不断地调用 read() 方法读取文件内容,直到返回 -1 为止。每次调用 read() 方法都会返回下一个字符的 ASCII 码,我们将其强制转换为字符并打印出来。

但是, FileReader 读取文件时,文件必须是文本文件(例如,.txt 文件)。如果要读取二进制文件(例如,.jpg 或 .mp3 文件),则应使用 java.io.FileInputStream 类。

java.io.FileInputStream

java.io.FileInputStream 类是文件字节输入流,是万能的,即任何类型的文件都可以采用这个流来读,因为所有的文件都是由字节组成的。

要使用 java.io.FileInputStream,需要导入 java.io 包,然后创建 FileInputStream 类的实例。您可以通过调用构造函数 FileInputStream(String name) 来完成此操作,其中 name 是您要读取的文件的名称。

以下是如何使用 FileInputStream 读取文件内容的示例:

代码语言:javascript
复制
public void testFileInputStream() {
    FileInputStream fileInputStream = null;
    try {
        //1. 实例化File类的对象,指明要操作的文件
        File file = new File("hello.txt");

        //2.提供具体的流
        fileInputStream = new FileInputStream(file);

        //3. 数据的读入
        int data = fileInputStream.read();
        while (data != -1) {
            System.out.print((char)data);
            data= fileInputStream.read();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //4. 流的关闭操作
        try {
            if (fileInputStream != null) {
                fileInputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

try-catch 语句确保 FileInputStreamtry 块完成后关闭,使用 finally 块来关闭 FileInputStream

也可以使用 try-with-resources 语句关闭FileInputStream,如下:

代码语言:javascript
复制
import java.io.FileInputStream;
import java.io.IOException;

public class Main {
  public static void main(String[] args) {
    String fileName = "test.txt";
    try (FileInputStream fis = new FileInputStream(fileName)) {
      int c;
      while ((c = fis.read()) != -1) {
        // process the byte read from the file
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-05-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • java.io.File 类
  • java.io.FileInputStream 类
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档