FileNotFoundException catch error when reading from file in Java - java

I am trying to write a simple program that reads integers in from a text file and then outputs the sum to an output file. The only error I am getting is in my catch block at line 38 "Unresolved compilation problem: file cannot be resolved". Note that "file" is the name of my input file object. If I comment out this exception block, the program runs fine. Any advice would be appreciated!
import java.io.*;
import java.util.Scanner;
public class ReadWriteTextFileExample
{
public static void main(String[] args)
{
int num, sum = 0;
try
{
//Create a File object from input1.txt
File file = new File("input1.txt");
Scanner input = new Scanner(file);
while(input.hasNext())
{
//read one integer from input1.txt
num = input.nextInt();
sum += num;
}
input.close();
//create a text file object which you will write the output to
File output1 = new File("output1.txt");
//check whether the file's name already exists in the current directory
if(output1.exists())
{
System.out.println("File already exists");
System.exit(0);
}
PrintWriter pw = new PrintWriter(output1);
pw.println("The sum is " + sum);
pw.close();
}
catch(FileNotFoundException exception)
{
System.out.println("The file " + file.getPath() + " was not found.");
}
catch(IOException exception)
{
System.out.println(exception);
}
}//end main method
}//end ReadWriteTextFileExample

The file variable is declared within the try block. It's out of scope in the catch block. (Although it couldn't happen in this case, imagine if the exception were thrown before execution had even reached the variable declaration. Basically, you can't access a variable in a catch block which is declared in the corresponding try block.)
You should declare it before the try block instead:
File file = new File("input1.txt");
try
{
...
}
catch(FileNotFoundException exception)
{
System.out.println("The file " + file.getPath() + " was not found.");
}
catch(IOException exception)
{
System.out.println(exception);
}

Scope in Java is based on blocks. Any variable you declare inside a block is only in scope until the end of that same block.
try
{ // start try block
File file = ...;
} // end try block
catch (...)
{ // start catch block
// file is out of scope!
} // end catch block
However, if you declare file before your try block, it will remain in scope:
File file = ...;
try
{ // start try block
} // end try block
catch (...)
{ // start catch block
// file is in scope!
} // end catch block

Related

Java, reading the file from input.txt has an issue

I am working on the project. For my purpose, I need to use them that find the median of medians.
At my point, I need to see the read
I also created the input.txt like that below
3 7
1 4 5 7 9 11 13
Below the snippet, I created the variable for the readpath.
// need the variable of filename to read
private static final String INPUT_FILE_PATH = "input.txt";
So, then I appended the code that needs to read the numerical integers in the input.txt in the main function as known below
public static void main(String args[]){
// read the input file
// TODO need to fix this readpath that gets the bad input
// ! ASAP
Path inputPath = Paths.get(INPUT_FILE_PATH);
Charset charset = Charset.forName("UTF-8");
List<String> fileLines = new ArrayList<>(0);
try {
fileLines = Files.readAllLines(inputPath, charset);
} catch (IOException ex) {
System.err.println("Error reading file: " + ex.getMessage());
System.exit(1);
}
int read_line = 0;
try {
read_line = Integer.parseInt(fileLines.get(0));
} catch (NumberFormatException ex) {
System.err.println("bad file input");
System.exit(1);
}
System.out.println("reading... " + read_line);
// end of reading the filename operation
}
As a result, this code suppose to work. I get the output that is bad file input. I do not understand why it gets bad file. By the way, I put all files together in the same directory.
int read_line = 0;
int read_line2 = 0;
try {
String[] words = fileLines.get(0).split("\\s+"); // Split on whitespace.
read_line = Integer.parseInt(words[0]);
read_line2 = Integer.parseInt(words[1]);
} catch (NumberFormatException ex) {
System.err.println("bad file input - not a number; " + e.getMessage());
System.exit(1);
}
The line contains two numbers, and results in a NumberFormatException.

Try catch, Java eclipse not catching exception

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter file name:");
String name = sc.nextLine();
creatingfeatures(name, "part1");
}
public static void creatingfeatures(String filename, String type) {
String outputFile = "../data/" + type + "/" + type + ".csv";
System.out.println("This is the output file: " + outputFile);
try {
CsvWriter csvOutput = new CsvWriter(new FileWriter(outputFile, true), ',');
for (int i = 0; i < 10 ; i++) {
csvOutput.write(i);
csvOutput.endRecord();
}
csvOutput.close();
}
catch (IOException e) {
System.out.println("Please enter another file name (wrong name given)");
System.exit(0);
}
}
Hello all, when I use an invalid file name (Ie when the file is not found), the message under the catch was not printed. Anybody knows why?
From the documentation it is clear, it does not gives exception for the wrong file name supplied to FileWriter, it rather creates new file if it is not present. Also if it is not able to create a file at a desired location, then it throws IOException. Just check at the location, it should have created files there.
Constructs a FileWriter object given a file name with a boolean
indicating whether or not to append the data written.
Parameters:
fileName String The system-dependent filename.
append boolean if true, then data will be written to the end of the file rather than the beginning. Throws:
IOException if the named file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot
be opened for any other reason
You are catching just IOExceptions
catch (IOException e) {
System.out.println("Please enter another file name (wrong name given)");
System.exit(0);
}
If you have other kind of exceptions you have to catch them also.
Use:
catch (Exception e) {
System.out.println("Other kind of exception");
System.exit(0);
}
instead or in addition to catch any kind of exceptions
catch (IOException e) {
System.out.println("Please enter another file name (wrong name given)");
System.exit(0);
}catch (Exception e) {
System.out.println("Other kind of exception");
System.exit(0);
}

Try/Catch blocks in Java

for the program that I have been assigned, we have to read from a text file, create an ArrayList of objects called NameInformation that contains the information from the file, and then prompt the user for a name and gender (Gender is one of the variables in the NameInformation class) and the computer will tell how many boys or girls had the given name.
Can files be accessed and used outside of a try catch block? I want to try something like this:
try {
FileReader inFile = new FileReader (FILE_NAME);
} catch (FileNotFoundException e) {
System.out.println ("The file " + FILE_NAME + " does not exist");
System.exit(-1);
}
Scanner file = new Scanner (infile);
ArrayList<NameInformation> nameList = new ArrayList<NameInformation>();
I tried the above code and kept getting an error message. The only way I could get it to work somewhat was to make the try block massive. Is that the only way to do it? I feel like having a massive try block is incorrect.
I want to add elements to the ArrayList too, but can't seem to get it right.
while (file.hasNextLine()) {
NameInformation babyName = new NameInformation(file.nextLine());
nameList.add(babyName);
}
But this doesn't quite do what I want it to.
You can do it like this and give only error throwing code into try catch block, you are never passing catch block anyway because system exits there, otherwise you should check that file isn't null afterwards:
FileReader inFile = null;
try {
inFile = new FileReader (FILE_NAME);
} catch (FileNotFoundException e) {
System.out.println ("The file " + FILE_NAME + " does not exist");
System.exit(-1);
}
Scanner file = new Scanner (infile);
ArrayList<NameInformation> nameList = new ArrayList<NameInformation>();
Initializing the file should be in Try Catch Block. But you should declare it outside the block to access it outside. Example:
FileReader inFile = null;
try {
inFile = new FileReader (FILE_NAME);
} catch (FileNotFoundException e) {
System.out.println ("The file " + FILE_NAME + " does not exist");
System.exit(-1);
}
Scanner file = new Scanner (infile);
ArrayList<NameInformation> nameList = new ArrayList<NameInformation>();

Why is my text file not overwriting after each execution?

My program reads in a text file, in.txt. That text file can have an arbitrary amount of lines.
My problem is that when I try to write to the output (out.txt) file, it appends it instead of overwriting.
The output file should have the same number as the input file.
try {
inFile = new Scanner(new File("in.txt"));
while (inFile.hasNext()) {
// Methods and stuff that doesn't matter...
// Problem starts here
try{
outFile = new PrintWriter((new FileWriter("out.txt", true)));
outFile.println(ArrayToString(intArray));
}
catch (IOException e) {
System.out.print("Could not find and write to the output file. " + e);
e.printStackTrace();
}
finally {
outFile.flush();
outFile.close();
}
}
}
catch (FileNotFoundException e) {
System.out.print("Could not find the input file. " + e);
e.printStackTrace();
}
The ArrayToString method returns a string to write.
EDIT:
I forgot to add this detail:
After reading the instructions again, I am not supposed to be creating a text file, just checking if it's there.
See the Javadoc for the FileWriter constructor:
public FileWriter(String fileName,
boolean append)
throws IOException
Constructs a FileWriter object given a file name with a boolean
indicating whether or not to append the data written.
Try setting the append flag to false. Then use the same writer instead of creating a new one each time through the loop (meaning that you should declare the FileWriter above the start of your while loop).
(Btw check out java.util.Arrays.toString, you shouldn't need to write your own code for this.)
The problem is here:
try{
outFile = new PrintWriter((new FileWriter("out.txt", true)));
outFile.println(ArrayToString(intArray));
}
catch (IOException e) {
System.out.print("Could not find and write to the output file. " + e);
e.printStackTrace();
}
Change the PrintWriter line to:
outFile = new PrintWriter((new FileWriter("out.txt", false)));
Now, it looks like you're opening the file on every loop through your input file. If you are wanting to open this file once, and write to it for each line in the input file, move the open and close outside the while loop like this:
try {
inFile = new Scanner(new File("in.txt"));
// here we open the out file, once
outFile = new PrintWriter((new FileWriter("out.txt", false)));
while (inFile.hasNext()) {
// Methods and stuff that doesn't matter...
// Problem starts here
try{
// this will write a line to the out.txt file containing the intArray as a String
outFile.println(ArrayToString(intArray));
}
catch (IOException e) {
System.out.print("Could not find and write to the output file. " + e);
e.printStackTrace();
}
}
}
catch (FileNotFoundException e) {
System.out.print("Could not find the input file. " + e);
e.printStackTrace();
}
finally {
inFile.close();
outFile.flush();
outFile.close();
}
change
outFile = new PrintWriter((new FileWriter("out.txt", true)));
to
outFile = new PrintWriter((new FileWriter("out.txt", false)));
and
outFile.println(ArrayToString(intArray));
to
outFile.print(ArrayToString(intArray));

Can I avoid catch block in Java?

Inside a method, I use a Scanner to read text inside a file. This file doesn't always exist, and if it doesn't, I want simply to do nothing (i.e. no scan).
Of course I could use a try/catch like this:
String data = null;
try
{
Scanner scan = new Scanner(new File(folder + "file.txt"));
data=scan.nextLine();
scan.close();
}
catch (FileNotFoundException ex)
{
}
My question is what can I do to avoid the try/catch? Because I don't like local variable unused. I was thinking of something like:
String data = null;
File file_txt = new File(folder + "file.txt");
if (file_txt.exists())
{
Scanner scan = new Scanner(file_txt);
data=scan.nextLine();
scan.close();
}
But of course with this I get an error in Netbeans and I can't build my project...
No, It's checked exception. try must be followed with either catch block and/or finally block. There are two method for handling checked exception.
Method 1 : Either wrap your code using try/catch/finally
Option 1
try{
Scanner scan = new Scanner(new File(folder + "file.txt"));
data=scan.nextLine();
scan.close();
}
catch (FileNotFoundException ex)
{
System.out.println("Caught " + ex);
}
Option 2
try{
Scanner scan = new Scanner(new File(folder + "file.txt"));
data=scan.nextLine();
scan.close();
}
finally
{
System.out.println("Finally ");
}
Option 3
try{
Scanner scan = new Scanner(new File(folder + "file.txt"));
data=scan.nextLine();
scan.close();
}catch(FileNotFoundException ex){
System.out.println("Caught " + ex );
}finally{
System.out.println("Finally ");
}
Method 2: Throw exception using throw and list all the exception with throws clause.
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
Note : Checked Exception means Compiler force you to write something to handle this error/exception. So, AFAIK, there is no any alternative for checked exception handling except above method.
FileNotFoundException is checked exception, Due to catch or specify behavior, you need to either catch (or) specify it in throws clause of method declaration.
how about
catch (FileNotFoundException ex)
{
// create a log entry about ex
}

Categories