Could not find main class Java - java

I have two classes Pair.java and Users.java where Users.java has the main program. Both these java files are under the package userdetails.
In unix,
I compiled it using the command
javac -d . -classpath avro-1.7.5.jar:lib/*:jackson-core-asl-1.9.13.jar:lib/* Pair.java Users.java
the class are under the folder userdetails.
I tried to run using the command
java -classpath avro-1.7.5.jar:lib/*:jackson-core-asl-1.9.13.jar:lib/* userdetails.Users
I'm getting error
Could not find main class userdetails.Users
Kindly help me.
source code :-
import java.io.File;
import java.io.IOException;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.specific.SpecificDatumReader;
import org.apache.avro.specific.SpecificDatumWriter;
import org.apache.avro.util.Utf8;
public class Users {
public void createUser() {
userdetails.Pair datum = new userdetails.Pair(new Utf8("L"), new Utf8("R"));
DatumWriter writer = new SpecificDatumWriter();
DataFileWriter fileWriter = new DataFileWriter(writer);
try {
fileWriter.create(datum.getSchema(), new File("users.avro"));
fileWriter.append(datum);
System.out.println(datum);
fileWriter.close();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("ERROR");
e.printStackTrace();
} }
public static void main(String[] args) {
Users user = new Users();
user.createUser();
}
}

When you specify a classpath, the current working directory is not automatically contained any more, so you must add it to the classpath:
java -classpath avro-1.7.5.jar:lib/*:jackson-core-asl-1.9.13.jar:lib/*:. userdetails.Users

You say both classes are under the package "userdetails", but there is no package declaration at the beginning of your source. Both Pair.java and User.java should begin with the line:
package userdetails;
Check out the Java Packages Tutorial

Related

Run java class from cmd with full path?

I have compile a java file
javac XSDValidator.java
And I get a XSDValidator.class
Lets say I have the the class (XSDValidatorc.class) file in
C:\xampp\htdocs\xsd_validtion
And I write this in cmd
C:\xampp\htdocs\xsd_validtion> java XSDValidator students.xsd students.xml
It works fine. But its not working if I I'am in another directory and want to run the file with absolute path. Why doesn't it work?
Lite this, lets say I'am in the directory
C:\aaa\User\Document
And write like this it's not working.
java C:\xampp\htdocs\xsd_validtion\XSDValidator C:\xampp\htdocs\xsd_validtion\students.xsd C:\xampp\htdocs\xsd_validtion\students.xml
This is the java-file
https://www.tutorialspoint.com/xsd/xsd_validation.htm
import java.io.File;
import java.io.IOException;
import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.SAXException;
public class XSDValidator {
public static void main(String[] args) {
if(args.length !=2){
System.out.println("Usage : XSDValidator <file-name.xsd> <file-name.xml>" );
} else {
boolean isValid = validateXMLSchema(args[0],args[1]);
if(isValid){
System.out.println(args[1] + " is valid against " + args[0]);
} else {
System.out.println(args[1] + " is not valid against " + args[0]);
}
}
}
public static boolean validateXMLSchema(String xsdPath, String xmlPath){
try {
SchemaFactory factory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new File(xsdPath));
Validator validator = schema.newValidator();
validator.validate(new StreamSource(new File(xmlPath)));
} catch (IOException e){
System.out.println("Exception: "+e.getMessage());
return false;
}catch(SAXException e1){
System.out.println("SAX Exception: "+e1.getMessage());
return false;
}
return true;
}
}
use the java classpath:
java -cp C:\xampp\htdocs\xsd_validtion\ XSDValidator C:\xampp\htdocs\xsd_validtion\students.xsd C:\xampp\htdocs\xsd_validtion\students.xml
This includes the directory where the class file is located to the classpath.
directories in java are package structures. Thats why you can not use it as a normal Path
The answer from Jens
java -cp C:\xampp\htdocs\xsd_validtion\ XSDValidator C:\xampp\htdocs\xsd_validtion\students.xsd C:\xampp\htdocs\xsd_validtion\students.xml
can be the accepted one. I just want to give another solution, in some situations, it's better
CD C:\xampp\htdocs\xsd_validtion
java XSDValidator students.xsd students.xml
CD C:\aaa\User\Document

"Attributes and objects cannot be resolved" - error

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()

While creating this java program in oracle db. Im facing some errors. CAn anyone tell me the way to compile it. the code is as follows

Below code is working properly in eclipse. But I,m trying to create this source in oracle 11g Db. While creating it throws some warnings.
create or replace
and compile java source named "Noitime"
as
package com;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
public class Noitime {
public String attr(String filepath,String filename)
{
long time = System.currentTimeMillis();
FileTime fileTime = FileTime.fromMillis(time);
Path path = Paths.get(filepath,filename);
try {
Files.setLastModifiedTime(path, fileTime);
return "Success";
} catch (IOException e) {
System.err.println(e);
return "Fail";
}
}
}
You appear to have garbled the error/warning message, but I think that it is telling you that you should be using the pathname "com/Noitime.java" when compiling. The pathname you use should correspond to the full class name, and the full class name is "com.Noitime".

how to set classpath for com.sun.tools.javac.Main.compile() function?

I am using com.sun.tools.javac.Main.compile() function to compile java file at run time from my struts projects. But for some files they need some specific jars like axis2. I have the jars but how can i set them to classpath to compile the java file at runtime? I have tried with System.setProperty("java.class.path","jar dir"); but failed to compile.
The following code which uses com.sun.tools.javac.Main worked for me:
Apple.java
//This class is packaged in a jar named MyJavaCode.jar
import com.xyz.pqr.SomeJavaExamples;
public class Apple {
public static void main(String[] args) {
System.out.println("hello from Apple.main()");
}
}
AClass.java
import com.sun.tools.javac.Main;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class AClass {
public static void main(String[] args) {
try {
//Specify classpath using next to -cp
//This looks just like how we specify parameters for javac
String[] optionsAndSources = {
"-g", "-source", "1.5",
"-target", "1.5",
"-cp", ".:/home/JavaCode/MyJavaCode.jar",
"Apple.java"
};
PrintWriter out = new PrintWriter(new FileWriter("./out.txt"));
int status = Main.compile(optionsAndSources, out);
System.out.println("status: " + status);
System.out.println("complete: ");
}catch (Exception e) {}
}
}
Note: To compile this AClass.java, tools.jar needs to be in the classpath, which is not there by default, so you will have to specify it.
If you are using Java 1.6 then you should consider using javax.tools.JavaCompiler instead, its getTask() methods takes an argument options which can have the classpath.
For example:
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import javax.tools.JavaFileObject;
public final class AClass {
private static boolean compile(JavaFileObject... source ){
List<String> options = new ArrayList<String>();
// set compiler's classpath to be same as the runtime's
options.addAll(Arrays.asList("-classpath", System.getProperty("java.class.path")));
//Add more options including classpath
final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
final JavaCompiler.CompilationTask task = compiler.getTask(/*default System.err*/ null,
/*std file manager*/ null,
/*std DiagnosticListener */ null,
/*compiler options*/ options,
/*no annotation*/ null,
Arrays.asList(source));
return task.call();
}
com.sun.tools.javac.Main is deprecated and undocumented too.

How to handle this error on kabeja?

I need to generate SVG from given DXF file. I try to archive that by using kabeja package. This is the code that they gave on their web page.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.xml.sax.ContentHandler;
import org.kabeja.dxf.DXFDocument;
import org.kabeja.parser.DXFParseException;
import org.kabeja.parser.Parser;
import org.kabeja.parser.ParserBuilder;
import org.kabeja.svg.SVGGenerator;
import org.kabeja.xml.SAXGenerator;
public class MyClass{
public MyClass(){
...
}
public void parseFile(String sourceFile) {
Parser parser = ParserBuilder.createDefaultParser();
try {
parser.parse(new FileInputStream(sourceFile));
DXFDocument doc = parser.getDocument();
//the SVG will be emitted as SAX-Events
//see org.xml.sax.ContentHandler for more information
ContentHandler myhandler = new ContentHandlerImpl();
//the output - create first a SAXGenerator (SVG here)
SAXGenerator generator = new SVGGenerator();
//setup properties
generator.setProperties(new HashMap());
//start the output
generator.generate(doc,myhandler);
} catch (DXFParseException e) {
e.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
Hear is the code that provided by the kabeja development group on sourceforge web site. But in above code I noticed that some of the classes are missing on their new package. for example
ContentHandler myhandler = new ContentHandlerImpl();
In this line it create contentHandlerImpl object but with new kabeja package it dosn't have that class.So because of this it doesn't generate SVG file. So could some one explain me how to archive my target by using this package.
Try to read symbol ContentHandlerImpl not found from kabeja's forum

Categories

Resources