Scanner 读取文件相关

本文介绍了如何在Java中使用Scanner类从文件中读取内容,强调了不能直接将文件名作为字符串传递给Scanner构造函数,以及处理FileNotFoundException的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

从 java 核心技术了解到

Scanner 类可用于读取文件


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScannerTest {
    public static void main(String[] args) {
        try {
            // 此处表明该文件在项目根目录下
            File file = new File("text.txt");
            // Scanner in = new Scanner(Paths.get("niyflle.txt"), "UTF-8");
            // System.out.println(System.getProperty("user.dir")); //获取当前项目的相对位置
            // System.out.println(file.getAbsolutePath()); // 获取当前file对象指向的的相对位置
            Scanner sc = new Scanner(file,"utf-8");
            while (sc.hasNext()) {
                String temp = sc.nextLine();
                System.out.println(temp);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

但需注意不可直接在Scanner中传入路径参数 “Scanner(“text.txt”)” ,里面的 “text.txt” 会被当成字符串

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值