Unreported exception java.io.FileNotFoundException;? - java

I want to open a file and scan it to print its tokens but I get the error: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
Scanner stdin = new Scanner (file1); The file is in the same folder with the proper name.
import java.util.Scanner;
import java.io.File;
public class myzips {
public static void main(String[] args) {
File file1 = new File ("zips.txt");
Scanner stdin = new Scanner (file1);
String str = stdin.next();
System.out.println(str);
}
}

The constructor for Scanner you are using throws a FileNotFoundException which you must catch at compile time.
public static void main(String[] args) {
File file1 = new File ("zips.txt");
try (Scanner stdin = new Scanner (file1);){
String str = stdin.next();
System.out.println(str);
} catch (FileNotFoundException e) {
/* handle */
}
}
The above notation, where you declare and instantiate the Scanner inside the try within parentheses is only valid notation in Java 7. What this does is wrap your Scanner object with a close() call when you leave the try-catch block. You can read more about it here.

The file is but it may not be. You either need to declare that your method may throw a FileNotFoundException, like this:
public static void main(String[] args) throws FileNotFoundException { ... }
or you need to add a try -- catch block, like this:
Scanner scanner = null;
try {
scanner = new Scanner(file1);
catch (FileNotFoundException e) {
// handle it here
} finally {
if (scanner != null) scanner.close();
}

Related

Compiling error when reading a file in Java

I am trying to run this simple program that reads from a separate text file and prints out each line. However, when I try to compile it, it keeps giving me the same error:
story.java:11: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
x = new Scanner(new File("names.txt"));
Here is my code:
import java.io.*;
import java.util.*;
public class story {
private static Scanner x;
public static void main(String[] args) {
String story = "";
x = new Scanner(new File("names.txt"));
while(x.hasNext()){
story = story + x;
}
System.out.println(story);
}
}
This message is telling you that your main() method is doing some stuff that may throw FileNotFoundException but you are neither catching this exception, nor declaring that such an exception may be thrown by the main() function.
To correct it, declare your main() method as follows:
public static void main(String[] args) throws FileNotFoundException {
Change it to
public static void main(String[] args) throws Exception {
String story = "";
x = new Scanner(new File("names.txt"));
while(x.hasNext()){
story = story + x;
}
System.out.println(story);
}
OR
Put try catch in your code
public static void main(String[] args) {
String story = "";
try {
x = new Scanner(new File("names.txt"));
while(x.hasNext()){
story = story + x;
}
System.out.println(story);
}
catch(Exception e) {
// handle
}
}
When programming there is the normal flow of logic that solves your problem, and a second flow of logic that handled "Exceptional" unexpected situations. Java uses the type Exception and the keyword throw to have bits of code present exceptional error states.
Your program, when being complied, is being checked for its ability to handle exceptional return values. Since you didn't handle the exceptional return value, it is not going to be compiled.
Below is your code, handling this Exception. Pay close attention to the try and catch block structure, as it is how one writes code that can handle an Exception being raised. However, don't be constrained by how I handled the exception for you, because the details of how to handle the exception are dependent on what you would prefer to do.
import java.io.*;
import java.util.*;
public class story {
private static Scanner x;
public static void main(String[] args) {
String story = "";
try {
x = new Scanner(new File("names.txt"));
} catch (FileNotFoundException error) {
System.out.println("the program failed because \"names.txt\" was not found.");
return -1;
}
while(x.hasNext()){
story = story + x;
}
System.out.println(story);
}
}
There is another approach to handling exceptions that sometimes is appropriate, which is to "not handle" the exception. When doing so, change the method from whatever the method was to whatever the method was throws Exception. For example public static void main(String[] args) to public static void main (String[] args) throws Exception.
While this handles the compiler's complaint it should be used sparingly because exceptions that bubble up through the nested method calls past the main method will crash the program, typically without easily readable output that might make the error easier for a human to fix.
Whenever working with a file object, you must handle the chance of a FileNotFoundException, which occurs when the file you specify does not exist.
to fix this, simply say throws Exception in you main header, or use a try/catch block.
public static void main(String[] args) throws Exception {
or
public static void main(String[] args) {
String story = "";
try
{
x = new Scanner(new File("names.txt"));
while(x.hasNext()){
story = story + x;
}
System.out.println(story);
}
catch(Exception e)
{
System.out.println("Error: File not found!");
}
}
1) You need to put them in the try catch block.
2) specify the path of "names.txt".
3) My code looks like:
String story = "";
try {
x = new Scanner(new File("/Users/Workspace/names.txt"));
while(x.hasNext()){
System.out.println(story = story+x.next());
}
System.out.println(story);
} catch (FileNotFoundException e){
e.printStackTrace();
}
}

Scanner not getting declared, but why?! also, it is saying I can't print the global variable "line"? but why?

import java.io.FileReader;
import java.util.Scanner;
public class file_reading
{
Scanner scanner;
try
{
FileReader reader = new FileReader("toread.txt");
scanner = new Scanner(reader);
} catch (Exception e) {
System.err.print("hello incorrect");
}
String line = scanner.nextLine();
public static void main(String[] args)
{
System.out.println(line);
}
}
You have a few errors here, first is that you write try outside of method which is illegal, you must have method and inside his block(between { }) you will write code.
Reason why you can't print line is probably because you are calling non-static variable from static method(main)
You have to put all the code inside a method. Except the declaration of Scanner.
You could declare it inside your main-method like this. Then it's visible only inside this method.
Scanner scanner;
Or you define it outside of the main method as a static member.
static Scanner scanner;
The it's available throughout the class.
And you have to put
String line = scanner.nextLine();
System.out.println(line);
inside your try/catch-block. Otherwise the compiler assumes that "scanner" might not have been initialized, as you initialize it only inside this block but want to use it outside. And you'd get a warning that "line" is unknown because you instantiated this inside the try/catch too, which makes it unreachable for all code outside the curly braces.
import java.io.FileReader;
import java.util.Scanner;
public class file_reading
{
public static void main(String[] args)
{
Scanner scanner;
try
{
FileReader reader = new FileReader("toread.txt");
scanner = new Scanner(reader);
String line = scanner.nextLine();
System.out.println(line);
} catch (Exception e) {
System.err.print("hello incorrect");
}
}
}

File not found for file in src\resources accessed with ClassLoader.getSystemResource("file.txt")

I am trying to access a text file within my Java Netbeans project, but I keep getting file not found.
Please note that I've tried specifying the file with "src\ ....", "resources\ ...", and only using the file name.
This is my code:
static class Task extends TimerTask {
// Load the directory as a resource
URL dir_url = ClassLoader.getSystemResource("word_list_moby_credits.txt");
// Turn the resource into a File
File f = new File(dir_url.getFile());
Scanner scanner = new Scanner(f);
I'm getting
File not found
on the last line of the code above.
This is my project:
Please try this to read words.txt in {Source Packages}/resources:
public static void main(String[] args) {
try{
URL url = Task.class.getResource("/resources/words.txt");
Scanner scanner = new Scanner(url.openStream());
System.out.println("" + scanner.next());
} catch(IOException ex) {
ex.printStackTrace();
}
}
In case you already have other main method and still want to keep this code outside a method, you can wrap it in a static block:
static class Task extends TimerTask {
static {
try {
URL url = Task.class.getResource("/resources/words.txt");
Scanner scanner = new Scanner(url.openStream());
System.out.println("" + scanner.next());
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

creating, writing to and reading from files java

I have made a program that is supposed to create a file, write to it, and then read from it. The problem comes with readFile(), where suddenly hasNext() is undefined for Formatter? I thought that
while (file.hasNext()) {
String a = file.next();
System.out.println(a);
would go as long as there was something in the file, copy it to a and then print a? What am I doing wrong?
import java.util.*;
import java.io.*;
class Oppgave3
{
public static void main(String[] args)
{
Kryptosystem a = new Kryptosystem();
a.createFile();
a.writeFile();
a.openFile();
a.readFile();
a.closeFile();
}
}
class Kryptosystem
{
public Kryptosystem(){}
Scanner keyboard = new Scanner (System.in);
private Formatter file;
private Scanner x;
public void createFile(){
try {
file = new Formatter("kryptFil.txt");
}
catch (Exception e) {
System.out.println("could not create file");
}
}
public void writeFile(){
System.out.println("what do you want to write");
String tekst = keyboard.nextLine();
file.format(tekst);
}
public void openFile() {
try {
x = new Scanner (new File("kryptFil.txt"));
}
catch (Exception e) {
System.out.println("something is wrong with the file");
}
}
public void readFile() {
while (file.hasNext()) {
String a = x.next();
System.out.println(a);
}
}
public void closeFile() {
file.close();
}
}
You state:
where suddenly hasNext() is undefined for Formatter?
Please have a look at the Formatter API as it will show you that this class has no hasNext() method, and your Java compiler is correctly telling you the same thing. Similarly, the Scanner API will show you that it in fact has the method you need.
You're opening the same File in a Scanner, called x, and this is what you want to use to read from the file. So the solution is to call hasNext() on the Scanner variable:
while (x.hasNext()) { // x, not file
String a = x.next();
System.out.println(a);
}
Note I'm not sure why you opened the file a second time and placed it into a Formatter object. Please clarify your motivation for this. I believe that you wish to write to the file with this, but you certainly would not try to use it to read from the File, which is what you're use of hasNext() is trying to do. I think you were just a little confused on which tool to use is all.

Java Try and Catch IOException must be caught or declared to be thrown

I am trying to use a bit of code I found at the bottom of this page. Here is the code in a class that I created for it:
import java.io.LineNumberReader;
import java.io.FileReader;
import java.io.IOException;
public class LineCounter {
public static int countLines(String filename) throws IOException {
LineNumberReader reader = new LineNumberReader(new FileReader(filename));
int cnt = 0;
String lineRead = "";
while ((lineRead = reader.readLine()) != null) {}
cnt = reader.getLineNumber();
reader.close();
return cnt;
}
}
My objective is to count the lines of a text file, store that number as an integer, then use that integer in my main class. In my main class I tried a few different ways of making this happen, but (being a new programmer) I am missing something. Here is the first thing I tried:
String sFileName = "MyTextFile.txt";
private int lineCount = LineCounter.countLines(sFileName);
With this attempt I get the error "unreported exception java.io.IOException; must be caught or declared to be thrown." I don't understand why I am getting this because as I can see the exception is declared in my "countLines" method. I tried to use a try catch block right under that last bit of code I posted, but that didn't work either (I don't think I did it right though). Here is my try catch attempt:
String sFileName = "MyTextFile.txt";
private int lineCount;{
try{
LineCounter.countLines(sFileName);
}
catch(IOException ex){
System.out.println (ex.toString());
System.out.println("Could not find file " + sFileName);
}
}
Please show me the way!
Initializer block is just like any bits of code; it's not "attached" to any field/method preceding it. To assign values to fields, you have to explicitly use the field as the lhs of an assignment statement.
private int lineCount; {
try{
lineCount = LineCounter.countLines(sFileName);
/*^^^^^^^*/
}
catch(IOException ex){
System.out.println (ex.toString());
System.out.println("Could not find file " + sFileName);
}
}
Also, your countLines can be made simpler:
public static int countLines(String filename) throws IOException {
LineNumberReader reader = new LineNumberReader(new FileReader(filename));
while (reader.readLine() != null) {}
reader.close();
return reader.getLineNumber();
}
Based on my test, it looks like you can getLineNumber() after close().
The reason you are getting the the IOException is because you are not catching the IOException of your countLines method. You'll want to do something like this:
public static void main(String[] args) {
int lines = 0;
// TODO - Need to get the filename to populate sFileName. Could
// come from the command line arguments.
try {
lines = LineCounter.countLines(sFileName);
}
catch(IOException ex){
System.out.println (ex.toString());
System.out.println("Could not find file " + sFileName);
}
if(lines > 0) {
// Do rest of program.
}
}
Your countLines(String filename) method throws IOException.
You can't use it in a member declaration. You'll need to perform the operation in a main(String[] args) method.
Your main(String[] args) method will get the IOException thrown to it by countLines and it will need to handle or declare it.
Try this to just throw the IOException from main
public class MyClass {
private int lineCount;
public static void main(String[] args) throws IOException {
lineCount = LineCounter.countLines(sFileName);
}
}
or this to handle it and wrap it in an unchecked IllegalArgumentException:
public class MyClass {
private int lineCount;
private String sFileName = "myfile";
public static void main(String[] args) throws IOException {
try {
lineCount = LineCounter.countLines(sFileName);
} catch (IOException e) {
throw new IllegalArgumentException("Unable to load " + sFileName, e);
}
}
}

Categories

Resources