Scanner keeps throwing FileNotFound Exception [duplicate] - java

This question already has answers here:
FileNotFoundException when creating a Scanner in Eclipse with Java
(3 answers)
Closed 2 years ago.
I am trying to load a file called SPY.txt into an array, but I can't even get this little snippet to work.
I don't understand. If f.exists is true, how can the Scanner throw a file not found exception?
import java.io.*;
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) {
File f = new File (new File("SPY.txt").getAbsolutePath());
System.out.println(f.exists());
Scanner s = new Scanner(f);
}
}
Output: True
Exception in thread "main" java.lang.RuntimeException: Uncompilable
source code - unreported exception java.io.FileNotFoundException; must
be caught or declared to be thrown at
scannertest.ScannerTest.main(ScannerTest.java:13)
Line 13 is
Scanner s = new Scanner(f);

The clue is in the error message:
Exception in thread "main" java.lang.RuntimeException: Uncompilable
source code - unreported exception java.io.FileNotFoundException;
must be caught or declared to be thrown at scannertest.ScannerTest.main(ScannerTest.java:13)
What it means is that Scanner constructor throws an exception, so you need to place it in try/catch block, like so:
import java.io.*;
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) {
//try block starts here
try {
File f = new File (new File("SPY.txt").getAbsolutePath());
System.out.println(f.exists());
Scanner s = new Scanner(f);
}
//catch the exception
catch(FileNotFoundException e) {
e.printStackTrace();
}
}
}
Check the docs here and here

FileNotFoundException is a checked exception that's thrown by that particular Scanner constructor. Either declare it with a throws clause, or put a try-catch block in there.
This has nothing to do with whether the file exists or not, but everything to do with exception handling in Java.

You are not getting an exception that the file is not found, you are getting an error about Uncompilable source code because you didn't handle an exception.
You have "Unhandled exception type FileNotFoundException" in:
new Scanner(f)
Solutions:
Surround with try-catch.
Declare main to throw FileNotFoundException.
//1
try {
File f = new File (new File("SPY.txt").getAbsolutePath());
System.out.println(f.exists());
Scanner s = new Scanner(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OR
//2
public static void main(String[] args) throws FileNotFoundException {

Related

Exception in thread "main" java.io.IOException: No source has been specified

I'm using Java to create a program that takes in a CSV file and outputs an Arff file. Whenever the program runs it comes up catching the exception that No source has been specified. When I delete the try catch it comes with the following error and I am not sure why,
Exception in thread "main" java.io.IOException: No source has been specified
at weka.core.converters.CSVLoader.getDataSet(CSVLoader.java:867)
at CSVtoArff.Convert(CSVtoArff.java:10)
at CSVtoArff.main(CSVtoArff.java:23)
Below is the code for the program
import weka.core.Instances;
import weka.core.converters.CSVLoader;
import weka.core.converters.ArffSaver;
import java.io.File;
public class CSVtoArff {
public static void Convert(String input, String output) throws Exception {
try {
CSVLoader load = new CSVLoader();
load.setSource(new File(input));
Instances data = load.getDataSet();
ArffSaver save = new ArffSaver();
save.setInstances(data);
save.setFile(new File(output));
save.writeBatch();
System.out.println("File successfully converted");
}
catch (Exception e) {
System.out.println("Does not meet arff standards: " + e.getMessage());
}
}
public static void main(String[] args) throws Exception{
String input = "C:\\Users\\jason\\Desktop\\example.csv";
String output =" C:\\Users\\jason\\Desktop\\example.arff";
Convert(input, output);
}
}
Please try putting the files in C:\temp folder and change it to below and try.
Sometime windows security my be denying access to protected system folders.
Also there is an extra leading space in output file path. I have removed that.
public static void main(String[] args) throws Exception{
String input = "C:/temp/example.csv";
String output ="C:/temp/example.arff";
Convert(input, output);
}

FileInputStream constructor throws FileNotFoundException when I pass a file to it in IntelliJ

I'm trying to create a FileInputStream object in IntelliJ however when I instantiate the object by passing the file to the constructor, I get an error message underneath saying that there's an unhandled FileNotFoundException. This stops me from even building my project. Here's the code that I'm working with:
import java.io.File;
import java.io.FileInputStream;
public class FileInputTest {
public void Test() {
File newFile = new File("RandomFile.txt");
FileInputStream newStream = new FileInputStream(newFile);
}
}
There's an error message beneath the line where I instantiate the FileInputStream object stating that there's an unhandled FileNotFoundException. Even though there's no error beneath the instantiation of newFile and RandomFile.txt is in the working directory in IntelliJ. The project won't even build because of this, anyone know a fix?
When working with files the compiler raises a checked Exception in your case it is FileNotFoundException. To fix the problem:
public class FileInputTest {
public void Test() {
try{
File newFile = new File("RandomFile.txt");
FileInputStream newStream = new FileInputStream(newFile);
}catch(FileNotFoundException ex){
ex.printStackTrace();
}
}
}
Also try to have a look at Exception Handling and I/O topics.

Java - System.setOut does not save an exception message

It seems that System.setOut() does not work in this test case.
Here are problem description.
test0 executes System.setOut(new PrintStream(byteBuffer)) so that it stores standard output.
test0 invokes AddChild1_wy_v1.main.
In the AddChild1_wy_v1.main, xml.addChild(null) generates an exception message.
The exception message should be stored in byteBuffer, but it seems it wasn't.. JVM stops running the test case once the exception message pops up. And the remaining code after AddChild1_wy_v1.main are not executed.
Is there a way for jvm to execute the remaining code in test0?
NanoAddChild1_wy_v1Tests.java
package tests;
import junit.framework.TestCase;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import net.n3.nanoxml.*;
public class NanoAddChild1_wy_v1Tests extends TestCase {
public void test0() throws Exception { //addchild1.out
String result;
ByteArrayOutputStream byteBuffer;
byteBuffer = new ByteArrayOutputStream();
System.setOut(new PrintStream(byteBuffer));
AddChild1_wy_v1.main(new String[] {"/home/junghyun/Dev/nanoxml/inputs/simple.xml"});
result = new String(byteBuffer.toByteArray());
assertEquals(result, "Exception in thread \"main\" java.lang.IllegalArgumentException: child must not be null\n\tat net.n3.nanoxml.XMLElement.addChild(XMLElement.java:165)\n\tat AddChild1_wy_v1.main(AddChild1_wy_v1.java:47)\n");
}
}
AddChild1_wy_v1.java
package tests;
import net.n3.nanoxml.IXMLParser;
import net.n3.nanoxml.IXMLReader;
import net.n3.nanoxml.StdXMLReader;
import net.n3.nanoxml.XMLElement;
import net.n3.nanoxml.XMLParserFactory;
import net.n3.nanoxml.XMLWriter;
public class AddChild1_wy_v1
{
public static void main(String args[])
throws Exception
{
if (args.length == 0) {
System.err.println("Usage: java DumpXML file.xml");
Runtime.getRuntime().exit(1);
}
IXMLParser parser = XMLParserFactory.createDefaultXMLParser();
IXMLReader reader = StdXMLReader.fileReader(args[0]);
parser.setReader(reader);
XMLElement xml = (XMLElement) parser.parse();
xml.addChild (null);
(new XMLWriter(System.out)).write(xml);
}
}
There's 3 default streams:
System.in : InputStream
System.out :PrintStream
System.err :PrintStream
So to set each one there is 3 methods:
public static void setIn(InputStream in) {...}
public static void setOut(PrintStream out) {...}
public static void setErr(PrintStream err) {...}
To set System.err you must use System.setErr(yourStream);
For another question: you just need to use
try {
//throwing exception
} catch (Exception e) {
//act on exception
}
It seems to me that you never write that Exception at all.
You just throw it upwards. Try catch it and have ex.printStackTrace();
Also that will go to standard error, unless you specifically say otherwise.
As by your request I will leave the test0 method unaltered, you can use it the way it is.
in AddChild1_wy_v1.java:
public class AddChild1_wy_v1 {
public static void main(String args[]) // note that I don't throw the Exception.
{
try {
if (args.length == 0) {
System.err.println("Usage: java DumpXML file.xml");
Runtime.getRuntime().exit(1);
}
IXMLParser parser = XMLParserFactory.createDefaultXMLParser();
IXMLReader reader = StdXMLReader.fileReader(args[0]);
parser.setReader(reader);
XMLElement xml = (XMLElement) parser.parse();
xml.addChild (null);
(new XMLWriter(System.out)).write(xml);
} catch (Exception any) {
any.printStackTrace(System.out); // note that I send the Stack Trace to standard out here.
}
}
}
Wrap your method call in a try-catch to continue past the exception:
try {
AddChild1_wy_v1.main(...);
} catch(Throwable t) {
t.printStackTrace();
}
// the rest of your code will execute
Exceptions are printed to standard error, not standard output. Try System.setErr.
Never post images of your code.

create multiple files do loop with java and store in a drive , how to?

my first java program ..
so I'm trying to create a file and store in my pc using java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class createfile {
public static void main(String[] args) throws IOException {
int[] numbers = {1,2,3};
for (int item : numbers) {
String key = "file" + item;
File file = File.createTempFile("c:\\",key,".txt");
Writer writer = new OutputStreamWriter(new FileOutputStream(file));
writer.write("abcdefghijklmnopqrstuvwxyz\n");
writer.write("01234567890112345678901234\n");
writer.write("!##$%^&*()-=[]{};':',.<>/?\n");
writer.write("01234567890112345678901234\n");
writer.write("abcdefghijklmnopqrstuvwxyz\n");
writer.close();
}
return file;
}
}
what am I missing here .. I coudln't figured it out. everything seem to follow along the book.
Thanks
===========update ===========
after I took of
- return file ;
- throws IOException ;
- and change to File file = File.createTempFile(key,".txt",new File("c:\\"));
I still get this error
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Unhandled exception type IOException
Unhandled exception type FileNotFoundException
Unhandled exception type IOException
Unhandled exception type IOException
Unhandled exception type IOException
Unhandled exception type IOException
Unhandled exception type IOException
Unhandled exception type IOException
you have some mistakes in java syntax:
When you declare method as void (here public static void main(....)) it means that method has no return value - so line "return file;" not needed here.
Use use wrong signature (wrong parameters types in File.createTempFile function.
Possible usages are:
createTempFile(String prefix, String suffix)
createTempFile(String prefix, String suffix, File directory)
For additional information about File class use this link: http://docs.oracle.com/javase/6/docs/api/java/io/File.html
Following possible version of working code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class createfile
{
public static void main(String[] args) throws IOException
{
int[] numbers = {1,2,3};
for (int item : numbers)
{
String key = "file" + item;
File file = File.createTempFile(key,".txt",new File("c:\\"));
Writer writer = new OutputStreamWriter(new FileOutputStream(file));
writer.write("abcdefghijklmnopqrstuvwxyz\n");
writer.write("01234567890112345678901234\n");
writer.write("!##$%^&*()-=[]{};':',.<>/?\n");
writer.write("01234567890112345678901234\n");
writer.write("abcdefghijklmnopqrstuvwxyz\n");
writer.close();
}
}
}
You can also see another sample how to write text to file: http://www.homeandlearn.co.uk/java/write_to_textfile.html. This link use NetBeans as Java Tool for writing code. I strongly suggest to use some IDE (Eclipse,NetBeans) to write code in java.It will mark your compile mistakes and will suggest corrections.
NetBeans site:https://netbeans.org/
Welcome to Java world
public static void main(String[] args) throws IOException { doesn't return anything, so the return file statement is not required
File.createTempFile either takes String, String, File or String, String so File file = File.createTempFile("c:\\", key, ".txt"); won't compile.
Something like, File file = File.createTempFile(key, ".txt", new File("c:\\")); might be a better idea, but is depended on what you want to achieve.
The JavaDocs state that the prefix must be at least three characters long, so you'll need to pad the key value to meet these requirements.
You MAY find using something like...
File file = new File("C:\\" + key + ".txt");
more managable...

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

This question already has an answer here:
What does "error: unreported exception <XXX>; must be caught or declared to be thrown" mean and how do I fix it?
(1 answer)
Closed 8 months ago.
I am creating a class -- just a class, no main() and I am receiving the error of "unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown" at this line:
FileOutputStream outStr = new FileOutputStream(FILE, true);
I don't understand; I put in a try{} catch{} block and it's still reporting the error.
Additionally, it's also reporting an "illegal start of type" for the try and both catch lines, and it's also saying that ';' is expected for both catch lines.
I'm using the NetBean IDE, FYI.
Thank you for any help.
Here is the full code:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.FileNotFoundException;
public class UseLoggingOutputStream
{
String FILE = "c:\\system.txt";
try
{
FileOutputStream outStr = new FileOutputStream(FILE, true);
}
catch(FileNotFoundException fnfe)
{
System.out.println(fnfe.getMessage());
}
catch(IOException ioe)
{
System.out.println(ioe.getMessage());
}
}
You need to put the file processing statements inside a method:
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
public class UseLoggingOutputStream {
public void myMethod() {
String file = "c:\\system.txt";
try {
FileOutputStream outStr = new FileOutputStream(file, true);
} catch(FileNotFoundException fnfe) {
System.out.println(fnfe.getMessage());
}
}
}
All functional code needs to go into methods - I don't see a method in your code - that's the illegal start of type problem. The other compile errors should become clearer once you get the basics down.
public class Foo {
public void doSomething() {
//code here
}
}
Move this code to some method or at least to a static initializer block.
import java.io.*;
import java.util.*;
public class SortNames {
private String[] strings = new String[10];
private int counter;
public SortNames() {
ArrayList<String> names = new ArrayList<String>();
Scanner scan = null;
File f = null;
try{
f = new File("names.txt");
scan = new Scanner(f);
while(scan.hasNext()) names.add(scan.next());
}
finally{scan.close();}
Collections.sort(names);
for(String s:names) System.out.println(s);
}
}
Sorry if this isn't helpful to you, but I was able to solve this exact issue by adding " throws FileNotFoundException " to my method call that contained the FileWriter. I know this may not be helpful since you aren't using methods, but then again, maybe it is.

Categories

Resources