gpt4 book ai didi

java - 访问外部文件Java

转载 作者:行者123 更新时间:2023-12-01 16:54:03 25 4
gpt4 key购买 nike

我正在用 Java 创建一个任务列表应用程序,但在尝试从我的代码中访问外部文件时遇到问题。这是我到目前为止所拥有的:

import java.io.*;
import java.util.Scanner;

public class Main {

public static String fileName = "Users/bobsmith/Desktop/tasklistjava/src/javatask.txt";

public static void main(String[] args) throws IOException {

int menuItem = -1;
while(menuItem != 0){
menuItem = menu();
switch (menuItem){
case 1:
showTaskList();
break;
case 2:
addTask();
break;
case 3:
sortList();
break;
case 0:
break;
default:
System.out.println("Invalid Input");

}
}
}
static int menu(){
int choice;
Scanner sc = new Scanner(System.in);
System.out.println("\n Task List Menu \n");
System.out.println("0: Exit Menu");
System.out.println("1: Show Tasks in List");
System.out.println("2: Add Task to List");
System.out.println("3: Sort Tasks by Due Date");
System.out.println();
System.out.println("Enter a Task: ");
choice = sc.nextInt();
return choice;
}

static void showTaskList(){
System.out.println("\nTask List\n");
try {
Scanner inFile = new Scanner(new FileReader(fileName));
String line;
int number = 1;
while(inFile.hasNextLine()){
line = inFile.nextLine();
System.out.println(number + " ");
System.out.println(line);
++number;
}
System.out.println();
inFile.close();
} catch (FileNotFoundException ioe) {
System.out.println("Can't Access File");
}
}

static void addTask(){
System.out.println("\nAdd Task\n");
try {
Scanner input = new Scanner(System.in);
PrintWriter outFile = new PrintWriter(new FileWriter(fileName, true));
System.out.println("Enter a Task: ");
String addedTask = input.nextLine();
System.out.println("You Must set a Due Date for this task: ");
String dueDate = input.nextLine();
outFile.println(addedTask + " " + dueDate);
outFile.close();
} catch (IOException ioe) {
System.out.println("Can't Access File");
}
}
static void sortList(){}

}

当我输入选项 1 或 2 时,我收到“无法访问文件”错误。这可能只是外部文件的错误链接吗?和建议有帮助。

最佳答案

所谓的无法访问文件错误是由您创建的:

System.out.println("Can't Access File");

当无法找到给定的文件路径和/或文件名时触发此错误,即:FileNotFoundException

确保您提供正确的文件名和/或文件路径。

关于java - 访问外部文件Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35232346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com