java - 打印指定文件练习 Java
问题描述
参加 Java 初学者课程,我被困在其中一个练习上。我们的目的是打印特定文件中的文本,我们可以通过用户输入的文件名找到该文件。在之前的练习中,我们了解到
try(Scanner scanner = new Scanner(Paths.get("data.txt")))
会在文件“data.txt”中找到文本,但我不确定如何将其转换为查找用户输入的任何文件名。
更多详情如下。
练习:编写一个程序,询问用户一个字符串,然后打印一个名称与提供的字符串匹配的文件的内容。您可以假设用户提供了程序可以找到的文件名。
练习模板包含文件“data.txt”和“song.txt”,您可以在测试程序功能时使用它们。当用户输入字符串“song.txt”时,程序的输出如下所示。打印的内容来自文件“song.txt”。自然,该程序也应该使用其他文件名,假设可以找到该文件。
到目前为止,我的代码是:
import java.nio.file.Paths;
import java.util.Scanner;
public class PrintingASpecifiedFile {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Which file should have its contents printed?");
String fileName = scanner.nextLine();
//try(Scanner scanner = new Scanner(Paths.get(fileName))) {
try(scanner = Paths.get(fileName)) { // this part of the code is underlined red
while (scanner.hasNextLine()){
String output = scanner.nextLine();
System.out.println(output);
}
}
catch (Exception e){
System.out.println("Error: " + e.getMessage());
}
}
}
我曾尝试搜索如何添加新扫描仪,因为这是一个建议,但每次我尝试它都会出错。“尝试”部分也带有红色下划线,似乎无法弄清楚原因。带下划线的红色部分表示try-with-resources 中的变量在 -source 8 中不受支持
如果有人有提示,我将不胜感激!谢谢!
解决方案
您使用了一个Scanner
从控制台读取文件路径。
您需要其他 Scanner
(或阅读器替代品)来阅读文件。
try (Scanner fileScanner = new Scanner(fileName)) {
try (Scanner fileScanner = new Scanner(Paths.get(fileName))) {
推荐阅读
- javascript - node-celery client.call('task') 从不执行/完成?
- node.js - 通过块 Node.js 从 Google Cloud Storage GCS 下载文件
- swift - SwiftUI ScrollView 只允许对某些单元格进行 HitTesting
- python - 为什么我的 tensorflow 模型将二进制分类标签从 0 和 1 转换为 .7?
- reactjs - 测试静态方法时,preloadWeek 方法未定义
- ios - Swift 图片元数据创建日期
- reactjs - 如何将输入字段用作搜索字段并存储注册数据?
- node.js - 我的承诺中未定义数据无法正确设置错误 [API 问题/前端问题?]
- node.js - 如何解决我在使用 docker 容器时遇到的 dns 问题?
- r - 如果某个级别的所有观察值都具有相同的值,我如何对列进行变异以返回一个值?