networked computer names to be displayed in jlist - java

How to retrieve or gathered all computer names from a networked place ? I need some guide or sample code on how to start from scratch.

in simplest form run loop over ip range execute command nslookup
import java.io.*;
public class TestExec {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("nslookup xx.xx.xx.xx ");
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
and parse response

Related

No output from a program that compiles

I can't wrap my head around why I get zero output... The code looks correct to me, and it compiles with no problem (except for the lack of output). I have tried with absolute path. The text file is stored in the same folder as the class. Am I missing something obvious?
public class File {
public static void main(String[] args) throws FileNotFoundException {
String filename = "./inputD2.txt";
readFile(filename);
System.out.println( readFile(filename));
}
private static List<String> readFile(String filename) {
List<String> records = new ArrayList<>();
try {
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
while ((line = reader.readLine()) != null) {
records.add(line);
}
reader.close();
return records;
}
catch (Exception e) {
System.err.format("Exception occurred trying to read '%s'.", filename);
e.printStackTrace();
return null;
}
}
}
package com.test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class FileReaderTest {
public static void main(String[] args) {
String filename = "F:\\Sixth_workspace\\Sampleproject\\src\\main\\resources\\try.txt";
System.out.println("Reading from the text file" + " " + readFile(filename));
}
private static List<String> readFile(String filename) {
List<String> records;
try {
records = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
while ((line = reader.readLine()) != null) {
records.add(line);
}
reader.close();
return records;
} catch (Exception e) {
System.err.println("Exception occurred trying to read '%s'." + filename);
e.printStackTrace();
return null;
}
}
}
I modified your code and got the desired output. Use the full path of the text file, here
F:\\Sixth_workspace\\Sampleproject\\src\\main\\resources\\try.txt
is my full path.
Changes:
Changed the classname
Given full path of the text file
Using java 1.8 (above 1.5 is required)

In Java, a small help to allow a program send commands to CMD.exe

I am trying to create a program (personal practice) to access CMD and type any command you want, as if you were working on cmd.exe;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class CMD_Live {
public static void main(String[] args) throws IOException {
// The purpose of this program is to use Java to perform CMD commands as if you are working on it live
Scanner ScanCMD = new Scanner(System.in);
while(true) {
System.out.print("Insert your Command> ");
String CMDcommand = ScanCMD.nextLine();
Process processToCMD = Runtime.getRuntime().exec(CMDcommand);
BufferedReader readerToCMD = new BufferedReader(new InputStreamReader(processToCMD.getInputStream()));
String line;
while ((line = readerToCMD.readLine()) != null) {
System.out.println(line);
}
System.out.println();
readerToCMD.close();
}
}
}
The problem with this code is, it works for straightforward commands,
like ping google.com, or nslookup google.com,
but if I insert nslookup and hit enter to access advance mode, then the response goes off.
Is there a way to fix it?
This should work for you:
ProcessBuilder processBuilder = new ProcessBuilder(CMDcommand); //note, that you can build your command here step by step.
Process process = processBuilder.start();
String response = null;
InputStream inputStream = process.getInputStream();
BufferedReader bufferedInputStream = new BufferedReader(new InputStreamReader(inputStream));
//and then do whatever you want to do.. my example is this:
while(response=bufferedInputStream.readLine()!=null) {
..some code..
}
} catch (IOException e) {
e.printStackTrace();
}

Java reading files

I am trying to learn file reading and writing, but I tried it with BufferedReader, and Scanner, it will always show the exception message. I followed the steps in the book tho. Not sure what went wrong.
package fileIO;
import java.io.*;
import java.util.*;
public class files {
public static void main(String[] args) {
String line = "";
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader("Shadow.txt"));
while(br.readLine() != null){
line += br.readLine();
System.out.println(line);
}
}catch(FileNotFoundException e){
System.err.println("File not found");
}catch(Exception e){
System.out.println("Throwing exception");
}
}
}
Change your while a little bit:
while( (line = br.readLine() ) != null ) {
System.out.println(line);
}
This works for me:
import java.io.*;
class Test {
public static void main(String[] args) {
Printer.print("Shadow.txt");
}
}
public class Printer {
public static void print(String filename) {
String line;
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
while ((line = br.readLine()) != null) System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.close();
}
}
}
I upgraded you to a try-with-resources, and fixed your while-loop. Hopefully it's also an example of how to write more modular code.

Executing ruby script with Spring

I have a problem with running ruby script in spring framework.
Let's say I have a script named 'my_script.rb', when I run it from terminal it works perfectly normal. When I execute it in "normal" java program:
public class RubyExecutor {
public static String execute(String command){
StringBuilder output = new StringBuilder();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
public static void main(String[] args){
System.out.println(RubtExecutor.execute("ruby /home/wookash/script.rb \"/home/wookash/rubyScripts\" \"case_0/\""));
}
script still works.
Problem comes when I put mentioned-above code in spring app.
What is weird: literally half of ruby script runs, magicly second half of lines of code is not being executed, no matter what is there. No errors, no warnings, nothing. I'm guessing that is caused by Spring task execution framework. However i have no idea how to fix it. Thank You in advance.
//EDIT I am pasting my spring method.
#RequestMapping("/execute")
public void executeCmd(){
executeCommand("ruby /home/wookash/script.rb \"/home/wookash/rubyScripts\" \"case_0/\"");
}
private String executeCommand(String command) {
StringBuilder output = new StringBuilder();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}

A Java program that runs an external "java myprog < input.txt > output.txt"

I want to write a Java program that runs an external "java myprog < input.txt > output.txt" command. The eventual goal is to run this command on two different programs and compare their output similarity from their respective output files.
I think I've read just about every relevant article about using ProcessBuilder to run an external program, and the few entries about handling user input in that external program, but I still can't get things working. From what I have read, I think the best approach is to not run the exact command above, but instead read the input.txt file and feed it byte-by-byte into the Process object, then collect the output and write it to output.txt ... I am 100% open to other options.
I put together the code below based on my readings. It seems to correctly feed input from input.txt into myprog, but when I try to print the external program's output to the console to verify, the program hangs at the point where (surprise) user input is expected in myprog.
I get the same issues with and without the redirectErrorStream(true) line.
I really want this to be in Java since I plan to share the source code with the people whose program outputs I will compare, and they are primarily only familiar with Java.
import java.io.*;
import java.util.*;
public class test7 {
public static void main(String args[]) {
try {
// WANT: "java myprog < input.txt > output.txt"
String inputFile = "input.txt";
String outputFile = "output.txt";
ProcessBuilder pb = new ProcessBuilder("java","myprog");
pb.redirectErrorStream(true); // merge stdout, stderr of process
Process p = pb.start();
// write input to the running program
OutputStream pos = p.getOutputStream();
InputStream fis = new FileInputStream(inputFile);
int read = 0;
while ( (read = fis.read()) != -1) {
pos.write(read);
}
fis.close();
// get output of running program
InputStreamReader isr = new InputStreamReader(p.getInputStream());
BufferedReader br = new BufferedReader(isr);
// HANGS HERE WHEN USER INPUT REQUIRED
String lineRead;
while ((lineRead = br.readLine()) != null) {
System.out.println(lineRead);
}
}
catch (IOException e) {
e.printStackTrace();
}
} // end main
}
Here is the content of myprog.java:
import java.io.*;
public class myprog {
public static void main(String args[]) throws IOException {
System.out.println("Hello world!");
System.out.println("Enter something:");
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
// the readLine() command causes ProcessBuilder to hang
cin.readLine();
}
}
And the input.txt file is just
p
The output.txt file should be
Hello world!
Enter something:
I wonder if your problem is partly to do with not using separate threads for reading input and writing output. For instance:
public static void main(String args[]) {
try {
// WANT: "java myprog < input.txt > output.txt"
String inputFile = "input.txt";
String outputFile = "output.txt";
// my ProcessBuilder Strings will be different from yours
ProcessBuilder pb = new ProcessBuilder("java", "-cp", ".;bin;",
"yr12.m04.a.MyProg");
pb.redirectErrorStream(true);
Process p = pb.start();
final OutputStream pos = p.getOutputStream();
final PrintWriter pw = new PrintWriter(pos);
final InputStream fis = new FileInputStream(inputFile);
final BufferedReader fileBr = new BufferedReader(new InputStreamReader(fis));
InputStreamReader isr = new InputStreamReader(p.getInputStream());
final BufferedReader br = new BufferedReader(isr);
new Thread(new Runnable() {
public void run() {
String lineRead;
try {
while ((lineRead = br.readLine()) != null) {
System.out.println(lineRead);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}).start();
new Thread(new Runnable() {
public void run() {
try {
String lineRead;
while ((lineRead = fileBr.readLine()) != null) {
pw.println(lineRead);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (pw != null) {
pw.close();
}
if (fileBr != null) {
try {
fileBr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
} // end main
Have you thought about using Runtime.getRuntime().exec() instead?
Process proc = Runtime.getRuntime().exec("java myprog "+inputFile+" "+outputFile);
You could include the jar of the 'myprog' and call the main() method yourself. Even more so if myprog is in your domain you could get rid of the main method altogether.

Categories