This question already has answers here:
Java: NullPointerException from class.getResource( ... )
(5 answers)
InputStream.getResourceAsStream() giving null pointer exception
(7 answers)
Closed 1 year ago.
I am relatively new to Java, and as a learning experience, tried to build a classifier in java by reading a dataset from a file called "dataset.csv"
This is the code I wrote for the whole class:
import java.io.IOException;
import weka.classifiers.trees.J48;
import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.core.converters.CSVLoader;
import weka.core.Instances;
public class classifier {
public static final String DATASET = "dataset.csv";
public static Instances getData(String filename) throws IOException
{
CSVLoader loader = new CSVLoader();
loader.setSource(classifier.class.getResourceAsStream("/"+filename));
System.out.println("getData function running");
Instances dataset = loader.getDataSet();
return dataset;
}
public static void J48Classifier() throws Exception
{
Instances dataset = getData(DATASET);
Classifier j48 = new J48();
j48.buildClassifier(dataset);
Evaluation eval = new Evaluation(dataset);
eval.evaluateModel(j48,dataset);
System.out.println("Evaluation with dataset: ");
System.out.println(eval.toSummaryString());
System.out.println("Expression as per the algorithm: ");
System.out.println(j48);
System.out.println(eval.toMatrixString());
System.out.println(eval.toClassDetailsString());
}
public static void main(String args[]) throws Exception
{
J48Classifier();
}
}
But once I run the code, I am getting this error:
This is my file Structure for reference (the dataset.csv file is located in the src directory of the below cited image):
Can anyone help me figure out if I have missed out on something?
Related
This question already has answers here:
Run cmd commands through Java
(14 answers)
Closed 10 months ago.
I want to run some commands from Java, but the following program does not print out the expected result. Any ideas?
import java.io.IOException;
public class MyClass {
public static void main(String args[]) throws IOException {
Process p = new ProcessBuilder("gcc", "--version").start();
}
}
You need to set the source and destination for subprocess standard I/O to be the same as those of the current Java process. You can to this by calling:
ProcessBuilder.inheritIO();
So your example should look something like:
import java.io.IOException;
public class MyClass {
public static void main(String args[]) throws IOException {
ProcessBuilder processBuilder = new ProcessBuilder("gcc", "--version");
processBuilder.inheritIO();
processBuilder.start()
}
}
For advanced process I/O usage you should take a look at ProcessBuilder and Process JavaDocs.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Have below Selenium Program using Object Repository Library File but the same is failing and shows java.lang.NullPointerException. Have commented the specific syntax lines as "error". Also attached the error screenshot and config.property files.enter image description here. Have tried to identify the cause but could not. please clarify the cause of the failing and error message.
package objectrepository;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;
import objectrepository.Lib_ChromeDriver;
public class OBRClass_2 {
#Test
public void launch_chrome() throws Exception{
Lib_ChromeDriver LCD = new Lib_ChromeDriver();// Lib_ChromeDriver is the Object Repository Library File
System.setProperty("webdriver.chrome.driver", LCD.Path());// error shown
WebDriver Snap = new ChromeDriver();
Snap.get(LCD.AppURL());
}
}
and:
// a Java Class containing Constructor & method and is saved as Library file.
// Constructor has will call the ObjectRepository File and
// method will call the Call the ChromeDriver Location to Launch the same
// this Library Class can be called in Selenium program to launch the Chrome Driver
package objectrepository;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import org.testng.annotations.Test;
public class Lib_ChromeDriver {
Properties Prop;
#Test
public void Lib_ChromeDriver() throws Exception{// Constructor calling the Object Repository File
File OB_File = new File("./Config/Config.property");
FileInputStream OB_FIS = new FileInputStream(OB_File);
Prop = new Properties();
Prop.load(OB_FIS);
}
public String Path() throws Exception{// method calling the ChromeDriver Path to Launch the same
String ChromePath = Prop.getProperty("ChromeDriver"); // error shown
return ChromePath;
}
public String AppURL() throws Exception{
String AppURL = Prop.getProperty("URL");
return AppURL;
}
}
change
public void Lib_ChromeDriver() // not a constructor
to
public Lib_ChromeDriver() // is a constructor
the code you are calling is not in your constructor but in a method called Lib_ChromeDriver
In this case your code is calling the default constructor which does not have any code in it - therefore the variable Props is never set
The following code is for reading or writing files with java, but:
Eclipse prints these errors:
buffer_1 cannot be resolved to a variable
file_reader cannot be resolved
also other attributes...
what is wrong in this code here:
//Class File_RW
package R_2;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.lang.NullPointerException;
public class File_RW {
public File_RW() throws FileNotFoundException, NullPointerException {
File file_to_read = new File("C:/myfiletoread.txt");
FileReader file_reader = new FileReader(file_to_read);
int nr_letters = (int)file_to_read.length()/Character.BYTES;
char buffer_1[] = new char[nr_letters];
}
public void read() {
file_reader.read(buffer_1, 0, nr_letters);
}
public void print() {
System.out.println(buffer_1);
}
public void close() {
file_reader.close();
}
public File get_file_to_read() {
return file_to_read;
}
public int get_nr_letters() {
return nr_letters;
}
public char[] get_buffer_1() {
return buffer_1;
}
//...
}
//main method # class Start:
package R_2;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.lang.NullPointerException;
public class Start {
public static void main(String[] args) {
File_RW file = null;
try {
file = new File_RW();
} catch (NullPointerException e_1) {
System.out.println("File not found.");
}
//...
}
}
I can't find any mistake. I have also tried to include a try catch statement into the constructor of the class "File_RW", but the error messages were the same.
Yes, there are errors in your code - which are of really basic nature: you are declaring variables instead of fields.
Meaning: you have them in the constructor, but they need to go one layer up! When you declare an entity within a constructor or method, then it is a variable that only exists within that constructor/method.
If you want that multiple methods can make use of that entity, it needs to be a field, declared in the scope of the enclosing class, like:
class FileRW {
private File fileToRead = new File...
...
and then you can use your fields within all your methods! Please note: you can do the actual setup within your constructor:
class FileRW {
private File fileToRead;
public FileRW() {
fileToRead = ..
but you don't have to.
Finally: please read about java language conventions. You avoid using "_" within names (just for SOME_CONSTANT)!
javacode already running...thx
same program edited with c++ in visual Studio express...
visit the stackoverflow entry link:
c++ file read write-error: Microsoft Visual C++ Runtime libr..debug Assertion failed, expr. stream.valid()
For my project, I am using weka.jar. I am converting a CSV file to ARFF using following code:
import weka.core.Instances;
import weka.core.converters.ArffSaver;
import weka.core.converters.CSVLoader;
import java.io.File;
public class CsvArffConverter
{
public static void Convert(String sourcepath,String destpath) throws Exception
{
// load CSV
CSVLoader loader = new CSVLoader();
loader.setSource(new File(sourcepath));
Instances data = loader.getDataSet();
// save ARFF
ArffSaver saver = new ArffSaver();
saver.setInstances(data);
saver.setFile(new File(destpath));
saver.setDestination(new File(destpath));
saver.writeBatch();
}
public static void main(String args[]) throws Exception
{
Convert("C:\\ad\\BSEIT.csv", "C:\\ad\\test.arff");
}
}
However, on executing, I am getting following error:
Cannot create a new output file. Standard out is used.
Exception in thread "main" java.io.IOException: Cannot create a new output file (Reason: java.io.IOException: File already exists.). Standard out is used.
at `enter code here`weka.core.converters.AbstractFileSaver.setDestination(AbstractFileSaver.java:421)
at Predictor.CsvArffConverter.Convert(CsvArffConverter.java:29)
at Predictor.CsvArffConverter.main(CsvArffConverter.java:34)
According to weka mail list, this error is a file issue, may be permission. Other emails suggest to use Java I/O approch to save arff file.
This error is coming from the CSVSaver and indicates that it is unable
to create the directory and/or file that you've specified. More than
likely it is something to do with permissions on where it is trying to
write to.
Try following code.
import weka.core.Instances;
import weka.core.converters.ArffSaver;
import weka.core.converters.CSVLoader;
import java.io.File;
public class CsvArffConverter
{
public static void Convert(String sourcepath,String destpath) throws Exception
{
// load CSV
CSVLoader loader = new CSVLoader();
loader.setSource(new File(sourcepath));
Instances dataSet = loader.getDataSet();
// save ARFF
BufferedWriter writer = new BufferedWriter(new FileWriter(destpath));
writer.write(dataSet.toString());
writer.flush();
writer.close();
}
public static void main(String args[]) throws Exception
{
Convert("BSEIT.csv", "test.arff");
}
}
As you can see, I use relative paths. Since absolute path writing may be blocked due to permission issues.
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...