i wrote a simple program which is in my book.
but i'm getting the MalformedURLException exception.This is my code
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class ImageGreet{
public static void main(String []args){
URL imageLocation = new URL("http://horstmann.com/java4everyone/duke.gif");
JOptionPane.showMessageDialog(null,"Hello","Title",JOptionPane.PLAIN_MESSAGE,new ImageIcon(imageLocation));
}
}
but my friend said he got it right with the same code.
what's wr9ong with my code? Is it because of the internet connection(I'm using a dial-up connection)
I
Java uses the concept of checked Exceptions. You need to put this code inside a try/catch block, since it is bound to throw a MalformedURLException. Something like
URL imageLocation = null;
try {
imageLocation = new URL("http://horstmann.com/java4everyone/duke.gif");
} catch (MalformedURLException mue) {
mue.printStackTrace();
}
Or let the main method throws the Exception like :
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class ImageGreet{
public static void main(String []args) throws MalformedURLException {
URL imageLocation = new URL("http://horstmann.com/java4everyone/duke.gif");
JOptionPane.showMessageDialog(null,"Hello","Title",JOptionPane.PLAIN_MESSAGE,new ImageIcon(imageLocation));
}
}
catch the MalformedURLException using try and catch block
try {
URL imageLocation = new URL("http://horstmann.com/java4everyone/duke.gif");
JOptionPane.showMessageDialog(null,"Hello","Title",
JOptionPane.PLAIN_MESSAGE,new ImageIcon(imageLocation));
}
catch (MalformedURLException e) {
// new URL() failed
// ...
}
Your internet connection would not cause that Exception. (If your URL did not exist, Java would throw an IOException, probably a FileNotFoundException, per URLConnection documentation.) In fact, your code isn't throwing an Exception at all! What you're seeing is a compile error:
$ javac ImageGreet.java
ImageGreet.java:7: error: unreported exception MalformedURLException; must be caught or declared to be thrown
URL imageLocation = new URL("http://horstmann.com/java4everyone/duke.gif");
^
1 error
When Java tries to turn your program from source code into machine code, it finds a problem, so it stops and asks you to fix it. Your code hasn't run yet -- Java's warning you that there's a problem with your program's source code. (If you're running an IDE, this will show up in a "problems" pane, as opposed to an error message from javac.)
The issue is that you need to catch the MalformedURLException in your code, or declare that main throws MalformedURLException. For example:
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class ImageGreet{
public static void main(String []args) throws MalformedURLException {
URL imageLocation=new URL("http://horstmann.com/java4everyone/duke.gif");
JOptionPane.showMessageDialog(null,"Hello","Title",JOptionPane.PLAIN_MESSAGE,new ImageIcon(imageLocation));
}
}
Note that I've added throws MalformedURLException to the end of your main method, which is the latter of the solutions I suggested above. That tells Java that your main method may propagate an Exception of type MalformedURLException.
Since Java has checked exception you have to add throws MalformedURLException to your methods header or you have to write the method logic inside try/catch blocks.
Related
I’m using java.net.URL.openStream() to access a HTTPS resource. The returned stream is incomplete for some URLs: for the example below, it yields a 1,105,724 byte-file whereas the same URL accessed from a browser yields a 5,755,858 byte-file (even when "disabling" Content-Encoding).
And it doesn’t even throw an exception.
What am I missing?
import static java.nio.file.Files.copy;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Paths;
public class Test {
public static void main(String... args) throws IOException {
try (final InputStream in = new URL(
"https://upload.wikimedia.org/wikipedia/commons/9/95/Germany_%28orthographic_projection%29.svg").openStream()) {
copy(in, Paths.get("germany.svg"));
}
}
}
Edit
I’ve tested this code a lot of times (on different networks, but always on JRE 1.8.0_60 / Mac OS X 10.11.4), and sometimes it’s suddenly "starting to work".
However, switching to another of my problematic URLs (e.g. "https://upload.wikimedia.org/wikipedia/commons/c/ce/Andorra_in_Europe_%28zoomed%29.svg") enables me to reproduce the issue.
Does this mean that it is a server issue? I’ve never seen it on a browser though.
It's working fine.
As others have suggested there may be a problem with your network, try connecting to another network.
package test;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class TestMain2 {
public static void main(String[] args) {
System.out.println("Started");
try (final InputStream in = new URL(
"https://upload.wikimedia.org/wikipedia/commons/9/95/Germany_%28orthographic_projection%29.svg")
.openStream()) {
Path outputFile = Paths.get("test.svg");
Files.copy(in, outputFile, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Output file size : " + outputFile.toFile().length());
System.out.println("Finished");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Output
Started
Output file size : 5755858
Finished
I am trying to test some data mining algorithms from smile project (https://github.com/haifengl/smile). The testing process is simple (I have included into existing Eclipse project Maven repositories of Smile project), but with the following code I catch a NPE (Null pointer exception) with InputStream , the file is just heavy csv file necessary to be read (included in the same project folder)
package com.algorithms;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import smile.data.AttributeDataset;
import smile.data.NominalAttribute;
import smile.data.parser.DelimitedTextParser;
public class DenclueTester {
public void doTestDenclue() throws IOException, ParseException
{
DelimitedTextParser parser = new DelimitedTextParser();
parser.setResponseIndex(new NominalAttribute("class"), 0);
InputStream in = this.getClass().getResourceAsStream("USCensus1990_data1.csv");
AttributeDataset data = parser.parse("US Census data", in);
double[][] x = data.toArray(new double[data.size()][]);
int[] y = data.toArray(new int[data.size()]);
}
public DenclueTester() {} //constructor
}
The following code is executed in main :
public class Dtest
{
public static void main(String[] args) throws IOException, ParseException
{
DenclueTester dt = new DenclueTester();
dt.doTestDenclue();
}
}
Stack trace:
Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.<init>(Unknown Source)
at java.io.InputStreamReader.<init>(Unknown Source)
at smile.data.parser.DelimitedTextParser.parse(DelimitedTextParser.java:234)
at com.algorithms.DenclueTester.doTestDenclue(DenclueTester.java:18)
at com.algorithms.Dtest.main(Dtest.java:26)
Could anyone help me with that?
Solved issue by placing the csv file into /classes/package_name folder. Thanks
I want to know the JUnit test cases for the following program.please help. I have not included the main method here. Want to know the JUnit test cases for the url() method in the code. This code is to read HTML from a website and save it in a file in local machine
package Java3;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Urltohtml
{
private String str;
public void url() throws IOException
{
try
{
FileOutputStream f=new FileOutputStream("D:/File1.txt");
PrintStream p=new PrintStream(f);
URL u=new URL("http://www.google.com");
BufferedReader br=new BufferedReader(new InputStreamReader(u.openStream()));
//str=br.readLine();
while((str=br.readLine())!=null)
{
System.out.println(str+"\n");
p.println(str);
}
}
catch (MalformedURLException ex)
{
Logger.getLogger(Urltohtml.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I would rename that class to UrlToHtml and write a single JUnit test class UrlToHtmlTest.
Part of the reason why you're having problems testing this is that the class is poorly designed and implemented:
You should pass in the URL you want to scrape, not hard code it.
You should return the content as a String or List, not print it to a file.
You might want to throw that exception rather than catch it. Your logging isn't exactly "handling" the exceptional situation. Let it bubble out and have clients log if they wish.
You don't need that private data member; return the contents. That lets you make this method static.
Good names matter. I don't like what you have for the class or the method.
Why are you writing this when you could use a library to do it?
Here's what the test class might look like:
public class UrlToHtmlTest {
#Test
public void testUrlToHtml() {
try {
String testUrl = "http://www.google.com" ;
String expected = "";
String actual = UrlToHtml.url(testUrl);
Assert.assertEquals(expected, actual);
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
}
I am getting this error when I try compiling
ConnectDB.java:14: error: unreported exception ClassNotFoundException; must be caught or declared to be thrown
Class.forName("com.mysql.jdbc.Driver");
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
public class ConnectDB
{
public ConnectDB() throws SQLException
{
Class.forName("com.mysql.jdbc.Driver");
Connection dbConnect = DriverManager.getConnection("jdbc:mysql://xx.xx.xxx.xxx:3306/my_DB", "userName", "superSecurePassword");
}
}
I have downloaded and installed the driver and set the classpath but continue to get the error.
That's because the compiler is telling you that you're not catching a checked exception. You need appropriate handling:
try {
Class.forName("com.mysql.jdbc.Driver");
} catch(ClassNotFoundException e) {
// log exception, probably abort application if it can't run without a database
}
You need to place the following code
Class.forName("com.mysql.jdbc.Driver")
inside a try catch block. Because the code throws *checked exception* and compiler force to catch the checked exception.
I am trying to call a ruby function in java. but I got a NullPointerException when I run the program.
Here is my java code
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.InputStream;
public class MyProgram
{
public static void main(String[] args) throws IOException, NoSuchMethodException
{
try
{
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine rbEngine = mgr.getEngineByExtension("rb");
InputStream is = ClassLoader.getSystemResourceAsStream("src/myruby.rb");
Reader reader = new InputStreamReader(is);
rbEngine.eval(reader);
Invocable invocableEngine = (Invocable)rbEngine;
if (invocableEngine != null)
{
int set = (Integer) invocableEngine.invokeFunction("myfunc",6,6);
}
}
catch (ScriptException e)
{
System.out.println("\nScriptException = "+e);
}
}
}
And the myruby.rb file contains
def myfunc(a,b)
f=a+b
return f
end
The Error I am getting is,
Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.<init>(Unknown Source)
at java.io.InputStreamReader.<init>(Unknown Source)
at MyProgram.main(MyProgram.java:22)
Please help me to find the problem.
Thanks in Advance.
InputStream is = ClassLoader.getSystemResourceAsStream("src/myruby.rb");
Here, is is null.
Try an absolute path to open your file.
If your file is found, then there is a problem with the ClassLoader.getSystemResourceAsStream.
As LaGrandMere said in his answer is is null here.
It is null because ClassLoader.getSystemResourceAsStream is not able to find the resource specified.
ClassLoader looks for the resource in the classpath specified.
To get this resource available, add myruby.rb in your class path.
Hope this helps !!