Java指定文件打印练习报错求助:try-with-resources语法问题
解决Java读取用户指定文件内容的问题
看起来你碰到了两个核心问题:一是try-with-resources的语法错误,二是对如何用用户输入的文件名创建文件读取流的困惑。咱们一步步来解决:
问题分析
- 类型不匹配错误:你写的
try(scanner = Paths.get(fileName))完全不对——Paths.get(fileName)返回的是Path对象,不是Scanner,根本没法赋值给Scanner类型的变量。 - Java 8 try-with-resources限制:错误提示“variables in try-with-resources are not supported in -source 8”是因为Java 8要求try-with-resources括号里必须声明新的资源变量,不能复用外面已经定义好的变量(比如你开头创建的
scanner)。
修正后的代码
import java.nio.file.Paths; import java.util.Scanner; public class PrintingASpecifiedFile { public static void main(String[] args) { // 先读取用户输入的文件名 Scanner inputScanner = new Scanner(System.in); System.out.println("Which file should have its contents printed?"); String fileName = inputScanner.nextLine(); inputScanner.close(); // 关闭输入用的Scanner // 用用户输入的文件名创建文件读取的Scanner,放在try-with-resources里 try(Scanner fileScanner = new Scanner(Paths.get(fileName))) { while (fileScanner.hasNextLine()){ String output = fileScanner.nextLine(); System.out.println(output); } } catch (Exception e){ System.out.println("Error: " + e.getMessage()); } } }
关键修正点
- 把输入用的Scanner和文件读取用的Scanner分开命名(比如
inputScanner和fileScanner),避免混淆,也符合Java 8对try-with-resources的要求——在括号里声明新的资源变量。 - 正确创建文件读取的Scanner:
new Scanner(Paths.get(fileName)),这才是把用户输入的文件名转换成Path,再传入Scanner的正确写法。 - 读取完文件名后,关闭输入用的
inputScanner(当然你也可以把它放进另一个try-with-resources块里,更规范)。
额外提示
如果你的项目确实在用Java 8,要确保IDE或编译命令的source/target版本设置为1.8,不然也可能出现奇怪的兼容性问题。另外,catchException虽然能捕获所有异常,但如果想更精准,可以单独捕获IOException(文件相关的异常),不过对入门练习来说,用Exception也没问题。
内容的提问来源于stack exchange,提问作者beginner1231
相关产品推荐
相关产品推荐

