error: exception java.io.FileNotFoundException - java

Can anyone tell me why I have this error: exception java.io.FileNotFoundException is never thrown in body of corresponding try statement.
I try to save text from a file in an ArrayList.
import java.io.*;
import java.util.*;
public class EditMembership
{
public static void main(String[] args) throws java.io.FileNotFoundException
{
ArrayList<String> member = readFromFile("database.txt");
System.out.println(Arrays.toString(member.toArray()));
}
public static ArrayList readFromFile(String fileName) throws java.io.FileNotFoundException
{
Scanner x = new Scanner(new File(fileName));
ArrayList<String> memberList = new ArrayList<String>();
try {
while (x.hasNextLine())
{
memberList.add(x.nextLine());
}
x.close();
}
catch(FileNotFoundException e)//here is the error
{
e.printStackTrace();
}
return memberList;
}
}

Because you aren't doing anything to open a file within the try block it's impossible to throw a File Not Found. Move the Scanner declaration down within the try block and I would expect that'll fix it. At that point you can remove the "throws" declaration from your method signature.

Related

error related to exception handling in java

How to resolve this error? I have tried using throws to throw FileNotFoundException but still same error.
Compile-Time Error : "Default constructor cannot handle exception type Exception thrown by the implicit super constructor. Must define an explicit constructor "
CODE :
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileOne {
Scanner sc = new Scanner(System.in);
String file_name = sc.nextLine();
File obj = new File(file_name);
Scanner reader_obj = new Scanner(obj); // <--- error in this line
public static void main(String args[]) {
FileOne f = new FileOne();
f.create();
f.writeFile();
f.readFile();
}
void create() {
try {
System.out.println("Enter a file name");
if (obj.createNewFile()) {
System.out.println("file name is" + obj.getName());
} else {
System.out.println("Already exists");
}
} catch (IOException e) {
System.out.println("error occured while creating");
}
}
//method to write in file
void writeFile() {
try {
FileWriter w = new FileWriter(obj);
w.write("Learning files now");
w.close();
} catch (IOException e) {
System.out.println("Exception occured while writing a file");
}
}
//method to read
/* use the Scanner class to read the contents of the text file created */
void readFile() {
while (reader_obj.hasNextLine()) {
String data = reader_obj.nextLine();
System.out.println(data);
}
reader_obj.close();
}
}
The line Scanner reader_obj=new Scanner(obj);, which is implicitly called by the default constructor, may throw a FileNotFoundException, which is a checked exception and must be handled.
One way of doing so is explicitly defining a no-arg constructor:
public FileOne() throws FileNotFoundException {
}
Although, if you're going to do that, you should consider moving the members' initialization in to it for clarity's sake.
Errors Resolved:
I used throws to throw exceptions in main() and reading() method.
Used FileReader class to read the data from the given input file
Final Code:
public class FileOne {
Scanner sc=new Scanner(System.in);
String file_name=sc.nextLine();
File obj=new File(file_name);
//method for creating a file
void create(){
try{
if(obj.createNewFile()){
System.out.println("file name is"+obj.getName());
}
else{
System.out.println("Already exists");
}
}
catch(IOException e){
System.out.println("error occured while creating");
}
}
//method to write in file
void writeFile(){
try{
FileWriter w=new FileWriter(obj);
w.write("Learning files now");
w.close();
}
catch(IOException e){
System.out.println("Exception occured while writing a file");
}
}
void reading() throws FileNotFoundException,IOException{
FileReader reader=new FileReader(file_name);
int i;
while((i=reader.read())!=-1){
System.out.print((char)i);
}
reader.close();
}
public static void main(String args[])throws FileNotFoundException,IOException{
FileOne f=new FileOne();
f.create();
f.writeFile();
f.reading();
}
}
Add the constructor as below :
public FileOne () throws FileNotFoundException {
}
Edit your void main () as below (You need to throw the exception from main as well) :
public static void main(String args[]) throws FileNotFoundException {
FileOne f = new FileOne();
f.create();
f.writeFile();
f.readFile();
}

Error:Exception in thread "main" java.lang.NullPointerException

The readfile class is a class i made so i can read some strings from file.txt and then print them in the console:
package mainpackage;
import java.io.*;
import java.util.*;
public class readfile {
private Scanner x;
public void openFile(){
try {
x = new Scanner(new File("file.txt"));
} catch (Exception e) {
System.out.println("Could not find file");
}
}
public void readFile(){
while(x.hasNext()){
System.out.print(x.nextLine()+"\n");
}
}
public void closeFile(){
x.close();
}
}
But when i call the methods of the class in the main i get an error like this:
Exception in thread "main" java.lang.NullPointerException. This is the call in main:
public static void main(String [] args)
{
readfile r = new readfile();
r.openFile();
r.readFile();
r.closeFile();
}
Any ideas? thank you
You should not catch exception in openFile() or if catch it, throw new exception if you got exception in openFile() method Scanner will be null and in other method got null pointer exception.
package mainpackage;
import java.io.*;
import java.util.*;
public class readfile {
private Scanner x;
public void openFile() throws Exception{
try {
x = new Scanner(new File("file.txt"));
} catch (Exception e) {
//in here throw (this/another) exception to caller or don't catch this exption
System.out.println("Could not find file");
throw new Exception("Could not find file");
}
}
public void readFile(){
while(x.hasNext()){
System.out.print(x.nextLine()+"\n");
}
}
public void closeFile(){
x.close();
}
}
And main driver for testing:
public static void main(String [] args)
{
try {
readfile r = new readfile();
r.openFile();
r.readFile();
r.closeFile();
} catch (Exception e) {
e.printStackTrace();
System.out.println("got exception");
}
}
If exception is thrown, what value is under "x"?
What happend next?
(You should use debugger to check readFile() func)
I need to clarify: Questions were asked to make #Marios P sit up and think.

How can I read a file from a path relative of my Main class in Java?

On the same directory of my Main.java file, I have a package/folder named database, and inside the database package I have a file named Data.txt.
This is my code of Main.java, but it is throwing this error:
java: exception java.io.FileNotFoundException
How can I get the file from a relative file? I'm used to web development, and usually something with a . dot like "./folder/file.txt" works.
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class Main {
public static void main(String[] args) {
readFile();
}
public static void readFile() {
File file = new File("./database/Data.txt");
Scanner scanner = new Scanner(file);
try {
while (scanner.hasNextLine()) {
int i = scanner.nextInt();
System.out.println(i);
}
scanner.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You are not importing FileNotFoundException class. also, scanner statement throws the exception which should inside try. Solution is as below.
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class Main {
public static void main(String[] args) {
readFile();
}
public static void readFile() {
File file = new File("database/Data.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
int i = scanner.nextInt();
System.out.println(i);
}
scanner.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Only check if those content can read using scanner or not. Content having int properly. otherwise it will throw java.util.InputMismatchException.
Are you working on a mac or windows system.
I am on windows and ".\database\Data.txt" would most probably work depending on where the file is in your file structure.

error: cannot find symbol - working with file scanner loops

What does this error mean? On every line of the code below the try catch block this error occurs. I'm confused as to why this error keeps appearing.
My imports:
import java.util.*;
import java.io.*;
My method:
public static void readLists(ArrayList <String> list1, ArrayList <String> list2)
{
Scanner list1s;
Scanner list2s;
try
{
list1s = new Scanner(new File("list1.txt"));
list2s = new Scanner(new File ("list2.txt"));
}
catch(FileNotFoundException ex)
{
System.out.println("File not found!\n");
}
while(list1s.hasNext())
list1.add(list1s.next());
while(list2s.hasNext())
list2.add(list2s.next());
list1s.close();
list2s.close();
}
Updated code was from the suggestions in the comments. However, I get the following error: variable list1s might not have been initialized
while(list1s.hasNext())
If I do not have the scanner declaration and initialization in the try/catch. Any idea as to why this is happening?
static Scanner list1s;
static Scanner list2s;
public static void readLists(ArrayList <String> list1, ArrayList <String> list2)
{
try
{
list1s = new Scanner(new File("list1.txt"));
list2s = new Scanner(new File ("list2.txt"));
}
catch(FileNotFoundException ex)
{
System.out.println("File not found!\n");
}
// Your code
}
Just for reference: class and instance variables when declared, are automatically given their default values.

java: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown [duplicate]

This question already has answers here:
Why is "throws Exception" necessary when calling a function?
(8 answers)
Closed 8 years ago.
Why am I getting a "must be caught or declared to be thrown" error with this code ? All I want is to test a bunch of code by pasting it into a new java program what is the easiest way to bunch of code ?
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(new File("C:\\Users\\User\\Selenium\\scrapjv\\interface\\NASDAQlist.txt"));
List<String> symbolList = new ArrayList<String>();
while (sc.hasNextLine()) {
symbolList.add(sc.nextLine());
}
PrintWriter logput = new PrintWriter("C:\\Users\\User\\Selenium\\scrapjv\\interface\\log.txt", "UTF-8");
for (String symb : symbolList) {
System.out.println(symb);
}
logput.close();
}
}
Some of the methods you're calling can throw FileNotFoundException if the file isn't found:
public Scanner(File source) throws FileNotFoundException
public PrintWriter(String fileName) throws FileNotFoundException
Java's compiler checks that some thrown exceptions -- those other than RuntimeException and its subclasses -- are either caught or declared thrown. Compilation will fail otherwise. This helps find some errors at compile-time, before the program is ever run.
One option is to declare your calling function to throw the exception or a superclass:
public static void main(String[] args) throws FileNotFoundException {
A better option in this case is to catch the exception and do something with it. For example, here's how you can do that for the Scanner() exception:
File inFile = new File("C:\\Users\\User\\Selenium\\scrapjv\\interface\\NASDAQlist.txt");
try {
Scanner sc = new Scanner( inFile );
List<String> symbolList = new ArrayList<String>();
while (sc.hasNextLine()) {
symbolList.add(sc.nextLine());
}
}
catch ( FileNotFoundException e ) {
System.out.println("Could not find file: " + inFile.getAbsolutePath());
}
Your two Scanner declaration lines have a chance to throw an exception, which are basically errors that happen after the code is executed (because of this they are sometimes called runtime errors). Because the compiler knows that your code might make a FileNotFoundException happen, it requires you to catch the exception.
This is done by enclosing the code in a try-catch block.
try {
Scanner sc = new Scanner(new File("C:\\Users\\User\\Selenium\\scrapjv\\interface\\NASDAQlist.txt"));
List<String> symbolList = new ArrayList<String>();
while (sc.hasNextLine()) {
symbolList.add(sc.nextLine());
}
PrintWriter logput = new PrintWriter("C:\\Users\\User\\Selenium\\scrapjv\\interface\\log.txt", "UTF-8");
for (String symb : symbolList) {
System.out.println(symb);
}
logput.close();
} catch (java.io.FileNotFoundException ex)
{
ex.printStackTrace();
}

Categories