You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GroovyConsole获取文件名输入报错求助:学生成绩文件处理项目遇阻

解决Groovy读取文件名输入报错的问题

你的代码报错主要有两个核心原因:

  1. System.console()在IDE的运行窗口中会返回null,调用readLine时触发空指针异常——很多IDE的控制台并非标准系统控制台,无法通过该方法获取输入。
  2. readLine是方法调用,虽Groovy允许省略括号,但规范写法需加上()。

给你两种可行的解决方式:

方式一:用Scanner类(通用适配,IDE中也能正常运行)

这是兼容性更强的写法,适配绝大多数运行环境:

class Main {
    static void main(String[] args) {
        print("Enter the name of the file: ")
        def scanner = new Scanner(System.in)
        def fileName = scanner.nextLine()
        println(fileName)
        scanner.close()
    }
}

方式二:修复System.console()调用(仅命令行运行有效)

若坚持使用System.console(),需先判空,且必须在命令行中执行脚本,不能在IDE内运行:

class Main {
    static void main(String[] args) {
        def console = System.console()
        if (console == null) {
            println("无法获取控制台,请在命令行运行此程序")
            System.exit(1)
        }
        print("Enter the name of the file: ")
        def fileName = console.readLine()
        println(fileName)
    }
}

另外补充:Groovy类名首字母建议大写(虽非强制,但符合Java/Groovy命名规范),main方法参数写成String[] args能增强代码可读性。

内容的提问来源于stack exchange,提问作者s k y l i n e

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 05:52:34