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 {
...
}
Related
I'm new to java and I'm having a little problem with my code. There's no error and such, it just keeps saying process finished but no output was displayed. The filename is correct as I've checked.
import java.nio.file.;
import java.io.;
public class GuessingGame {
public GuessingGame() {
String filename = "C:\\Users\\angela\\Documents\\words.txt";
Path path = Paths.get(filename.toString());
try {
InputStream input = Files.newInputStream(path);
BufferedReader read = new BufferedReader(new InputStreamReader(input));
String word = null;
while((word = read.readLine()) !=null) {
System.out.println(word);
}
}
catch(IOException ex) {
}
}
public static void main (String[] args) {
new GuessingGame();
}
}
You are ignoring the exception and you don't close the file. Save some typing by using the built-in input.transferTo() for copying the file to System.out, and pass on the exception for the caller to handle by adding throws IOException to constructor and main.
Replace your try-catch block with this try-with-resources, which handles closing the file after use:
try (InputStream input = Files.newInputStream(path)) {
input.transferTo(System.out) ;
}
You managed to call the intended class, but you also needed to specify the specific function which you have declared in the function. Like so:
public static void main (String[] args) { GuessingGame gg = new GuessingGame; gg.GuessingGame(); }
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.
A Java program on CodeEval had to accept a file path as an argument. I used a command line argument to do this, but I get an exception as below when I submitted my code on CodeEval. What are some potential solutions to this problem?
Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
at java.util.StringTokenizer.nextElement(StringTokenizer.java:407)
at Main.FileRead(Main.java:61)
at Main.main(Main.java:26)
Here's the boilerplate Java code that I use for my Codeeval code. The specific problem code generally goes in the processLine method. I don't use Scanner or StringTokenizer. I use the String split method to process the input.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main implements Runnable {
private String fileName;
public Main (String fileName) {
this.fileName = fileName;
}
#Override
public void run() {
try {
processFile();
} catch (IOException e) {
e.printStackTrace();
}
}
private void processFile() throws IOException {
BufferedReader br = new BufferedReader(
new FileReader(fileName));
String line = "";
while ((line = br.readLine()) != null) {
processLine(line);
}
br.close();
}
private void processLine(String line) {
System.out.println(line);
}
public static void main(String[] args) {
new Main(args[0]).run();
}
}
Firstly, Check the name of class.Class name should be 'Main'.
Second you have to give all the imports in CodeEval Editor which you are using in your program.
This happens if you don't check to see if there are any more tokens (by calling hasMoreTokens). If no more tokens exist and you call nextToken, you will get this exception. However, without seeing the rest of your code, there is no way to know what is actually happening.
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.
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();
}