Reputation: 167
I'm creating a Task-list application in Java but am running into a problem trying to access an external file from within my code. This is what I have so far:
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(){}
}
When I enter choices 1 or 2 I get the "can't access file" error. Could this just be a bad link to the external file? And suggestions help.
Upvotes: 0
Views: 2957
Reputation: 557
I tried running the code. You need to mention the full path to your file e.g. C:/tempDir/xyz.txt. Also the exception you are throwing is misleading. Even if you have an IOE, you are throwing "Can't Access the file" which point your app is not able to access the file which is not the case. It should be System.out.println(ioe); This is tell you the actual error.
Upvotes: 1
Reputation: 17454
Your so called can't access file
error is created by you:
System.out.println("Can't Access File");
What triggers this is when the given filepath and/or filename cannot be located, i.e: FileNotFoundException
Make sure you provide the correct filename and/or filepath.
Upvotes: 3