Scanner user = new Scanner(System.in);
String word;
System.out.println("Location of file: ");
word = user.nextLine();
FileReader fileOpen = new FileReader(word);
BufferedReader fileRead = new BufferedReader(fileOpen);
How can I do an error check if the user enters a wrong file destination?
I get:
java.io.FileNotFoundException:
when a invalid file destination is entered.
I want the program to say something like
System.out.println("Invalid directory");
I get errors for the methods isDirectory() and exists() telling me they don't exist for the type String when I try:
if (word.exists())
{
//do blah blah
}
else
{
//Print error
}
Wrap your word in File and then do the checks:
if (new File(word).exists())
{
//do blah blah
}
else
{
//Print error
}
Alternatively, you may catch an exception when it is thrown:
Scanner user = new Scanner(System.in);
String word;
System.out.println("Location of file: ");
word = user.nextLine();
try {
FileReader fileOpen = new FileReader(word);
BufferedReader fileRead = new BufferedReader(fileOpen);
} catch (FileNotFoundException fnf) {
// print an error
}
Create a File instance of 'word' then check if it exists. For the exception, surround it with a try and catch, in the catch: put the code you want to run should it not exist.
Related
I've figured out how to get the program to terminate if the file name doesn't exist but I'm not sure how to do the same if the file itself includes anything besides integers.
if (args.length == 0) {
System.out.println("Enter the name for a file: ");
filename = keyboard.nextLine();
} else {
filename = args[0];
}
File file = new File(filename);
if (file.exists() != true) {
System.out.println("File name does not exist");
System.exit(1);
}
Scanner inputFile = new Scanner(file);
Right now, if I were to put a character other than an integer into an existing file I get an error. Instead, I want the program to terminate with a message saying:
Invalid input
You could use a try/catch to catch the error and display a message of "invalid input" then terminate the program.
Scanner inputFile = new Scanner(file);
try{
int i=Integer.parseInt(inputFile.nextLine());//place it in a loop if you want to read multiple lines
}catch(Exception e){//it throws an exception if the line is not a number (e.g. if contains letters)
System.out.println("Invalid input");
System.exit(2);
}
File file = new File("student_info1.txt");
// if file is not found, report and exit program
if (!file.exists()) {
System.out.println("File can not be found! Exiting program...");
System.exit(1);
}
// open a scanner object to read from file
Scanner input = new Scanner(file);
You will have to read the file by repeatedly calling Scanner#nextLine(); on input.
while (!input.hasNextLine()) {
String lineOfText = input.nextLine();
// Do something with your line of text here.
}
I'm trying to code for a file not found exception in a while loop so that the program continues prompting the user for the file (test.txt). I wrote a try/catch block inside a while loop. However, when I delete the input file (test.txt), the program should catch this error and print "Error, cannot locate the 'test.txt' file, please try again:" and allow the user to input another file name. However, the program crashes and gives me a FileNotFoundException.
In this case it's probably better to ask for permission rather than forgiveness (e.g. check if the file exists before attempting to read it).
File file = new File("test_input.txt");
if (file.exists()) {
FileReader fileReader = new FileReader(file);
}
You should add another try and catch for the Scanner
// prompt user for name for output textfile
System.out.println();
System.out.print("What would you like to call your output file: ");
String outputName = inputReader.nextLine();
// scanner and printwriter objects for reading text file
try {
Scanner in = new Scanner(correctInputfile);
PrintWriter out = new PrintWriter(outputName);
// read input (values) and write the output (average)
// messages triggered by successful location of files.
if (fileName.equalsIgnoreCase(("test_input.txt"))) {
// code logic
}
} catch (FileNotFoundException ex) {
System.out.println();
System.out.println("***** ERROR *****");
System.out.println("\nCannot locate the input file " + "'" + fileName + "'" + "on your computer - please try again.");
System.out.print("\nInput file name (from your computer): ");
}
In your code, two lines raise FileNotFoundExceptions that you are not catching:
// scanner and printwriter objects for reading text file
Scanner in = new Scanner(correctInputfile);
PrintWriter out = new PrintWriter(outputName);
// read input (values) and write the output (average)
You can replace them with the following, and the code (should) work.
Scanner in = null;// Initialize to null, so they don't raise warnings.
PrintWriter out = null;
try { // Surround with try/catch to get the exception
in = new Scanner(correctInputfile);
out = new PrintWriter(outputName);
}catch(FileNotFoundException e){
/*TODO: something about the exception here!
Make sure the Scanner and PrintWriter get
properly initialized with valid file names.*/
}
So I'm having a few troubles here. I need to be able to write my output to a file, and have it contain only the keywords specified in the code. This code is writing nothing to the file, and it only opens another box for user input. How do I get it to close the input box after the user inputs the file name, get it to write the output to the file, and get the output to display in the compiler? Thanks!
import java.util.*;
import java.io.*;
public class Classname {
static Scanner sc = new Scanner(System.in);
public static void main(String args[]) throws IOException,
FileNotFoundException {
String filename;
// Connecting to a file with a buffer
PrintWriter outFile = new PrintWriter(
new BufferedWriter(
new FileWriter("chatOutput.log")));
// Get the file
System.out.print("Please enter full name of the file: ");
filename = sc.next();
// Assign the name of the text file to a file object
File log = new File( filename);
String textLine = null; // Null
String outLine = ""; // Null
while(sc.hasNext())
{
String line=sc.nextLine();
if(line.contains("LANTALK"))
System.out.println(line);
}
try
{
// assigns the file to a filereader object..this will throw an error if
the file does not exist or cannot be found
BufferedReader infile = new BufferedReader(new FileReader(log));
try
{
// read data from a file..this will throw and error if something goes
wrong reading (empty or past end of file)
while((textLine = infile.readLine()) != null)
{
//System.out.printf("%s\n",textLine);
outLine = textLine.toUpperCase();
outFile.printf("%s\n",outLine);
}// end of while
} // end of try
finally // finally blocks get executed even if an exception is thrown
{
infile.close();
outFile.close();
}
}// end of try
catch (FileNotFoundException nf) // this goes with the first try because it
will throw a FileNotFound exception
{
System.out.println("The file \""+log+"\" was not found");
}
catch (IOException ioex) // this goes with the second try because it will
throw an IOexception
{
System.out.println("Error reading the file");
}
} /// end of main
} // end of class
What you need is to end the while(sc.hasNext()) while loop because the Scanner sc will always have a next because you are literally saying asking yourself if you got the line from the user then wait for next line with sc.nextLine(); then you are putting it into a string so next time you ask yourself do i have the line the answer is yes,anyways it's a little complicated to get over this issue you need to change the while loop to have a special word that will brake it,so you have to change it from:
while(sc.hasNext()){
String line=sc.nextLine();
if(line.contains("LANTALK"))
System.out.println(line);
}
To,for example:
while(true){
String line=sc.nextLine();
if(line.contains("LANTALK"))
System.out.println(line);
if(line.contains("END"))
break;
}
Also you need to check if the file entered by the user exists and actually add the text from the console to the file,so it would look something like this:
if(!log.exists())log.createNewFile();
// Connecting to a file with a buffer
PrintWriter logFile = new PrintWriter(
new BufferedWriter(
new FileWriter(log.getAbsolutePath())));
while(true){
String line=sc.nextLine();
if(line.contains("LANTALK"))
System.out.println(line);
if(line.contains("END"))
break;
logFile.println(line);
}
logFile.close();
Now all we have to do is print the output to the console when writing it to the logFile,so the while((textLine = infile.readLine()) != null),will now look a little something like this:
while((textLine = infile.readLine()) != null)
{
//System.out.printf("%s\n",textLine);
outLine = textLine.toUpperCase();
outFile.println(outLine);
System.out.println(outLine);
}// end of while
} // end of try
So in the end the hole thing should look a little something like this:
import java.util.*;
import java.io.*;
public class Classname{
static Scanner sc = new Scanner(System.in);
public static void main(String args[]) throws IOException,
FileNotFoundException {
String filename;
// Connecting to a file with a buffer
PrintWriter outFile = new PrintWriter(
new BufferedWriter(
new FileWriter("chatOutput.log")));
// Get the file
System.out.print("Please enter full name of the file: ");
filename = sc.next();
// Assign the name of the text file to a file object
File log = new File(filename);
String textLine = null; // Null
String outLine = ""; // Null
if(!log.exists())log.createNewFile();
// Connecting to a file with a buffer
PrintWriter logFile = new PrintWriter(
new BufferedWriter(
new FileWriter(log.getAbsolutePath())));
while(true){
String line=sc.nextLine();
if(line.contains("LANTALK"))
System.out.println(line);
if(line.contains("END"))
break;
logFile.println(line);
}
logFile.close();
try{
// assigns the file to a filereader object..this will throw an error if the file does not exist or cannot be found
BufferedReader infile = new BufferedReader(new FileReader(log));
try
{
// read data from a file..this will throw and error if something goes wrong reading (empty or past end of file)
while((textLine = infile.readLine()) != null)
{
//System.out.printf("%s\n",textLine);
outLine = textLine.toUpperCase();
outFile.println(outLine);
System.out.println(outLine);
}// end of while
} // end of try
finally // finally blocks get executed even if an exception is thrown
{
infile.close();
outFile.close();
}
}// end of try
catch (FileNotFoundException nf) // this goes with the first try because it will throw a FileNotFound exception
{
System.out.println("The file \""+log+"\" was not found");
}
catch (IOException ioex) // this goes with the second try because it will throw an IOexception
{
System.out.println("Error reading the file");
}
} /// end of main
} // end of class
If this is not what you are looking for i'm sorry,but i tried to make it do want you described you wanted,i mean it does write the output to the file, and get the output to display in the compiler,here's what the compiler console looks like:
Please enter full name of the file: test.txt
hi
hi
hi
END
HI
HI
HI
I'm sorry if this is not what you wanted but i tried my best,hope it helps.
I am trying to output a file scanner object from my method. This is a school assignment and I am specifically instructed to NOT throw any exceptions, but use try/catch instead. The assignment requires that the command line prompt the user for a file to scan. If the file does not exist, we are supposed to tell the user, then prompt them for a file again. If the file does exist, then the method returns a scanner object that scans the file.
My code works, but it is not clean. It involves 2 methods. This is my code so far:
public static Scanner getInputScanner (Scanner console) {
File inputFile = null;
Scanner input = null;
try {
inputFile = getFile(inputFile, console);
input = new Scanner (inputFile);
return input;
} catch (FileNotFoundException e) {
try {
return input = new Scanner (getFile (inputFile, console));
} catch (FileNotFoundException f) {
System.out.println("An error has occured.");
return input;
}
}
}
public static File getFile (File inputFile, Scanner console) {
System.out.println("Enter input file: ");
inputFile = new File (console.nextLine());
while (!inputFile.exists()) {
System.out.println("File does not exist.");
System.out.print("Enter input file: ");
inputFile = new File (console.nextLine());
}
return inputFile;
}
The problem with the code is that the output looks like this:
Enter input file:
File does not exist.
Enter input file:
It then is waiting for the user's input. I don't want the output to have the 2 lines of code before the last line though.
Can anybody explain why my code is outputting these 2 lines?
Also, is there a simpler solution to getting an input file without throwing the FileNotFoundException?
Thanks!
If I understand correctly,
your program outputs these lines when you run it,
no matter what,
without you getting a chance to actually enter a filename.
Enter input file:
File does not exist.
And then the programs asks you again:
Enter input file:
And you don't want the first two lines above, right?
This can happen for example if the Scanner console you received has an unread newline in it.
You haven't posted that part of the code,
so it's hard to tell, but this is a common gotcha with Scanner.
Before calling getInputScanner,
make sure the Scanner console is ready to use,
with no unread garbage still buffered in it.
As for the second part of your question,
yes this can be written simpler and better, for example:
public static Scanner getInputScanner(Scanner console) {
try {
File inputFile = getExistingFile(console);
return new Scanner(inputFile);
} catch (FileNotFoundException e) {
throw new AssertionError("The file is expected to exist (was supposed to be verified earlier)");
}
}
public static File getExistingFile(Scanner console) {
while (true) {
System.out.println("Enter input file: ");
File inputFile = new File(console.nextLine());
if (inputFile.exists()) {
return inputFile;
}
System.out.println("File does not exist.");
}
}
It execute below line as soon the getFile() being called.
System.out.print("Enter input file: ");
Since no file exist, the below lines keeps on executing :
while (!inputFile.exists()) {
System.out.println ("File does not exist.");
System.out.print("Enter input file: ");
You can use throws() instead of try/catch, then caller will take care of exception.
Had to consume whatever junk was being carried over from the scanner by inserting a Scanner.nextLine() before getting user input. Final code looks like this:
public static Scanner getInputScanner(Scanner console) {
try {
File inputFile = getExistingFile(console);
return new Scanner(inputFile);
} catch (FileNotFoundException e) {
throw new AssertionError("The file is expected to exist (was supposed to be verified earlier)");
}
}
public static File getExistingFile(Scanner console) {
while (true) {
console.nextLine();
System.out.println("Enter input file: ");
File inputFile = new File(console.nextLine());
if (inputFile.exists()) {
return inputFile;
}
System.out.println("File does not exist.");
}
}