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
Related
I'm trying to pass a file from the main method to another class that should handle it, but while the file is recognized in the main class, it throws this error in the second one.
Exception in thread "main" java.io.FileNotFoundException: file:/home/giovanni/Desktop/spring-course/exercises-part2/word-inspection/target/classes/words.txt (File o directory non esistente)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:219)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157)
at java.base/java.util.Scanner.<init>(Scanner.java:639)
at com.vanny96.WordInspection.<init>(WordInspection.java:16)
at com.vanny96.App.main(App.java:13)
The path for the file is correct, and the file is there, so I have no idea why it isn't working.
I tried looking around for a solution but couldn't find any, and the fact that the file works fine in the main method while not in another one confused me a lot, if you could point me to a thread where this is solved it would be enough!
Here is the code:
Main App
package com.vanny96;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
public class App {
public static void main(String[] args) throws FileNotFoundException
{
URL fileUrl = App.class.getClassLoader().getResource("words.txt");
File file = new File(fileUrl.toString());
WordInspection inspector = new WordInspection(file);
}
}
WordInspection class
package com.vanny96;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class WordInspection {
private File file;
private Scanner reader;
public WordInspection(File file) throws FileNotFoundException {
this.file = file;
this.reader = new Scanner(this.file);
}
}
I think the Scanner is not able to resolve the file as an URL, but is able to resolve it as an URI.
If you change the line:
File file = new File(fileUrl.toString());
to
File file = new File(fileUrl.toURI());
your Scanner should be able to resolve the file (i have tested it). You will have to add an additional throws class for the toUri() method.
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
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
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 !!
When I am trying pass paramaters from crystal report SDK and export my report to PDF. It is stand alone application so I can't user crystalreportviewer options but it is keep giving me error
com.crystaldecisions.sdk.occa.report.lib.ReportSDKParameterFieldException: InternalFormatterException---- Error code:-2147217394 Error code name:missingParameterValueError My code is given below please help
import com.crystaldecisions.reports.sdk.DatabaseController;
import com.crystaldecisions.reports.sdk.ReportClientDocument;
import com.crystaldecisions.reports.sdk.ParameterFieldController;
import com.crystaldecisions.sdk.occa.report.data.IConnectionInfo;
import com.crystaldecisions.sdk.occa.report.exportoptions.ExportOptions;
import com.crystaldecisions.sdk.occa.report.exportoptions.ReportExportFormat;
import com.crystaldecisions.sdk.occa.report.lib.ReportSDKException;
public class Test {
public static void main(String args[]) throws ReportSDKException, SQLException, FileNotFoundException, IOException{
try{
ReportClientDocument reportClientDoc = new ReportClientDocument();
reportClientDoc.open("Report.rpt",0);
ParameterFieldController paramController = reportClientDoc.getDataDefController().getParameterFieldController();
paramController.setCurrentValue("","P_DP",new Integer(22));
//Here I was calling switch database code
ByteArrayInputStream byteArrayInputStream = (ByteArrayInputStream)reportClientDoc.getReportSource().export(ReportExportFormat.PDF);
IOUtils.copy(byteArrayInputStream, new FileOutputStream("new.pdf"));
reportClientDoc.close();
}
}
it starts working by just moving setting parameter code to above line. we need to set parameter before opening the report.
import com.crystaldecisions.reports.sdk.DatabaseController;
import com.crystaldecisions.reports.sdk.ReportClientDocument;
import com.crystaldecisions.reports.sdk.ParameterFieldController;
import com.crystaldecisions.sdk.occa.report.data.IConnectionInfo;
import com.crystaldecisions.sdk.occa.report.exportoptions.ExportOptions;
import com.crystaldecisions.sdk.occa.report.exportoptions.ReportExportFormat;
import com.crystaldecisions.sdk.occa.report.lib.ReportSDKException;
public class Test {
public static void main(String args[]) throws ReportSDKException, SQLException, FileNotFoundException, IOException{
try{
ReportClientDocument reportClientDoc = new ReportClientDocument();
ParameterFieldController paramController = reportClientDoc.getDataDefController().getParameterFieldController();
paramController.setCurrentValue("","P_DP",new Integer(22));
reportClientDoc.open("Report.rpt",0);
//Here I was calling switch database code
ByteArrayInputStream byteArrayInputStream = (ByteArrayInputStream)reportClientDoc.getReportSource().export(ReportExportFormat.PDF);
IOUtils.copy(byteArrayInputStream, new FileOutputStream("new.pdf"));
reportClientDoc.close();
}
}