Getting process Details in windows using Java - java

In windows OS. using tasklist ( getting list of current open process ) i have collected list of running process. But how to get actual path of executable file of that process [FILE LOCATION]?
Is there any way to find recently used process from java?

do you mean something like this
import java.io.*;
public class taskmanager {
public static void main(String[] args) throws IOException {
String line;
Process p = Runtime.getRuntime().exec("tasklist.exe");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line); //<-- Parse data here.
// new lines from here
String searchPath = "where notepad.exe";
searchProcessPath(searchPath);
}
input.close();
}
public static void searchProcessPath(String processName) throws IOException
{
Runtime.getRuntime().exec(processName);
}
}

Related

Junit test by passing file path string and IOException handling inside private method

I have a private method called from the main() method to which I am passing the input file path as an argument. My code-under-test is the main() method. Somewhere in the middle of the private method, the file is read and some operations performed.
How can I:
1. Pass the file path of String type ("src/test/resources/test.txt") as an argument. I am getting FileNotFoundException if I pass the file path.
2. How can I test an IOException that is handled in private method on not finding the file?
Adding my code snippets here:
Code under Test:
public class MyApp {
public static void main(String[] args) {
new MyApp().readFile(args);
}
private void readFile(String[] args) {
if (args != null) {
String file = args[0];
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
// More business logic here for processing that line
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
Test for main:
#Test
void mainTest() {
String[] args = {"/test_input.txt"};
MyApp.main(args);
assertNotNull(<some_object_after_processing>);
}
To get file path you can use suitable way mentation in this link
There is no need to check any assertion for main method.
If the test case is completed successfully then it passed.
Thank you for raising your queries! First, you need to change your application code because you are reading a single file from the args[0] position then why you are going to read the strings array [File Array or collection of files].
1] Create 'resources' folder in your project:
Right-click on project and create a folder with name 'resources'.
2] Create 'test.txt' into the 'resources' folder.
3] Modified code:
package com.application;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class MyApp {
public static void main(String[] args) {
new MyApp().readFile("resources/Test.txt");
}
private void readFile(String fileName) {
if (fileName != null) {
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
// More business logic here for processing that line
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
Here, You can pass a fileName directly to the method. I hope that it will help you to resolve your first query.

FileWriter / BufferedReader Java word finder

I have this code set up and I am trying to write a program that looks through a file and finds a specific hidden secret word then replaces the word with "found!" then re-prints the text file in the console. I know how to use reader and writer but I am unsure how i can use them in unison to do this. Code is as follows:
Reader Class:
package Main;
import java.io.*;
public class Read {
private static String line;
FileReader in;
File file;
public Read() {
line = "";
}
public void readFile() throws IOException {
file = new File("C:examplePathName\\ReadWriteExp.txt");
in = new FileReader(file);
BufferedReader br = new BufferedReader(in);
while((line = br.readLine()) != null) {
System.out.println(line);
}
in.close();
}
public String getLine() {
return line;
}
public File getFile() {
return file;
}
}
Writer(change) class:
package Main;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class Change {
public static void main(String[] args) throws IOException{
Read r = new Read();
String line = r.getLine();
FileWriter fw = new FileWriter(r.getFile());
while(line != null) {
if(line.equals("example")) {
fw.write("found!");
}
System.out.println(line);
}
}
}
Am i on the right path or should i combine both of these into one class. Also is this the proper way of writing to a specific line in a text file?
If the file is a reasonable size, you can read it into memory, change what you need and write it back out again:
public static void replaceOccurrences(String match, String replacement, Path path) throws IOException {
Files.write(path, Files.lines(path).map(l -> {
if(l.contains(match)) {
return l.replace(match, replacement);
} else {
return l;
}
}).collect(Collectors.toList()));
}
Alternatively, if you know that the search term occurs only once and you just need to find the position of the occurrence, use the following:
try(BufferedReader reader = Files.newBufferedReader(path)) {
int lineIndex = 0;
String line;
while(!(line = reader.readLine()).contains(match)) {
lineIndex++;
}
System.out.println(lineIndex); // line which contains match, 0-indexed
System.out.println(line.indexOf(match)); // starting position of match in line, 0-indexed
}
If all you have to do is print the converted text to system out (rather than writing it out to a file), the second class isn't really needed. You can accomplish what you need in the readFile() method of the Read class:
public void readFile() throws IOException {
file = new File("C:examplePathName\\ReadWriteExp.txt");
in = new FileReader(file);
BufferedReader br = new BufferedReader(in);
while((line = br.readLine()) != null) {
System.out.println(line.replaceAll("example", "found!"));
}
in.close();
}
There are a lot of other tweaks you could make, but that's the core of the functionality you specified in your question.

which is the equivalent command for execute a curl command in windows java?

An equivalent command for something like this I don't know which is the correct form to call a batch command
def proc =["/bin/sh", "-c","curl https://stackoverflow.com"]
proc.waitFor()
StringBuffer outputStream = new StringBuffer()
proc.waitForProcessOutput(outputStream, System.err)
String output = outputStream.toString()
Why don't you consider using java.net.URL instead?
Sample code is here
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Hello{
public static void main(String []args){
try
{
URL url = new URL("http://stackoverflow.com");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"))) {
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
}
}
}
catch (Exception e)
{
System.out.println("error occured");
}
}
}
instead if you want to invoke the curl command from java use the below
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class ShellFromJava {
public static ArrayList<String> command(final String cmdline,
final String directory) {
try {
Process process =
new ProcessBuilder(new String[] {"bash", "-c", cmdline})
.redirectErrorStream(true)
.directory(new File(directory))
.start();
ArrayList<String> output = new ArrayList<String>();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ( (line = br.readLine()) != null )
output.add(line);
if (0 != process.waitFor())
return null;
return output;
} catch (Exception e) {
//Warning: doing this is no good in high-quality applications.
//Instead, present appropriate error messages to the user.
//But it's perfectly fine for prototyping.
return null;
}
}
public static void main(String[] args) {
testHandler("curl http://stackoverflow.com");
}
static void testHandler(String cmdline) {
ArrayList<String> output = command(cmdline, ".");
if (null == output)
System.out.println("\n\n\t\tCOMMAND FAILED: " + cmdline);
else
for (String line : output)
System.out.println(line);
}
}
You can spawn a process from Java:
public class useProcess {
public static void main(String[] args) throws Exception {
String params[] = {"/bin/sh", "-c", "curl", "https://stackoverflow.com"};
Process myProcess = Runtime.getRuntime().exec(params);
myProcess.waitFor();
}
}

compile java in a different path from java

it's probably a stupid question but i need help.(i tried to solved it myself for 3 hours , so please do not block me)
i'm trying to compile java files in a different directory.
i'm getting a folder with some .java files and i need to compile them.
with:
public boolean complie() throws Exception{
Process pro = Runtime.getRuntime().exec("javac -cp "+location+"/*.java");
String line = null;
BufferedReader in = new BufferedReader(
new InputStreamReader(pro.getErrorStream()));
while ((line = in.readLine()) != null) {
System.out.println(name + " " + line);
}
}
but i'm getting errors.
the errors are point to the usage of other class in the folder. (error: cannot find symbol)
when i'm trying to compile in the CMD after navigating to the folder with "javac *.java", there is no errors.
please help me!
update:
i have trid:
File pathToExecutable = new File(location );
ProcessBuilder builder = new ProcessBuilder( pathToExecutable.getAbsolutePath(),"javac *.java");
builder.directory( new File( location ).getAbsoluteFile() ); // this is where you set the root folder for the executable to run with
builder.redirectErrorStream(true);
Process process = builder.start();
Scanner s = new Scanner(process.getInputStream());
StringBuilder text = new StringBuilder();
while (s.hasNextLine()) {
text.append(s.nextLine());
text.append("\n");
}
s.close();
but getting CreateProcess error=5, Access is denied error (i'm running my IDE as administrator)
One, see this: link ... (I believe that your executing a folder and not a commnad at the example given by you)
Two, ProcessBuilder should be called like this:
String classpath = "somePath" + File.pathSeparator + "otherpath";
ProcessBuilder builder = new ProcessBuilder("javac", "-cp " + classpath, "*.java");
builder.directory(new File(location));
This assuming that location contains the files .java that you want to compile...
UPDATE: This a little example that works for compiling and executing:
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
public class Compile {
public static void main(String[] args) throws IOException {
ProcessBuilder builder = new ProcessBuilder("javac", "hello/*.java");
builder.directory(new File("C:\\Users\\carlitos\\Desktop"));
Process pro = builder.start();
String line = null;
BufferedReader in = new BufferedReader(new InputStreamReader(pro.getErrorStream()));
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
// executing...
ProcessBuilder builder1 = new ProcessBuilder("java", "hello.Main", "carlitosWay");
builder1.directory(new File("C:\\Users\\carlitos\\Desktop"));
Process pro1 = builder1.start();
in = new BufferedReader(new InputStreamReader(pro1.getInputStream()));
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
}
}
And the main class:
package hello;
public class Main {
public static void main(String[] args) {
System.out.println("Hello: " + args[0]);
}
}
My example assumes that at "C:/Users/carlitos/Desktop", there is a folder called: "hello", and it contains the class "Main"...

Run Import database DOS command from Java

I am trying to run a database import command from a Java program like this:
public class Test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String[] str = {"imp ASKUL/askul#ASKDB file=askdbinstall.dmp log=askul.log fromuser=askul touser=ASKUL full=N ignore=Y grants=Y indexes=Y;"};
Process pro;
try {
pro = Runtime.getRuntime().exec(str);
} catch (Exception e) {
System.out.println(e);
}
}
}
The error Output is:
java.io.IOException: Cannot run program "imp ASKUL/askul#ASKDB file=askdbinstall.dmp log=askul.log fromuser=askul touser=ASKUL full=N ignore=Y grants=Y indexes=Y;": CreateProcess error=2, The system cannot find the file specified
The file askdbinstall.dmp is present because if I Paster the Same Command in CMD, it is importing the database Dump Quite fine. What is My Mistake?
Added:
From Reimius Suggestion I have also tried this:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
public class Tes {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try {
String [] cmd = {"imp", "ASKUL/askul#ASKDB file=askdbinstall.dmp",
"log=askul.log", "fromuser=askul", "touser=ASKUL",
"full=N ignore=Y grants=Y indexes=Y;"};
Process process = Runtime.getRuntime().exec(cmd);
InputStream in = process.getInputStream();
InputStreamReader ins=new InputStreamReader(in);
BufferedReader br = new BufferedReader(ins);
String data = null;
while ((data = br.readLine()) != null) {
System.out.println(data);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
Output
run:
BUILD SUCCESSFUL (total time: 3 seconds)
No Import is taking place.
Your import command String is being treated as one single command. Try breaking up the tokens. Also check what is being output from Process#getErrorStream:
String[] str = {"imp", "ASKUL/askul#ASKDB file=askdbinstall.dmp",
"log=askul.log", "fromuser=askul", "touser=ASKUL",
"full=N ignore=Y grants=Y indexes=Y;"};
process = Runtime.getRuntime().exec(str);
BufferedReader in =
new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.err.println(line);
}
Aside: ProcessBuilder make the use of parameter passing easier.

Categories