Java command error. Couldn't find or load main class - java

Today I meet a problem with "java" command.
I work in Intellij IDEA and think that I wrong classpath to "java" command.
Please, help me.
package ru.mch;
import ru.mch.RunTask;
public class Program {
public static void main(String[] args) {
String taskCode = "class UserProgram{ public static void main(String[] args) { int b = 3 + 1; System.out.println(b);}}";
String packageName = "package ru.mch; ";
String all = packageName + taskCode ;
RunTask runTask = new RunTask(all);
int result = runTask.run();
}
}
I want to get program code from String, create new java class, write code to the class and compile and run new java class.
package ru.mch;
import java.io.*;
public class RunTask {
private String answerFromPage;
private int programExitValue;
public RunTask(String answerFromPage) {
this.answerFromPage = answerFromPage;
this.programExitValue = 0;
}
private static void printLines(String name, InputStream ins) throws Exception {
String line = null;
BufferedReader in = new BufferedReader(
new InputStreamReader(ins));
while ((line = in.readLine()) != null) {
System.out.println(line);
}
}
private static int runProcess(String command) throws Exception {
Process pro = Runtime.getRuntime().exec(command);
printLines(/*command + */" stdout:", pro.getInputStream());
printLines(" stderr:", pro.getErrorStream());
pro.waitFor();
System.out.println(command + " exit value = " + pro.exitValue());
return pro.exitValue();
}
public int run(){
//String fileName = "src\\main\\java\\ru\\mch\\UserProgram.java";
String fileName = "src\\main\\java\\ru\\mch\\UserProgram.java";
File f = new File(fileName);
f.getParentFile().mkdirs();
try {
f.createNewFile();
} catch (IOException e) {
throw new IllegalArgumentException("File creating error");
}
try(FileWriter writer = new FileWriter(fileName, false))
{
writer.write(this.answerFromPage);
writer.flush();
}
catch(IOException ex){
System.out.println(ex.getMessage());
}
try {
System.out.println(runProcess("javac -sourcepath src src\\main\\java\\ru\\mch\\UserProgram.java"));
System.out.println("------------");
this.programExitValue = runProcess("java src\\main\\java\\ru.mch.UserProgram");
} catch (Exception e) {
e.printStackTrace();
}
return this.programExitValue;
}
}
This is IDEA log :
javac src\main\java\ru\mch\UserProgram.java exit value = 0
0
------------
Error: Could not find or load main class src\main\java\ru.mch.UserProgram
java src\main\java\ru.mch.UserProgram exit value = 1
New class was created and .class too.
I try to write full classpath, try to write '\' instead of '.' in package name, but all is wrong.
Sorry for my bad English.

Use the following command:
java -cp src\main\java ru.mch.UserProgram

Related

runtime.exec(batchCommand) - Issues with Space in folder

Below method return me below path
Output - "C:\ProgramData\MySQL\MySQL Server 5.5\bin\"
private String getPath() {
String mysqlpath = "";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(dbUrl, user, password);
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery("select ##datadir");
while (res.next()) {
mysqlpath = res.getString(1);
}
mysqlpath = mysqlpath.replace("\\Data", "\\bin").replace("\\", "\\\\");
System.out.println("Mysql path is :" + mysqlpath);
} catch (Exception ee) {
System.out.println(ee);
}
return mysqlpath;
}
Now i run below command to export mysql dump.
Runtime runtime = Runtime.getRuntime();
Process p = runtime.exec(batchCommand);
batchCommand - "C:\ProgramData\MySQL\MySQL Server 5.5\bin\mysqldump" -h localhost --port 3306 -u root --password=root123 --add-drop-database -B accountingbook -r "E:\softwares\Tomcat_accountingBook\webapps\accountingbookaccountingbook-localhost-(02-08-2017).sql"
Exception - java.io.IOException: Cannot run program ""C:\ProgramData\MySQL\MySQL": CreateProcess error=2, The system cannot find the file specified
I also tried below, but same issue:-
1.) Process p = runtime.exec(batchCommand.split(" "));
2.) Adding double quotes like "C:\ProgramData\MySQL\MySQL Server 5.5\bin\"
Problem is it breaks as soon as it encounters space.
From the Exception, it looks like JVM is not able to find MYSQL executable file at the location given.
This can be due to "\" file separator. Try using "\\" to separate your paths. Then your path would be : "C:\\ProgramData\\MySQL\\MySQL.
I'v written one class this might help you click here
public class RuntimeExample {
private final String commandCode = "cmd /c";
private final Scanner scanner = new Scanner(System.in);
private Process process;
private BufferedReader reader;
private String input = "";
private final String defaultCode = "help";
public RuntimeExample() {
UserInput();
}
private void UserInput() {
System.out.println("Enter command (ex: ipconfig)");
input = scanner.nextLine();
if (input.isEmpty()) {
System.out.println("You didn't give any command please take a look at these available Commands." + "\n");
sendCommand(defaultCode);
} else {
sendCommand(input);
}
}
private void sendCommand(String command) {
try {
process = Runtime.getRuntime().exec(commandCode + " " + command);
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
showResult(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void showResult(String result) {
System.out.println(result + "\n");
}
public static void main(String[] args) {
new RuntimeExample();
}
}

error in running java file using another java file

I am actually trying to run my java file using another java file in windows....and this is my code:
private static void printLines(String name, InputStream ins) throws Exception {
String line = null;
BufferedReader in = new BufferedReader(
new InputStreamReader(ins));
while ((line = in.readLine()) != null) {
System.out.println(name + " " + line);
}
}
private static void runProcess(String command) throws Exception {
String s=System.getProperty("user.dir");
s="C:\\Users\\HP\\Downloads\\apache-tomcat-7.0.54-windows-x64\\apache-tomcat-7.0.54\\webapps\\Mazil4.0\\WEB-INF\\classes";
File workingDir = new File(s);
System.out.println(q);
//new Foo().nonStaticMethod();
Process pro = Runtime.getRuntime().exec(command,null,workingDir);
printLines(command + " stdout:", pro.getInputStream());
printLines(command + " stderr:", pro.getErrorStream());
pro.waitFor();
System.out.println(command + " exitValue() " + pro.exitValue());
}
public static void mai(String[] args) {
String[] credentials=new String[4];int k=0;
for (String s: args) {
System.out.println(s);
credentials[k]=s;k++;
if(k==4)
break;
}
try {
//runProcess("javac test2.java");
//thread foo=new thread();
runProcess("java mainclasses.emaildownload "+credentials[0]+" "+credentials[1]+" "+credentials[2]+" "+credentials[3]+" ");
} catch (Exception e) {
e.printStackTrace();
}System.out.println("hI");
}
I am giving the location of class by using workingDir...and my file path is:
C:\Users\HP\Downloads\apache-tomcat-7.0.54-windows-x64\apache-tomcat-7.0.54\webapps\Mazil4.0\WEB-INF\classes\mainclasses\emaildownload.class
package name is mainclasses.but it still gives error:
could not find or load main class mainclasses.emaildownload
whay could possibly be the reason?
IN this line:
public static void mai(String[] args) {
is an 'n' missing.
Change to
public static void main(String[] args) {
I belive command should look like:
java -cp <path-to-jar> <main-class>
Providing that:
main class you whish to load: mainclasses.emaildownload
(class emaildownload in package mainclasses)
patch to jar containing given
main class:
C:\Users\HP\Downloads\apache-tomcat-7.0.54-windows-x64\apache-tomcat-7.0.54\webapps\Mazil4.0\WEB-INF\classes\
command should look like:
java -cp C:\Users\HP\Downloads\apache-tomcat-7.0.54-windows-x64\apache-tomcat-7.0.54\webapps\Mazil4.0\WEB-INF\classes\<jar-file> mainclasses.emaildownload
or you can use wildcard:
java -cp "C:\Users\HP\Downloads\apache-tomcat-7.0.54-windows-x64\apache-tomcat-7.0.54\webapps\Mazil4.0\WEB-INF\classes\*" mainclasses.emaildownload

File Structured Error [duplicate]

This question already has an answer here:
StreamCorruptedException: invalid type code: AC
(1 answer)
Closed 5 years ago.
sorry to bother you, once again I need help on the Java language , more precisely on the file structured as the title .
The error in question is that after you have stored more than once , I read reports an error (of course putting in append mode) , and does so even if I do all in the main program ...
My program consists of three classes in three files:
Alluno.java:
import java.io.Serializable;
class Alunno implements Serializable {
private String nome, cognome, data_nascita, indirizzo, residenza, telefono;
public Alunno() {
nome = ""; cognome = ""; data_nascita = ""; indirizzo = ""; residenza = ""; telefono = "";
}
public void setNome(String nome) {
this.nome = nome;
}
void setCognome(String cognome) {
this.cognome = cognome;
}
void setData_Nascita(String data_nascita) {
this.data_nascita = data_nascita;
}
void setIndirizzo(String indirizzo) {
this.indirizzo = indirizzo;
}
void setResidenza(String residenza) {
this.residenza = residenza;
}
void setTelefono(String telefono) {
this.telefono = telefono;
}
}
File.java:
import java.io.*;
class File {
private int dim;
public Alunno nuovoAlunno() throws IOException {
BufferedReader t = new BufferedReader(new InputStreamReader(System.in));
Alunno a = new Alunno();
System.out.println("***Inserimento nuovo alunno***");
System.out.format("Nome: ");
a.setNome(t.readLine());
System.out.format("Cognome: ");
a.setCognome(t.readLine());
System.out.format("Data di nascita: ");
a.setData_Nascita(t.readLine());
System.out.format("Indirizzo: ");
a.setIndirizzo(t.readLine());
System.out.format("Residenza: ");
a.setResidenza(t.readLine());
System.out.format("Telefono: ");
a.setTelefono(t.readLine());
return a;
}
public void sciviFile(Alunno a) {
try {
FileOutputStream f = new FileOutputStream("istituto.dat", true);
ObjectOutputStream fOUT = new ObjectOutputStream(f);
fOUT.writeObject(a);
fOUT.flush();
fOUT.close();
} catch (Exception e) {
System.out.println("Eccezione scrittura: " + e.getMessage());
}
}
public void leggiFile() {
Alunno a;
try {
FileInputStream f = new FileInputStream("istituto.dat");
ObjectInputStream fIN = new ObjectInputStream(f);
while (true) {
try {
a = (Alunno) fIN.readObject();
dim++;
System.out.println("Dimensione file: " + dim);
} catch (EOFException e) {
break;
}
}
f.close();
} catch (Exception e) {
System.out.println("Eccezione lettura: " + e.getMessage());
}
}
}
IstitutoScolastico.java:
import java.io.*;
public class IstitutoScolastico {
public static void main(String[] args) throws IOException {
File f = new File();
//f.sciviFile(f.nuovoAlunno());
f.leggiFile();
}
}
OUTPUT:
Dimensione file: 1
Eccezione lettura: invalid type code: AC
I do not read more than one object if I put in append mode, where did I go wrong?
Ah, anyway sorry for the grammatical errors, but I'm Italian and I helped with google translate!
The problem is that ObjectOutputStream writes a header to the file in it's constructor.
Since you call the constructor for each Alunno you append, you write a new header to the file too.
However ObjectInputStream expects only one header(at the start of the file).
If you don't want to change much in your code, you should create a new ObjectInputStream for each Alunno you read, change the code in your File class:
public void leggiFile() {
Alunno a;
try {
FileInputStream f = new FileInputStream("istituto.dat");
try {
while (true) {
// the header is read in the constructor
ObjectInputStream fIN = new ObjectInputStream(f);
a = (Alunno) fIN.readObject();
dim++;
System.out.println("Dimensione file: " + dim);
}
} catch (EOFException e) { }
f.close();
} catch (Exception e) {
System.out.println("Eccezione lettura: " + e.getMessage());
}
}
A alternative would be to skip 2(?) shorts (4(?) bytes) from the FileInputStream, but if the definition of the header should change (although this seems unlikely), you might have to change your code.
Another alternative would be to read all the Alunnos that are already in the file and then write all Alunnos (including the new one) to the File starting at the beginning of the file. But this may not be as fast as you wish.
For detailed information you can read http://docs.oracle.com/javase/7/docs/platform/serialization/spec/output.html and http://docs.oracle.com/javase/7/docs/platform/serialization/spec/input.html
One last tip: If you use Java SE 7 (or higher) consider using try-with-resources for your streams.

How can I tell wheter a file is opened by an other application?

Is there a way to tell whether a file is opened by another application in PHP of Java?
Command fuser -v filename will tell you everything you need to know:
$ fuser -v test.php
USER PID ACCESS COMMAND
test.php: guest 17983 F.... cat
I'd say No. Please read these threads.
How to check if a file is already open by another process in C?
Java: Check if file is already open
How to check if a file has been opened by another application in C++
On windows you could download handle which is a command line tool to identify which windows file handles are owned by which processes.
Output looks like this:
Handle v3.46
Copyright (C) 1997-2011 Mark Russinovich
Sysinternals - www.sysinternals.com
------------------------------------------------------------------------------
System pid: 4 NT AUTHORITY\SYSTEM
84: File (R--) C:\System Volume Information\_restore{5D536487-92AI-5I25-9237-28AHSOU23728}\RP425\change.log
B4: File (RWD) C:\Documents and Settings\All Users\Application Data\avg9\Log\avgldr.log
728: File (-W-) C:\pagefile.sys
7A4: File (---) C:\WINDOWS\system32\config\SECURITY
(etc...)
Here an example application which uses handle.exe to determine if there is a handle on a file or directory (Windows only):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Application which determines which processes have a handle on a file or
* directory. Pass the file or directory to check as the first application
* parameter.
*
* This application uses handle.exe, which can be downloaded here:
* http://technet.microsoft.com/en-us/sysinternals/bb896655
*
* Copy handle.exe to C:/Program Files/handle/
*
* For the Runtime.exec() code I looked at:
* http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=2
*
* #author Adriaan
*/
public class Handle {
private static final String HANDLE_PATH = "C:/Program Files/handle/handle.exe";
private static final String DEFAULT_TARGET = "C:\\WINDOWS";
public static void main(String[] args) throws IOException,
InterruptedException {
checkOS();
String fileName = getFileName(args);
Process proc = executeCommand(fileName);
readResults(fileName, proc);
checkTermination(proc);
}
private static void checkOS() {
String osName = System.getProperty("os.name");
if (!osName.contains("Windows")) {
throw new IllegalStateException("Can only run under Windows");
}
}
private static String getFileName(String[] args) {
String fileName;
if (args != null && args.length > 0) {
fileName = args[0];
} else {
fileName = DEFAULT_TARGET;
}
return fileName;
}
private static Process executeCommand(String fileName) throws IOException {
String[] cmd = new String[] { HANDLE_PATH, fileName };
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);
return proc;
}
private static void readResults(final String fileName, final Process proc) {
Thread errorHandler = new Thread() {
public void run() {
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(proc.getErrorStream()));
String line = null;
while ((line = br.readLine()) != null) {
System.err.println(line);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
};
Thread outputHandler = new Thread() {
public void run() {
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
String line = null;
while ((line = br.readLine()) != null) {
if (line.endsWith(fileName)) {
System.out.println(line);
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
};
errorHandler.start();
outputHandler.start();
}
private static void checkTermination(final Process proc)
throws InterruptedException {
int exitVal = proc.waitFor();
if (exitVal != 0) {
throw new IllegalStateException("Exitvalue " + exitVal);
}
}
}
You probably want to use file locking.
http://tuxradar.com/practicalphp/8/11/0
Edit: This is presuming you mean programatically with PHP or Java.
On linux you can scan through all the /proc/{pid}/fd/nnn file descriptors to see if the file in question is already open.
Using files to share data between running programs is generally a bad idea and error prone.

Execute another jar in a Java program

I had written several simple java applications named as A.jar, B.jar.
Now i want to write a GUI java program so that user can press button A to execute A.jar and button B to execute B.jar.
Also i want to output the run-time process detail in my GUI program.
Any suggestion?
If I understand correctly it appears you want to run the jars in a separate process from inside your java GUI application.
To do this you can use:
// Run a java app in a separate system process
Process proc = Runtime.getRuntime().exec("java -jar A.jar");
// Then retreive the process output
InputStream in = proc.getInputStream();
InputStream err = proc.getErrorStream();
Its always good practice to buffer the output of the process.
.jar isn't executable. Instantiate classes or make call to any static method.
EDIT:
Add Main-Class entry while creating a JAR.
>p.mf (content of p.mf)
Main-Class: pk.Test
>Test.java
package pk;
public class Test{
public static void main(String []args){
System.out.println("Hello from Test");
}
}
Use Process class and it's methods,
public class Exec
{
public static void main(String []args) throws Exception
{
Process ps=Runtime.getRuntime().exec(new String[]{"java","-jar","A.jar"});
ps.waitFor();
java.io.InputStream is=ps.getInputStream();
byte b[]=new byte[is.available()];
is.read(b,0,b.length);
System.out.println(new String(b));
}
}
Hope this helps:
public class JarExecutor {
private BufferedReader error;
private BufferedReader op;
private int exitVal;
public void executeJar(String jarFilePath, List<String> args) throws JarExecutorException {
// Create run arguments for the
final List<String> actualArgs = new ArrayList<String>();
actualArgs.add(0, "java");
actualArgs.add(1, "-jar");
actualArgs.add(2, jarFilePath);
actualArgs.addAll(args);
try {
final Runtime re = Runtime.getRuntime();
//final Process command = re.exec(cmdString, args.toArray(new String[0]));
final Process command = re.exec(actualArgs.toArray(new String[0]));
this.error = new BufferedReader(new InputStreamReader(command.getErrorStream()));
this.op = new BufferedReader(new InputStreamReader(command.getInputStream()));
// Wait for the application to Finish
command.waitFor();
this.exitVal = command.exitValue();
if (this.exitVal != 0) {
throw new IOException("Failed to execure jar, " + this.getExecutionLog());
}
} catch (final IOException | InterruptedException e) {
throw new JarExecutorException(e);
}
}
public String getExecutionLog() {
String error = "";
String line;
try {
while((line = this.error.readLine()) != null) {
error = error + "\n" + line;
}
} catch (final IOException e) {
}
String output = "";
try {
while((line = this.op.readLine()) != null) {
output = output + "\n" + line;
}
} catch (final IOException e) {
}
try {
this.error.close();
this.op.close();
} catch (final IOException e) {
}
return "exitVal: " + this.exitVal + ", error: " + error + ", output: " + output;
}
}
The following works by starting the jar with a batch file, in case the program runs as a stand alone:
public static void startExtJarProgram(){
String extJar = Paths.get("C:\\absolute\\path\\to\\batchfile.bat").toString();
ProcessBuilder processBuilder = new ProcessBuilder(extJar);
processBuilder.redirectError(new File(Paths.get("C:\\path\\to\\JavaProcessOutput\\extJar_out_put.txt").toString()));
processBuilder.redirectInput();
try {
final Process process = processBuilder.start();
try {
final int exitStatus = process.waitFor();
if(exitStatus==0){
System.out.println("External Jar Started Successfully.");
System.exit(0); //or whatever suits
}else{
System.out.println("There was an error starting external Jar. Perhaps path issues. Use exit code "+exitStatus+" for details.");
System.out.println("Check also C:\\path\\to\\JavaProcessOutput\\extJar_out_put.txt file for additional details.");
System.exit(1);//whatever
}
} catch (InterruptedException ex) {
System.out.println("InterruptedException: "+ex.getMessage());
}
} catch (IOException ex) {
System.out.println("IOException. Faild to start process. Reason: "+ex.getMessage());
}
System.out.println("Process Terminated.");
System.exit(0);
}
In the batchfile.bat then we can say:
#echo off
start /min C:\path\to\jarprogram.jar
If the jar's in your classpath, and you know its Main class, you can just invoke the main class. Using DITA-OT as an example:
import org.dita.dost.invoker.CommandLineInvoker;
....
CommandLineInvoker.main('-f', 'html5', '-i', 'samples/sequence.ditamap', '-o', 'test')
Note this will make the subordinate jar share memory space and a classpath with your jar, with all the potential for interference that can cause. If you don't want that stuff polluted, you have other options, as mentioned above - namely:
create a new ClassLoader with the jar in it. This is more safe; you can at least isolate the new jar's knowledge to a core classloader if you architect things with the knowledge that you'll be making use of alien jars. It's what we do in my shop for our plugins system; the main application is a tiny shell with a ClassLoader factory, a copy of the API, and knowledge that the real application is the first plugin for which it should build a ClassLoader. Plugins are a pair of jars - interface and implementation - that are zipped up together. The ClassLoaders all share all the interfaces, while each ClassLoader only has knowledge of its own implementation. The stack's a little complex, but it passes all tests and works beautifully.
use Runtime.getRuntime.exec(...) (which wholly isolates the jar, but has the normal "find the application", "escape your strings right", "platform-specific WTF", and "OMG System Threads" pitfalls of running system commands.
First we cerate a class FirstFileOutput having a main method that outputs a line to stable output and a line to stable error. With all first procedure, we'll again create a class RuntimeExecCheck that will run our FirstFileOutput class in starting for process, and after that RuntimeExecCheck class will read the stable output and the stable error from FirstFileOutput and output comes.
package check;
public class FirstFileOutput{
public static void main(String[] args) {
System.out.println("This is output to stable output");
System.err.println("This is output to stable error");
}
}
package check;
import java.io.InputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class RuntimeExecCheck {
public static void main(String[] args) {
try {
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec("java -classpath C:\\projects\\workspace\\check\\bin check.FirstFileOutput");
InputStream inputStream = process.getInputStream();
InputStreamReader isr = new InputStreamReader(inputStream);
InputStream errorStream = process.getErrorStream();
InputStreamReader esr = new InputStreamReader(errorStream);
int n1;
char[] c1 = new char[1024];
StringBuffer stableOutput = new StringBuffer();
while ((n1 = isr.read(c1)) > 0) {
stableOutput.append(c1, 0, n1);
}
System.out.println("Stable Output: " + stableOutput.toString());
int n2;
char[] c2 = new char[1024];
StringBuffer stableError = new StringBuffer();
while ((n2 = esr.read(c2)) > 0) {
stableError.append(c2, 0, n2);
}
System.out.println("Stable Error: " + stableError.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
If you are java 1.6 then the following can also be done:
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
public class CompilerExample {
public static void main(String[] args) {
String fileToCompile = "/Users/rupas/VolatileExample.java";
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int compilationResult = compiler.run(null, null, null, fileToCompile);
if (compilationResult == 0) {
System.out.println("Compilation is successful");
} else {
System.out.println("Compilation Failed");
}
}
}

Categories

Resources