the following code is returning the following error message:
package demo3;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class App {
public static void main(String[] args) {
try {
openFile();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("File not found: " + file.toString());
}
}
public static void openFile() throws FileNotFoundException {
File file = new File("test.txt");
FileReader fr = new FileReader(file);
}
}
Error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
file cannot be resolved
at demo3.App.main(App.java:13)
I'm not sure whether this is because the file is in a different class to the try catch loop or if it's caused by something else. Any help would be much appreciated. Thanks
Instead of handling the FileNotFound exception in your main method, handle it in your openFile() method.
Right now you're trying to access the file method where the variable has not been defined. The file variable has only been defined in the openFile() method.
You can also define it above your main method. If you do that, every method in your class will have access to it.
Either solution will solve your problem. Choose the one that best fits your needs.
Related
I was trying to read the file named test. My program is AntlrTest.java. They are in the same directory: /Users/MyName/Documents/. The content in AntlrTest.java is shown below:
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
public class AntlrTest {
public static void main(String[] args) {
String fileName = "test";
CharStream input = CharStreams.fromFileName(fileName);
}
}
And what in the file test is just simple UTF-8 text a//b.
However, when I tried to javac AntlrTest.java, it says:
error: unreported exception IOException; must be caught or declared to be thrown
CharStream input = CharStreams.fromFileName(fileName);
^
I also tried to change the filename to be an absolute path /Users/MyName/Documents/test, but just got the same IOException.
Does anyone have some suggestions?
Many thanks!
The compiler shows the error and the possible solutions. Therefore, use one of the available alternatives:
Catch the IOException and handle it appropriately.
try {
CharStream input = CharStreams.fromFileName(fileName);
} catch (final IOException e) {
// Handle the exception.
// For example: log (print to standard to error) it and return.
System.err.println(e);
return;
}
Declare the IOException to be thrown by the main method.
public static void main(String[] args) throws IOException {
...
}
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.
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.
I am trying to open a .csv file using FileReader in Eclipse. I have tried specifying the file's absolute path (as shown below), as well as moving the file into the current directory. Either way, I get the same I/O Exception - shown below after the code. Any help with this would be appreciated. thx
package demos;
import java.util.*;
import java.io.*;
import au.com.bytecode.opencsv.CSV;
import au.com.bytecode.opencsv.CSVReadProc;
import au.com.bytecode.opencsv.CSVWriteProc;
import au.com.bytecode.opencsv.CSVWriter;
import au.com.bytecode.opencsv.CSVReader;
public class ExampleCSVWrite {
public static void main (String[] args) {
CSVReader reader = new CSVReader(new FileReader("/Users/aaronarpi/Documents/UA.csv"));
List<String[]> myEntries = reader.readAll();
reader.close();
}
}
The exceptions are:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Unhandled exception type FileNotFoundException
Unhandled exception type IOException
Unhandled exception type IOException
at demos.ExampleCSVWrite.main(ExampleCSVWrite.java:12)
Error mentions about the uncatched IOException. You either need to throw or catch the IOException
public class ExampleCSVWrite {
public static void main (String[] args) throws IOException {
CSVReader reader = new CSVReader(new FileReader("/Users/aaronarpi/Documents/UA.csv"));
List<String[]> myEntries = reader.readAll();
reader.close();
}
}
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();
}