Compiling error when reading a file in Java - 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();
}
}

Related

File Scanner: Unreported exception FileNotFoundException; must be caught or declared to be thrown

I have tried everything I can find on the internet, and nothing seems to fix this. I am begging for help, tell me what I am doing wrong. I am brand new to Java. Thanks!
import java.util.Scanner;
class File_Scanner {
public static void read() {
File credentials_file = new File("credentials.txt");
Scanner file_reader = new Scanner(credentials_file);
String[] users = new String[6];
int index_counter = 0;
try {
while (file_reader.hasNextLine()) {
users[index_counter] = file_reader.nextLine();
}
file_reader.close();
} catch (Exception e) {
System.out.println(e.getClass());
}
}
}
This is showing the following error
Unreported exception FileNotFoundException; must be caught or declared to be thrown
I would like to recommend to surround the whole read function with a try/catch block like the following.
import java.util.Scanner;
class File_Scanner{
public static void read(){
try {
File credentials_file = new File("credentials.txt");
Scanner file_reader = new Scanner(credentials_file);
String[] users = new String[6];
int index_counter = 0;
while (file_reader.hasNextLine()) {
users[index_counter] = file_reader.nextLine();
}
file_reader.close();
} catch (Exception e) {
System.out.println(e.getClass());
}
}
}
The idea of try/catch is to avoid any error that might occur while running your program. In your case, Scanner file_reader = new Scanner(credentials_file); can throw an error if the credentials_file is not found or deleted. Hence you need to cover this around a try block which will give you an exception which can be handled to show proper response message in the catch block.
Hope that helps!
I agree with the other answers as to the problem (the Scanner can throw an exception if it can't find the file). I haven't seen what I'd consider the correct solution though.
String[] users = new String[6];
int index_counter = 0;
File credentials_file = new File("credentials.txt");
try (Scanner file_reader = new Scanner(credentials_file)) {
while (file_reader.hasNextLine()) {
users[index_counter] = file_reader.nextLine();
index_counter++;
}
} catch (FileNotFoundException e) {
// handle exception
} catch (NoSuchElementException e) {
// handle exception
} catch (IllegalStateException e) {
// handle exception
}
The try-with-resources statement will automatically close the Scanner for you. This will work with any class that implements the AutoCloseable interface.
And in this case, it puts the statement within the scope of the try, so exceptions will be caught.
Your exception handling is questionable, so I didn't include it. But that's not really the point here. You can read more about Best Practices to Handle Exceptions in Java or How to Specify and Handle Exceptions in Java.
There is an argument that you should let the exception bubble up to the caller. This answer describes how to do that. But in this case, the caller doesn't really know how to handle a FileNotFoundException, because it doesn't know anything about the file. The file is defined in this method.
You could throw a different, more explanatory exception. Or you could handle the exception here by explaining what a credentials.txt is. Or fail over to a default. Or just log the exception, although that's questionable. If you do that, you should explain (in a comment) why that is sufficient.
I added a line to increment index_counter just because it seemed to be missing.
See also
Why do I get "Exception; must be caught or declared to be thrown" when I try to compile my Java code?
Am I using the Java 7 try-with-resources correctly?
Java has checked exceptions. Which means that if the code within your method declares that it might possibly throw a particular exception, your method either needs to do one of the following:
Either (1) handle that exception:
public static void read() {
try {
// your method code
} catch (FileNotFoundException ex) {
// handle the exception
}
}
Or (2) declare that it might possibly throw that exception:
public static void read() throws FileNotFoundException {
// your method code
}
Just add this to your method declaration:
public static void read() throws FileNotFoundException
For ways to handle checked exceptions in java check this(Oracle Docs Java Tutorials):
You associate exception handlers with a try block by providing one or
more catch blocks directly after the try block. No code can be between
the end of the try block and the beginning of the first catch block.
try {
} catch (ExceptionType name) {
} catch (ExceptionType name) {
}
And this:
Sometimes, it's
appropriate for code to catch exceptions that can occur within it. In
other cases, however, it's better to let a method further up the call
stack handle the exception
public void writeList() throws IOException {
P.S. Also, it has been already discussed on stackoverflow, so maybe should be marked as duplicate.
You should read the java checked exception
public static void read() {
try {
File credentials_file = new File("credentials.txt");
Scanner file_reader;
file_reader = new Scanner(credentials_file);
String[] users = new String[6];
int index_counter = 0;
while (file_reader.hasNextLine()) {
users[index_counter] = file_reader.nextLine();
}
file_reader.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (Exception e) {
System.out.println(e.getClass());
}
}

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.

<identifier> expected, arrayList

I'm having trouble with some java code. The program consists of about 7 files, but I will try to keep it short.
I'm trying to load an ArrayList from a file into a variable, with ObjectStream. It gave me a warning, because all the compiler could see, was that I said an Object should be casted to ArrayList. of course the compiler won't know what kind of object there is in the file. As the coder I know that the file can only consist of one ArrayList and nothing else. So I searched the web, and found out to supress the warning, nut now it give me the error:
Schedule.java:34: error: <identifier> expected
To give you a picture of what's happening, here is the code the error happens in. This error shouldn't be affected by any of the other classes
import java.util.*;
import java.io.*;
public class Schedule
{
private static ArrayList<Appointment> schedule;
private static File file;
private static ObjectInputStream objIn;
private static boolean exit;
private static Scanner in = new Scanner(System.in);
public static void main(String[] args)
{
initializeSchedule();
System.out.println("Welcome!");
while(!exit){
System.out.print("write command: ");
Menu.next(in.next());
}
}
public static void initializeSchedule()
{
try{
file = new File("Schedule.ca");
if(!file.exists()){
schedule = new ArrayList<Appointment>();
}
else{
objIn = new ObjectInputStream(new FileInputStream("Schedule.ca"));
#SuppressWarnings("unchecked")
schedule = (ArrayList<Appointment>)objIn.readObject();
objIn.close();
}
} catch (IOException e){
System.out.println("Exception thrown :" + e);
} catch (ClassNotFoundException e){
System.out.println("Exception thrown :" + e);
}
}
public static void exit()
{
exit = true;
}
public static ArrayList<Appointment> getSchedule()
{
return schedule;
}
}
the error is in initializeSchedule, right under the supression, where schedule is set to the ObjectStream input.
The correct locations for #SuppressWarnings("unchecked") are
TYPE, FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE
So the compiler cannot parse #SuppressWarnings at this point, but considers it a statement. If you move it above the method declaration or above the declaration of schedule, it should be fine.
A better way to fix that is to actually correct the issue that the compiler is complaining about like this:
final Object input = objIn.readObject();
if (input instanceof ArrayList) {
schedule = (ArrayList<Appointment>) input;
} else {
throw new IllegalStateException(); // or whatever suits you
}
You can't annotate an assignment. Move the
#SuppressWarnings("unchecked")
to the line before the method starts.

Unreported exception java.io.FileNotFoundException;?

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();
}

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