java.lang.NullPointerException when using Java with Ruby - java

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 !!

Related

Nullpointer Exception While Using Trying to Read Excel in Selenium

Hi guys i Searched Every Where Solution For But Can't Find. Why Am Getting Null Pointer Exception For This i Dunno. Please Sort Me This Out. It is Showing as Path is Only Wrong But i Specified it Correctly only.
My Code :
package UsingExcel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.sun.rowset.internal.Row;
public class Demo
{
public void ReadExcel(String filepath,String filename,String Sheetname) throws IOException
{
File file = new File(filepath); // line 21
FileInputStream stream = new FileInputStream(file);
Workbook Mybook = null;
String FileExtensionnname = filename.substring(filename.indexOf("."));
if(FileExtensionnname.equals(".xlsx"))
{
Mybook = new XSSFWorkbook(stream);
}
else if(FileExtensionnname.equals(".xls"))
{
Mybook = new HSSFWorkbook(stream);
}
Sheet filesheet = Mybook.getSheet(Sheetname);
int rowcount = filesheet.getLastRowNum()-filesheet.getFirstRowNum();
for(int i=0;i<rowcount+1;i++)
{
org.apache.poi.ss.usermodel.Row row =filesheet.getRow(i);
for(int j=0;j<row.getLastCellNum();j++)
{
System.out.println(row.getCell(j).getStringCellValue()+ "||");
}
System.out.println();
}
}
public static void main(String[] args) throws IOException
{
Demo excelfile = new Demo();
String filepath = System.getProperty("E:\\Mybook.xlsx");
excelfile.ReadExcel(filepath, "Mybook.xlsx", "DemoExcel");
}
}
My Error is :
Exception in thread "main" java.lang.NullPointerException
at java.io.File.<init>(Unknown Source)
at UsingExcel.Demo.ReadExcel(Demo.java:21)
at UsingExcel.Demo.main(Demo.java:61)
Hope You Have Understood My Problem, Please Sort This out. But When am Testing a Login Page Using Excel That No Problem Will Be Coming, Now i Try To Print on The
Console it is Not Working.
Your filepath should just be
String filepath = "E:\\Mybook.xlsx", don't use System.getProperty.
From docs :
Gets the system property indicated by the specified key
A null is being passed to your method ReadExcel(...), because there is no System property defined as E:\Mybook.xlsx

folder and file creation not working

I am currently having trouble creating a folder and a file if not present. I keep getting and error about it not being specified and I don't really know how to fix it.
this is my main
import java.io.IOException;
public class main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException{
timeKeepHome ja = new timeKeepHome();
//ja.setVisible(true);
fileTimeLog log = new fileTimeLog();
log.checkFile();
}
}
and this is my class to create the file/ folder.
import java.io.IOException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Formatter;
public class fileTimeLog
{
File log = new File("log/sixWeek.dat");
File folder = new File("log");
PrintWriter logW = new PrintWriter("log/sixWeek.dat");
public fileTimeLog() throws IOException
{
System.out.println("successful");
checkFile();
}
public void checkFile() throws IOException
{
if(!(log.exists()))
{
createFile();
}
}
public void saveTime() throws IOException
{
}
public void saveDate()
{
}
public void createFile() throws IOException
{
folder.mkdir();
logW = new PrintWriter(log);
logW.println("DONT MODIFY THIS FILE IF UNLESS YOU KNOW WHAT YOUR ARE DOING ");
logW.close();
}
}
and the error i'm getting
Exception in thread "main" java.io.FileNotFoundException: log\sixWeek.dat (The system cannot find the path specified)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
at java.io.PrintWriter.<init>(PrintWriter.java:184)
at fileTimeLog.<init>(fileTimeLog.java:17)
at main.main(main.java:18)
I would make everything look nicer and neater but I'm just really frustrated and I've done research but don't really understand.
The Printwriter will try and create a file, so when you do this
PrintWriter logW = new PrintWriter("log/sixWeek.dat");
in your class defintion, then it will try to create it, but the folder does not exist until you do createFile
As you re-initialize logW in createFile anyway, you do not need to initialize it in your class defintion

Incomplete java.net.URL.openStream() stream

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

Java InputStream NullPointerException

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

javascript error"java.lang.NullPointerException" in netbeans

Im trying to use javascript with netbeans. Im supposed to make a mastermind game using javascript. when ı tried to add something to .js ı always have this error;
Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:78)
at java.io.InputStreamReader.<init>(InputStreamReader.java:72)
at assgn1.Main.main(Main.java:32)
ı couldnt figur out why. thanks for any help.
my codes are;
Main.java
package assgn1;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Main {
public static void main(String[] args) throws ScriptException {
// TODO code application logic here
// create manager
ScriptEngineManager m = new ScriptEngineManager();
// create javascript script engine
ScriptEngine js = m.getEngineByName("javascript");
// evaluate "hello.js"
InputStream strm = Main.class.getResourceAsStream("/hello.js");
Reader r = new InputStreamReader(strm);
js.eval(r);
}
}
hello.js
importPackage(javax.swing);
importClass(java.lang.System);
function exit(){
System.exit(0);
}
var f= new JFrame("MasterMind");
var b= new JButton("exit");
b.addActionListener(exit);
f.add(path);
f.add(b,"South");
f.setSize(800,800);
f.visible=true;
You should check if
InputStream strm = Main.class.getResourceAsStream("/hello.js");
doesnt return a null object because the path is wrong. Seems like you get the NullPointerException because of that.

Categories