IOException error when compiling [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I get an IOException error when trying to compile this code:
public class TextEditor extends JDialog implements ActionListener {
public TextEditor (File fich,Frame owner) throws IOException{
super(owner,true);
fichier=fich;
String langage="//fortran_regex";
cree_ihm(langage);
};
public String config( String langage ) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader (langage));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
try {
while( ( line = reader.readLine() ) != null ) {
stringBuilder.append( line );
stringBuilder.append( ls );
}
return stringBuilder.toString();
} finally {
reader.close();
}
}
private void cree_ihm(String langage) throws IOException{
config(langage);
}
}
///////When calling main
import utils.TextEditor;
public class launch_editeur {
public static void main(String[] args) throws IOException{
TextEditor editeur=new TextEditor(null);
editeur.Affiche(true);
//editeur.setControlOn(false);
}
}
What is happening?
Am I using it wrongly? I think it may have to do with the functions I called (or maybe with the classes? )
Thx

From your comment:
I get this: launch_editeur.java:5: error: cannot find symbol public static void main(String[] args) throws IOException{ ^ symbol: class IOException location: class launch_editeur 1 error
That's not the same as an IOException error (which happens at runtime), that's a compile error saying it can't find the class IOException. You need to import the IOException in the classes that use it:
import java.io.IOException;

The reader.close() call in your finally block needs a try { } catch around it, as it also can throw an IOException

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

The output file value is null (0KB)

I'm trying to write file using using file writer but the value is null :
FileReader inCorpus2=new FileReader("output2.txt");
FileWriter outCorpus2=new FileWriter("Doc2(THE WANTED FILE).txt");
Scanner sc2=new Scanner(inCorpus2);
try{
while(sc2.hasNextLine()){
String tempLine=sc2.nextLine();
Scanner sc3=new Scanner(tempLine);
while(sc3.hasNext()){
String temp=sc3.next();
for(int i=0;i<UC.length;i++){
for(int j=0;j<temp.length();j++){
if(temp.charAt(j)==UC[i])temp=removeChar(temp,j);
}
}
And this is the error massage :
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at aya.SecondFilePreproc.main(SecondFilePreproc.java:25)
I hope i was clear , i tried my best .. help me please .
Not sure if it's help, need to see full code. Just added some exceptions.
import java.io.*;
import java.util.Scanner;
public static String removeChar(String x,int y){
return "something";
}
public class SomeClass {
public static void main(String[] args) throws FileNotFoundException, IOException {
try(FileReader inCorpus2=new FileReader("output2.txt");
FileWriter outCorpus2=new FileWriter("Doc2(THE WANTED FILE).txt");
Scanner sc2=new Scanner(inCorpus2)
){
while(sc2.hasNextLine()){
String tempLine=sc2.nextLine();
Scanner sc3=new Scanner(tempLine);
while(sc3.hasNext()){
String temp=sc3.next();
//just a guess what is UC
//char UC[]={'A','B','C'};
}
for(int i=0;i<UC.length;i++){
for(int j=0;j<temp.length();j++){
if(temp.charAt(j)==UC[i])temp=removeChar(temp,j);
}
}
}
}
}
}

read only text from url using java

I have been trying to execute this program, but it shows error saying that urlconnectionreader cannot be resolved. I'm new to programming. Can someone help me with this?
This is my code:
import java.net.*;
import java.io.*;
public class ReadTextFromUrl {
public static String getText(String url) throws Exception {
URL website = new URL(url);
URLConnection connection = website.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
return response.toString();
}
public static void main(String[] args) throws Exception {
// enter code here
String content = URLConnectionReader.getText(args[0]);
System.out.println(content);
}
}
There are Many Libraries to read text from URL,
You can Try jsoup library to read or extract only text.
import java.io.IOException;
import org.jsoup.Jsoup;
public class ReadTextFromURL {
public static void main(String[] args) throws IOException {
String text = Jsoup.connect("https://stackoverflow.com/questions/40741265/read-only-text-from-url-using-java").get().text();
System.out.println(text);
}
}
In your case the class name should be URLConnectionReader or you can change the the calling function via your class name .
String content = ReadTextFromUrl.getText(args[0]);
what you need to study more is objects.you must know that the classes are the blueprints.you cant use a saw blueprint to saw a tree.you need the saw itself.and by creating a object from that class you will have the saw.so when you have the saw in your hands you can saw the tree.making an object from a class works exactly the same.and using the ways(methods) to saw the tree with the actual saw is like using the methods of the class.
lets think you have a class named Saw and it has a method named sawTheTree.
public class Saw {
public void sawTheTree {
// do the sawing
}
}
its the blueprint by now.to use this saw and the method you need this :
Saw saw = new Saw();
now you have the saw in your hands.lets go and saw the tree.for this you need this code in your main method or where ever you feel the need of sawing the tree.
saw.sawTheTree();
now the the saw will saw the tree for you.
P.S: in your code you have declared the getText method static so you don't need the object creation part.if you are asking why look again at static statement description.but to use a non static method from a class you need to create the object.

Scanner keeps throwing FileNotFound Exception [duplicate]

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 {

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.

Categories

Resources