Java: ClassNotFound Classpath issues - java

Im trying to read some information from a file into some objects. Main method just reads the Information into some string variables then uses those strings to initialize objects. Pretty simple. The objects are stored using a BST.
However, The error Im getting is ClassNotFoundException. Except when I run the java 'file' command, 'file' is spelled and capitalized correctly.
I've been reading that you can change the path that JVM uses when searching for class files.
so I tried:
set CLASSPATH=$CLASSPATH=~/../../BackEnd
but that didn't do anything..
Here is my main file..
import java.util.Scanner;
import java.io.File;
class BackEnd
{
public static void main(String args[]) throws java.io.FileNotFoundException
{
Tree.ServiceTree providers = new Tree.ServiceTree();
String path = "./providers.txt";
Scanner read = new Scanner (new File(path));
read.useDelimiter(",");
String information[] = new String[5];//array of strings used to store info from file, then used to initialize objects
try
{
while(read.hasNext())
{
for(int i = 0; i < 5; ++i)
{
information[i] = read.nextLine();//read in all the info into the array
}
Services.Service newService;//used as dynamic reference to be passed to tree
Services.Service serviceInfo = new Services.Service(information[0], information[1]);//initalizes base class to be passed to derived constructor
switch(information[0])//check type to initalize appropriate object
{
case "Dogwalk":
newService = new Services.Dogwalk(serviceInfo, information[2], information[3]);
case "Groceries":
newService = new Services.Groceries(serviceInfo, information[2], information[3]);
case "Housework":
newService = new Services.Housework(serviceInfo, information[2], information[3]);
}
providers.insert(information[4], newService);
}
read.close();
throw new java.io.FileNotFoundException("File not found...");
}
catch(java.io.FileNotFoundException exception)
{
System.out.println("File not found");
}
//providers.display();
}
}

Figured it out. Error had nothing to do with compilation or class path and was due
to uninitialized variable newService

Related

Accessing Object Property for Individual using Apache Jena

I have created an OWL ontology using Protégé, describing a patient database system. I am now attempting to develop a Java code using Apache Jena to read the OWL file I created, then perform a number of operations on it. My primary goal is to get my code to be able to find a specific Individual by name (Patient name for example) and then access a specific Object Property for that individual, and output its value. For example, A patient "John" has an object property "Treated_By" which corresponds to another individual "Amy" (Amy is an individual of type doctor). However, I have been unable to figure out which Jena method is used to retrieve Object property values from a certain individual.
Here is my code (Please ignore comments, they are fragments of previous attempts for this task):
public class Main {
public static void main(String[] args) {
OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
String fileName = "C:/Users/Ahmed Medhat/Documents/assignment1ontv3.0.owl";
try {
InputStream inputStream = new FileInputStream(fileName);
model.read(inputStream, "RDF/XML");
//model.read(inputStream, "OWL/XML");
inputStream.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
Scanner sc = new Scanner(System.in);
System.out.println("Enter Patient Name: ");
String patientName = sc.next();
ExtendedIterator<Individual> itI = model.listIndividuals();
while (itI.hasNext()) {
Individual i = itI.next();
String localName = i.getLocalName();
//System.out.println(patientName);
//System.out.println(localName);
if(localName.equals(patientName))
{
//System.out.println("Conditional Code Accessed.");
OntClass Class = i.getOntClass();
System.out.println("Patient Disease is: " + Class.listDeclaredProperties());
}
System.out.println("Failed.");
}
}
}
Try this (replace the property URI accordingly):
final Property p = model.createObjectProperty("http://example.org/Treated_by");
final RDFNode object = i.getPropertyValue(p);

How can I read Class and objects name from File using Java Reflection?

I have a file named Objects.dat and I want to read the Class name and objects name from that file using Java Reflection. I'm able to read from another Java class but not from the file. How can I solve this?
Java Class
public class EmployeeInfo {
private String username = "John";
private int userage = 23;
}
Objects.dat contains the same text as Java class.
Class Reader
public class FileRd {
public static void main(String[] args) {
try {
Class cls = Class.forName("EmployeeInfo");
Object obj = cls.newInstance();
System.out.println("Class Name-->"+obj.getClass());
Field[] fields = cls.getDeclaredFields();
for( int i = 0 ; i < fields.length ; i++ ) {
fields[i].setAccessible(true);
System.out.println("Name-->"+fields[i].getName());
}
}
catch( Exception e ) { e.printStackTrace(); }
}
}
The above code works for the Java class but I want to input the file like and read -
FileInputStream fin = new FileInputStream("D:\\Objects.bat");
and perform the above functionally but I failed to do that.
You need a Custom classloader for such, if the file is already compiled (if not you can use javac tool to compile it with classpath or an Bytecode tool like ASM or Javassist).
Then you use your ClassLoader to load the file(.class) and findClass.
Maybe Serialization / Deserialization is the better way than save Java code at the file.

Problems with scanning

I'm studying Biomedical Informatics and I'm now doing my clinical practice, where I have to check that the charges made to hospitalized patients were performed correctly on supplies that are of unique charging (every procedure and supplies used have a codification).
I can import the Excel file on the software I'm doing but, I don't know now how to do the scan.
Here is the code (I'm doing it on NetBeans),
public class Portal extends javax.swing.JFrame {
private DefaultTableModel model;
public static int con = 0;
public ArrayList listas = new ArrayList();
public ArrayList listasr = new ArrayList();
public Portal() {
initComponents();
model = new DefaultTableModel();
jTable1.setModel(model);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser examinar = new JFileChooser();
examinar.setFileFilter(new FileNameExtensionFilter("Archivos Excel", "xls", "xlsx"));
int opcion = examinar.showOpenDialog(this);
File archivoExcel = null;
if(opcion == JFileChooser.APPROVE_OPTION){
archivoExcel = examinar.getSelectedFile().getAbsoluteFile();
try{
Workbook leerExcel = Workbook.getWorkbook(archivoExcel);
for (int hoja=0; hoja<leerExcel.getNumberOfSheets(); hoja++)
{
Sheet hojaP = leerExcel.getSheet(hoja);
int columnas = hojaP.getColumns();
int filas = hojaP.getRows();
Object data[]= new Object[columnas];
for (int fila=0; fila < filas; fila++)
{
for(int columna=0; columna < columnas; columna++)
{
if(fila==0)
{
model.addColumn(hojaP.getCell(columna, fila).getContents());
}
System.out.println(hojaP.getCell(columna, fila).getContents());
if(fila>=1)
data[columna] = hojaP.getCell(columna, fila).getContents();
}model.addRow(data);
}
}
model.removeRow(0);
JOptionPane.showMessageDialog(null, "Excel cargado exitosamente");
}
}
}
Before you import the excel file save it as a csv(comma delimited) file(remeber to delete the headings). Then open the netbeans project folder under my documents, then open the your project folder and dump the csv file in their. Look at your project under files in netbeans open the folder and you will see the file in their. Now you said you want to read the file/ scan the file.
You can use my method at first, understand it and adapt to other scenarios you have in the future.
First create a class or use an readily created( you already created java class).
Declare arrays depending on how many rows you had in the excel file not the csv file and a counter.
Example two.
String [] patientsnamess;
int [] ages;
int count;
Now initiate the arrays in a deafault constructor(you don't have to because you can do it when you declare them but it is conventional). You can learn about constructors there are two I know of or there are only two but I will only show a default constructor.
It will look like this.
public yourClassName(){
patientsnames = new String[400];//the number in square brackets are an example it sets the size of the array. You can set the size according to how many patients there are or you could just use lists as the limit on the list as dependent on primary and virtual memory.
ages = new int[400];
count = 0;
}
now create the method two read the text file.
public void readFile(){
count = 0;//important
Scanner contents = null;
try{
contents = new Scanner(new FileReader("You file's name.txt");
while(contents.hasNext()){
String a = contents.nextLine();
String p[]= a.split("\\;");
patientsnames[count] = p[0];
ages[count] = p[1];
count++;//important
}
}
catch(FileNotFoundException e){
System.out.println(e.getMessage());
}
}
Now create get methods to call up the arrays with the values from the file.(Find out on rest of stackoverflow).
Remeber that field types link up with the data in the file.
I really hope this works for you. If not I am sorry but good luck with your Biochemical Informatics course.
Remeber to call the readFile method with an object in this case or it won't work.
Research the neccessary imports such as:
import java.io.*;
import java.util.*;

Getting variables from another .java file using reflection

I've managed to get reflection working by getting and formatting the variables in the class that the toString() method is in.
public class ReadFile {
public int test1 =0;
public String test2 = "hello";
Boolean test3 = false;
int test4 = 1;
public static void main(String[] args) throws IOException{
ReadFile test = new ReadFile();
System.out.println(test);
}
public String toString(){
//Make a string builder so we can build up a string
StringBuilder result = new StringBuilder();
//Declare a new line constant
final String NEW_LINE = System.getProperty("line.separator");
//Gets the name of THIS Object
result.append(this.getClass().getName() );
result.append(" Class {" );
result.append(NEW_LINE);
//Determine fields declared in this class only (no fields of superclass)
Field[] fields = this.getClass().getDeclaredFields();
//Print field names paired with their values
for ( Field field : fields ) {
result.append(" ");
try {
result.append(field.getType() + " ");
result.append( field.getName() );
result.append(": ");
//requires access to private field:
result.append( field.get(this) );
} catch ( IllegalAccessException ex ) {
System.out.println(ex);
}
result.append(NEW_LINE);
}
result.append("}");
return result.toString();
}
}
However I was wondering whether it would be possible to specify a specific file in the directory for the toString() to work on?
I have tried getting a file and plugging it in the System.out.println() but the way I see it is you need to make an instance of a class and give it the instance for it to work. So I'm not sure how that can be done programatically.
I have been trying something like this:
Path path = FileSystems.getDefault().getPath("D:\\Directory\\Foo\\Bar\\Test.java", args);
File file = path.toFile();
System.out.println(file);
However I don't get very far with it, I've mainly been seeing if I can convert the file into anything usable but I'm not sure what I need to be doing!
Any advice would be great.
I think you need to look into the ClassLoader API - you need to get an new URLClassLoader and ask it to load your .java file into the JVM. You can then reflect on it.
You can try to read the package information from the file (D:\Directory\Foo\Bar\Test.java) and than try to load it the class by its name:
Class.forName(nameOfTheClass)
Java API Class

Differentiating between reading a file, and user input in a method

This program starts off in the FleetInterface class by asking the user for a file (run()). The buildFleet() method reads the file then calls the Vehicle to the Fleet class by calling the addVehicle() method and in that method, it sets the new Vehicle object into the vehicle array.
After all that's done, a user menu comes up asking if they would like to 1.) Add a Vehicle, 2.) Delete a Vehicle.
Let's say they add a new Vehicle. The requirement is to have the user manually enter data about that vehicle (All the same info that was in the file in the beginning). The problem is that this option also calls addVehicle(). If I program in the addVehicle() method some statements like "Please enter the model of your vehicle:", that will also show up when the program first starts and calls addVehicle().
The tricky part - I am not allowed to create any new public methods (only private), and I cannot add any new class level data.
My Fleet class has 2 constructors: 1 is blank (Not allowed to set anything here.) And 1 has a parameter value of File (Used for reading the original file).
So to sum it up, I need a way for the program to start by reading the values in a file, calling addVehicle(), then also allow the user to enter in a vehicle manually via Scanner.. while also calling addVehicle()
Here is my code:
FleetInterfaceApp:
public void run() throws FileNotFoundException
{
File file = new File(getFile());
fleet = new Fleet(file);
buildFleet(file);
}
private void buildFleet(File file) throws FileNotFoundException
{
fleet = new Fleet(file);
fleet.addVehicle(Honda);
userMenu(file, fleet);
}
private void userMenu(File file, Fleet fleet) throws FileNotFoundException
{
int choice = 0;
Scanner input = new Scanner(System.in);
this.createMenu();
choice = this.menu.getChoice();
switch(choice)
{
case 1:
fleet.addVehicle(Honda);
break;
}
}
Fleet:
Class Level data (cannot change):
Vehicle[] vehicles = new Vehicle[4];
File file;
addVehicle:
public void addVehicle(Vehicle Honda[]) throws FileNotFoundException
{
Scanner reader = new Scanner(file);
if(canAddVehicle() == true)
{
for(int i = 0; i < vehicles.length; i++)
{
if(vehicles[i] == null)
{
Honda[i] = new Vehicle();
Honda[i].readRecord(reader);
vehicles[i] = Honda[i];
reader.close();
break;
}
}
System.out.println("Vehicle Added!");
}
else
{
System.out.println("You can not add more than 4 vehicles.");
}
}
You can write out the user input to a temp file and then set the file attribute in your fleet object to the temp file before you call addVehicle. The file attribute is accessible to other classes because it is scoped package private by default. This means that any classes in the same package can access it. If FleetInterfaceApp is in the same package then it can already do this.
Here is some example code based off of the code provided in the question. This needs extra work before it will run.
// somewhere inside userMenu(File file, Fleet fleet)
File tempFile = File.createTempFile( "tmp", ".tmp" );
FileWriter fout = new FileWriter( tempFile );
fout.append( userInput );
fout.close();
fleet.file = tempFile;
switch(choice)
{
case 1:
fleet.addVehicle(Honda);
break;
}

Categories