How can I fix problems while running .exe file - java

I have a ThMapInfratab1-2.exefile under C:\Users\Infratab Bangalore\Desktop\Rod directory. I executed in command prompt in the following way.it's working fine.
C:\Users\Infratab Bangalore\Desktop\Rod>ThMapInfratab1-2.exe TMapInput.txt
I want to do same procedure using Java technology. using StackOverFlow guys,I tried in 2 ways.
Case 1:
Using getRuntime().
import java.util.*;
import java.io.*;
public class ExeProcess
{
public static void main(String args[]) throws IOException
{
Runtime rt = Runtime.getRuntime();
File filePath=new File("C:/Users/Infratab Bangalore/Desktop/Rod");
String[] argument1 = {"TMapInput.txt"};
Process proc = rt.exec("ThMapInfratab1-2.exe", argument1, filePath);
}
}
Case 2:
Using ProcessBuilder
import java.io.File;
import java.io.IOException;
public class ProcessBuilderSample {
public static void main(String args[]) throws IOException
{
String executable = "ThMapInfratab1-2.exe";
String argument1 = "TherInput.txt";
File workingDirectory = new File("C:/Users/Infratab Bangalore/Desktop/Rod");
ProcessBuilder pb = new ProcessBuilder(executable, argument1);
pb.directory(workingDirectory);
pb.start();
}
}
in both cases, I am getting the following error.
Error:
Exception in thread "main" java.io.IOException: Cannot run program "ThMapInfratab1-2.exe" (in directory "C:\Users\Infratab Bangalore\Desktop\Rod"): CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(Unknown Source)
at ProcessBuilderSample.main(ProcessBuilderSample.java:16)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
... 2 more
I did't figure out, what's the problem. can anyone suggest me.
I am using jre 7.
Thanks

try to use this :
import java.io.File;
import java.io.IOException;
public class ProcessBuilderSample {
public static void main(String args[]) throws IOException
{
String executable = "ThMapInfratab1-2.exe";
String argument1 = "TherInput.txt";
File workingDirectory = new File("C:/Users/Infratab Bangalore/Desktop/Rod");
ProcessBuilder pb = new ProcessBuilder("cmd", "/c","start" ,executable, argument1);
pb.directory(workingDirectory);
pb.start();
}
}

The statement
pb.directory(workingDirectory);
specifies only the working directory. This is not the directory where the executable ThMapInfratab1-2.exe is to be searched for. But it is the directory where the file you specify as argument TMapInput.txt is to be searched for. Since TMapInput.txt is not an absolute path, your programm will then search for that file relativly to the working directory.
To solve you problem you need to specify the full path for the excecutable:
String executable = "C:\\Users\\Infratab Bangalore\\Desktop\\Rod\\ThMapInfratab1-2.exe";
String argument1 = "TherInput.txt";
File workingDirectory = new File("C:\\Users\\Infratab Bangalore\\Desktop\\Rod");
Or if you do not need to the location C:\Users\Infratab Bangalore\Desktop\Rod just pass the absolute path of the file too and remove the statement pb.directory(workingDirectory);:
String executable = "C:\\Users\\Infratab Bangalore\\Desktop\\Rod\\ThMapInfratab1-2.exe";
String argument1 = "C:\\Users\\Infratab Bangalore\\Desktop\\Rod\\TherInput.txt";
Alternatively you could extend your PATH environment variable to include the location C:\Users\Infratab Bangalore\Desktop\Rod. In this case the programm will run just fine as you posted it.

Related

is it possible to read the downloaded file from chrome browser using selenium

I downloaded a text file by a click button functionality, using Selenium Java.
then the file is downloaded to a particular location in the system, for example,
C://myAppfiles.
But I can't access that downloaded folder because of some reason. But I have to read that file while downloading.
How to do it? is it possible to read that file from the browser(chrome) using selenium or any other method is available?
so I'd suggest to do the following:
wait until file download is done completely.
After that- try to list all the files in the given directory:
all files inside folder and sub-folder
public static void main(String[]args)
{
File curDir = new File(".");
getAllFiles(curDir);
}
private static void getAllFiles(File curDir) {
File[] filesList = curDir.listFiles();
for(File f : filesList){
if(f.isDirectory())
getAllFiles(f);
if(f.isFile()){
System.out.println(f.getName());
}
}
}
files/folder only
public static void main(String[]args)
{
File curDir = new File(".");
getAllFiles(curDir);
}
private static void getAllFiles(File curDir) {
File[] filesList = curDir.listFiles();
for(File f : filesList){
if(f.isDirectory())
System.out.println(f.getName());
if(f.isFile()){
System.out.println(f.getName());
}
}
}
That will help You to understand if there any files at all (in the given directory).
Dont forget to make paths platform independent (to the folder/ file), like:
//platform independent and safe to use across Unix and Windows
File fileSafe = new File("tmp"+File.separator+"myDownloadedFile.txt");
Also, You might want to check whether file actually exists via Path methods.
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) throws Exception {
Path filePath= Paths.get("C:\\myAppfiles\\downloaded.txt");
System.out.println("if exists: " + Files.exists(firstPath));
}
}
Additionally, path suggests You to check some other options on the file:
The following code snippet verifies that a particular file exists and that the program has the ability to execute the file.
Path file = ...;
boolean isRegularExecutableFile = Files.isRegularFile(file) &
Files.isReadable(file) & Files.isExecutable(file);
Once You face any exception- feel free to post it here.
Hope this helps You

Jackson writeValue() to file not working with relative path

I'm trying to write an object to json file by jackson.
If i provide an absolute path "D:/Projects/quiz-red/src/main/resources/com/models/Quizzes.json" it's working and file appears in the directory
But if i provide a relative path - "/com/models/Quizzes.json" i'm just getting Process finished with exit code 0 in console and nothing happens. What am I doing wrong?
There is my code:
public static void writeEntityToJson(Object jsonDataObject, String path) throws IOException {
ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());
writer.writeValue(new File(path), jsonDataObject);
}
public static void main(String[] args) throws IOException {
Quiz quiz = new Quiz(5L, "Title", "Short desc");
writeEntityToJson(quiz, "/com/models/Quizzes2.json");
}
I want to save a file to resources from DataProvider using relative path
Exception:
Exception in thread "main" java.io.FileNotFoundException: com\models\Quizzes5.json (The system cannot find the path specified)
at java.base/java.io.FileOutputStream.open0(Native Method)
at java.base/java.io.FileOutputStream.open(FileOutputStream.java:298)
at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:237)
at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:187)
at com.fasterxml.jackson.core.JsonFactory.createGenerator(JsonFactory.java:1223)
at com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:942)
at com.utils.DataProvider.writeEntityToJson(DataProvider.java:33)
at com.utils.DataProvider.main(DataProvider.java:50)

ImportError: No Module named demiso in Jython

I'm new to the Jython and I'm trying to run a python class using Jython in Java. But I'm running into some issues.
The Java class that I've defined:
public class DemistoCalls {
PythonInterpreter interpreter = null;
public DemistoCalls()
{
PythonInterpreter.initialize(System.getProperties(),
System.getProperties(), new String[0]);
this.interpreter = new PythonInterpreter();
}
void execfile( final String fileName )
{
this.interpreter.execfile(fileName);
}
PyInstance createClass( final String className, final String opts )
{
return (PyInstance) this.interpreter.eval(className + "(" + opts + ")");
}
public static void main(String[] args) {
DemistoCalls demistoCalls = new DemistoCalls();
demistoCalls.execfile("C:\\Users\\AlokNath\\Desktop\\Demisto_Project\\demisto-py-master\\demisto\\SimpleConnect.py");
}
}
The SampleConnect.py file that I'm trying to run:
import sys
sys.path.append("C:\Users\AlokNath\Desktop\Demisto_Project\demisto-py-
master\demisto")
import demisto
While Running the java file, I'm getting this error:
File "C:\Users\AlokNath\Desktop\Demisto_Project\demisto-py-master\demisto\SimpleConnect.py", line 3, in <module>
import demisto
ImportError: No module named demisto
Although I've defined the "demisto" module in the system path and checked that the system path in python contains the appropriate path to Jython 2.7.lb2 Library. I'm not sure where am I going wrong. Any help is appreciated.
Regards,
Alok
I found a solution to the import error problem. We need to copy the missing module to the “site-packages” folder under "modeler-installation/lib/jython/Lib". This will resolve the dependency problem.

Project throwing IOException (File Not Found) when jar is run

I've made a project in java, using Eclipse.
Here is the project structure:
When I'm running the project in Eclipse as a java application, it runs perfectly fine.
Now, I need to export it as a jar. So, I created the jar using the method described in 3rd answer on this link (answered by Fever):
Failing to run jar file from command line: “no main manifest attribute”
Here is the output of jar tf EventLogger.jar:
META-INF/MANIFEST.MF
com/
com/project/
com/project/eventLogger/
com/project/eventLogger/KafkaConsumerGroup.class
com/project/eventLogger/KafkaProducer.class
com/project/eventLogger/ConsumeConfig.class
com/project/eventLogger/ConsumerThread.class
com/project/eventLogger/Formatter.class
com/project/eventLogger/Execute.class
com/project/eventLogger/Config.class
com/project/eventLogger/package-info.class
com/project/eventLogger/ProdConfig.class
com/project/eventLogger/FormatConfig.class
resources/
resources/Config.properties
resources/ConsumerConfig.properties
resources/FormatterConfig.properties
resources/ProducerConfig.properties
resources/log4j.properties
Here is the manifest file:
Manifest-Version: 1.0
Built-By: vishrant
Class-Path: lib/json-simple-1.1.1.jar lib/junit-4.10.jar lib/hamcrest-
core-1.1.jar lib/kafka_2.9.2-0.8.2.2.jar lib/jopt-simple-3.2.jar lib/
kafka-clients-0.8.2.2.jar lib/log4j-1.2.16.jar lib/lz4-1.2.0.jar lib/
metrics-core-2.2.0.jar lib/slf4j-api-1.7.6.jar lib/snappy-java-1.1.1.
7.jar lib/slf4j-log4j12-1.6.1.jar lib/zkclient-0.3.jar lib/zookeeper-
3.4.6.jar lib/jline-0.9.94.jar lib/netty-3.7.0.Final.jar lib/scala-li
brary-2.9.2-RC3.jar
Build-Jdk: 1.8.0_74
Created-By: Maven Integration for Eclipse
Main-Class: com.project.eventLogger.Execute
and, here is the exception:
java.io.FileNotFoundException: ConsumerConfig.properties (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at com.project.eventLogger.ConsumeConfig.loadPropertiesFile(ConsumeConfig.java:34)
at com.project.eventLogger.ConsumeConfig.<clinit>(ConsumeConfig.java:42)
at com.project.eventLogger.Execute.main(Execute.java:18)
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.project.eventLogger.Execute.main(Execute.java:18)
Caused by: java.lang.NullPointerException
at com.project.eventLogger.ConsumeConfig.<clinit>(ConsumeConfig.java:47)
... 1 more
Seeing the exception, it is clear that it is not able to load ConsumerConfig.properties which is being done in ConsumeConfig.java.
Here is ConsumeConfig.java:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Properties;
/**
* #author vishrant
*
*/
public class ConsumeConfig {
public static String zookeeper;
public static String balance;
public static String bootstrap_servers;
public static String zk_session_to;
public static String zk_sync;
public static String auto_commit;
public static String[] topics;
private static String kafka_bin;
private static final String PROPERTIES_FILE_PATH = "src/main/resources/ConsumerConfig.properties";
private static Properties loadPropertiesFile() throws IOException {
Properties properties = new Properties();
InputStream in = new FileInputStream(PROPERTIES_FILE_PATH);
properties.load(in);
return properties;
}
static {
Properties property = null;
try {
property = loadPropertiesFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
zookeeper = property.getProperty("ZOOKEEPER");
balance = property.getProperty("BALANCE");
bootstrap_servers = property.getProperty("BOOTSTRAP_SERVERS");
zk_session_to = property.getProperty("ZK_SESSION_TO");
zk_sync = property.getProperty("ZK_SYNC_TIME");
auto_commit = property.getProperty("AUTO_COMMIT_INTERVAL");
topics = property.getProperty("CONSUMER_TOPICS").split(",");
kafka_bin = property.getProperty("KAFKA_BIN_PATH");
}
}
Can someone tell me what is the problem and how to resolve this?
This runs perfectly well when run in Eclipse itself.
EDIT1:
Now, the exception is:
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.project.eventLogger.Execute.main(Execute.java:18)
Caused by: java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:434)
at java.util.Properties.load0(Properties.java:353)
at java.util.Properties.load(Properties.java:341)
at com.project.eventLogger.ConsumeConfig.loadPropertiesFile(ConsumeConfig.java:35)
at com.project.eventLogger.ConsumeConfig.<clinit> (ConsumeConfig.java:42)
... 1 more
line no 35:
props.load(resourceStream);
This is the code now:
private static final String PROPERTIES_FILE_PATH = "ConsumerConfig.properties";
private static Properties loadPropertiesFile() throws IOException {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Properties props = new Properties();
InputStream resourceStream = loader.getResourceAsStream(PROPERTIES_FILE_PATH);
props.load(resourceStream);
return props;
}
I see the following problems to be the cause:
The jar file is not created correctly for a maven project because the directory resources will normally be not copied to the target directory as is, i.e., instead of
resources/Config.properties
it should look like without the resources directory:
Config.properties
directly under the root directory of the jar file.
The second point is you are using the following in your code
private static final String PROPERTIES_FILE_PATH = "src/main/resources/ConsumerConfig.properties";
This path will not be seen outside of your IDE (in this case Eclipse) because src/main/resources should not exist in the jar file as you could see in the list of your jar file.
The last point is, you should use getResourceAsStream() of the class loader as Vikrant Kashyap already pointed.
try this
// Change Your File Path First.
private static final String PROPERTIES_FILE_PATH = "ConsumerConfig.properties";
private static Properties loadPropertiesFile() throws IOException {
Properties properties = new Properties();
// First way to load ResourceAsStream.
// ClassLoader loader = Thread.currentThread().getContextClassLoader();
// InputStream resourceStream = loader.getResourceAsStream(PROPERTIES_FILE_PATH);
// Second way to load ResourceAsStream.
InputStream resourceStream = ConsumeConfig.class.getResourceAsStream(PROPERTIES_FILE_PATH);
properties.load(resourceStream);
return properties;
}

Why can't java find my class?

I have a class that compiles without error. The class has a main method. But when I try to run it on ubuntu linux from the classes' directory I get a class not found error. I am pretty sure I am missing something dead obvious but I don't see it.
Here is my ls operation:
zookeeper#zookeeper-virtual-machine:~/zookeeper-3.4.5/programs$ ls
CreateGroup.java LsGroup.class LsGroup.java zookeeper-3.4.5.jar
Here is what happens when I to run LsGroup
zookeeper#zookeeper-virtual-machine:~/zookeeper-3.4.5/programs$ java -cp "zookeeper-3.4.5.jar" LsGroup
Exception in thread "main" java.lang.NoClassDefFoundError: LsGroup
Caused by: java.lang.ClassNotFoundException: LsGroup
at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
Could not find the main class: LsGroup. Program will exit.
Here is the code for LsGroup
package org.zookeeper;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.KeeperState;
public class LsGroup implements Watcher {
private static final int SESSION_TIMEOUT = 5000;
private ZooKeeper zk;
private CountDownLatch connectedSignal = new CountDownLatch(1);
public void connect(String hosts) throws IOException, InterruptedException {
zk = new ZooKeeper(hosts, SESSION_TIMEOUT, this);
connectedSignal.await();
}
#Override
public void process(WatchedEvent event) { // Watcher interface
if (event.getState() == KeeperState.SyncConnected) {
connectedSignal.countDown();
}
}
public void ls(String groupName) throws KeeperException, InterruptedException {
String path = "/" + groupName;
try {
List<String> children = zk.getChildren(path, false);
for (String child : children) {
System.out.println(path+"/"+child);
System.out.println(zk.getChildren(path +"/"+ child, false));
}
} catch (KeeperException.NoNodeException e) {
System.out.printf("Group %s does not exist\n", groupName);
System.exit(1);
}
}
public void close() throws InterruptedException {
zk.close();
}
public static void main(String[] args) throws Exception {
LsGroup lsGroup = new LsGroup();
lsGroup.connect(args[0]);
lsGroup.ls(args[1]);
lsGroup.close();
}
}
The original problem was that your class was in a package, but you were trying to load it as if it weren't in a package. You'd normally organize your source code to match your package hierarchy, then from the root of the hierarchy, you'd run something like:
java -cp .:zookeeper-3.4.5.jar org.zookeeper.LsGroup
Now that you've temporarily worked around the package issue by moving the code out of a package, the next problem is that the current directory isn't in the classpath. So instead of this:
java -cp "zookeeper-3.4.5.jar" LsGroup
You want:
java -cp .:zookeeper-3.4.5.jar LsGroup
Once you've got that working, you should move the classes back into packages, as per normal Java best practice.
You could remove the package declaration:
package org.zookeeper;
...or just place your LsGroup class in org/zookeeper directory.
The class file is supposed to live in a path like:
org/zookeeper/LsGroup.class
The -cp must include the directory that contains the org/ directory. Then you can
java -cp parent-of-org org.zookeeper.LsGroup
The message "wrong name: org/zookeeper/LsGroup" means, you have to respect the package structure of Java. Use the following directory structure:
./org/zookeeper/LsGroup.class
Then launch java org.zookeeper.LsGroup from within the current directory. The package separator "." will be translated to corresponding directory.
Your files are not under package org.zookeeper
You should be running your class from ~/zookeeper-3.4.5/org/zookeeper
Otherwise JVM won't find the classes to load.
Your class is part of the org.zookeeper package but you keep it in the root folder of your project (/zookeeper-3.4.5/programs).
The qualified name of the package member and the path name to the file are parallel (see Managing Source and Class Files), so if your package is org.zookeeper the class file should be kept in /zookeeper-3.4.5/programs/org/zookeeper
You made two mistakes:
1) You tried to run java LsGroup but you have to use the complete name including packages java org.zookeeper.LsGroup
2) your directory structure is not correct: the package org.zookeeper corresponds with the directory structure ./org/zookeeper/
If you change the directory structure and then run java from the top of this directory structure it should work

Categories

Resources