Use a command line program from within Java - java

How can I use a command line program from within Java?
I'm trying to pass a graph definition in the dot-language (see Wikipedia) to the interpreter program dot (see GraphViz) through java.
The problem is, that the program does not answer, after I have sent the dot-graph to its InputStream, because it does not know, that I'm finished sending the description.
This is, what I currently have:
package exercise4;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
public class Main {
public static void main(String[] args) {
PrintStream out = System.out;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
final String start =
"strict graph LSR%1$d {\n" +
" node [shape=circle color=lightblue style=filled];\n\n" +
" {rank=same; A--B [label=6];}\n" +
" {rank=same; C--D [label=12]; D--E [label=4];}\n" +
" A--C [label=4]; B--D [label=4]; B--E [label=9];\n\n" +
" node [shape=record color=\"#000000FF\" fillcolor=\"#00000000\"];\n}\n";
Process dot = Runtime.getRuntime().exec("dot -Tsvg");
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintStream(dot.getOutputStream(), false, "UTF-8");
out.printf(start, 0);
out.flush();
out.close();
while(in.ready()) {
System.out.println(in.readLine());
}
in.close();
dot.destroy();
} catch (UnsupportedEncodingException ex) {
} catch (IOException ex) {
} finally {
out.close();
}
}
}

Looks as if you are reading from the wrong input stream. Have a look at this answer: https://stackoverflow.com/a/4741987/1686330

Related

Why doesn't FileChannel append to end of file?

I am trying to download a few different files from a REST API using Java.
So far, I am getting the files, but the content won't append to the end of an output file.
I changed the FileOutputStream constructor from new FileOutputStream(path) to new FileOutputStream(path, true) but somehow it does not work.
Can somebody please provide pointers to what I am missing?
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class GetXML {
// This Method Is Used To Download A Sample File From The Url
private static void downloadFileFromUrlUsingNio() {
String filePath ="config/sample.txt";
Scanner in = new Scanner(System.in);
System.out.println("Enter the NO which you want to parse: ");
while(in.hasNextLine()){
String sampleUrl = "e.g.comSearch?NO=" + in.nextLine();
URL urlObj = null;
ReadableByteChannel rbcObj = null;
FileOutputStream fOutStream = null;
// Checking If The File Exists At The Specified Location Or Not
Path filePathObj = Paths.get(filePath);
boolean fileExists = Files.exists(filePathObj);
if(fileExists) {
try {
urlObj = new URL(sampleUrl);
rbcObj = Channels.newChannel(urlObj.openStream());
fOutStream = new FileOutputStream(filePath, true);
fOutStream.getChannel().transferFrom(rbcObj, 0, Long.MAX_VALUE);
System.out.println("! File Successfully Downloaded From The Url !");
} catch (IOException ioExObj) {
System.out.println("Problem Occured While Downloading The File= " + ioExObj.getMessage());
} finally {
try {
if(fOutStream != null){
fOutStream.close();
System.out.println("fOutStream closed");
}
if(rbcObj != null) {
rbcObj.close();
System.out.println("rbcObj closed");
}
} catch (IOException ioExObj) {
System.out.println("Problem Occured While Closing The Object= " + ioExObj.getMessage());
}
}
} else {
System.out.println("File Not Present! Please Check!");
}
}
in.close();
System.out.println("Scanner Closed");
}
public static void main(String[] args) {
downloadFileFromUrlUsingNio();
}
}
You have written:
fOutStream.getChannel().transferFrom(rbcObj, 0, Long.MAX_VALUE);
The second parameter, 0, specifies that data should be transferred to the file at position zero. The position is absolute, and it doesn't matter that you opened the file for append, because you are ignoring the current channel position.
Note the documentation that states,
position - The position within the file at which the transfer is to begin; must be non-negative
Your code is an unconventional approach to a common task. As such, it's hard for readers to comprehend, and, when you encounter mistakes, hard for you to get help. Since URL only offers InputStream support, stick with streams, and avoid channels.

Why isn't BufferedWriter writing into file?

package com.mycompany.mavenproject1;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.math.BigDecimal;
public class Main {
public BufferedWriter writer;
public Main() {
Charset charset = Charset.forName("US-ASCII");
try {
this.writer = Files.newBufferedWriter(Paths.get("test.txt"), charset);
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
}
public void print_fees(String msg, BigDecimal b) {
try {
int msg_len = msg.length();
int t;
t = 34 - msg_len;
t = t - 6;
this.writer.write(msg + String.format("%" + t + "s", b));
this.writer.newLine();
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
}
public static void main(String args[]) {
BigDecimal b = new BigDecimal(2);
Main obj = new Main();
try {
obj.print_fees("Fee: ", b);
} catch (Exception e) {
System.err.format("Exception: %s%n", e);
}
}
}
Why isn't BufferedWriter writing into file?
The point of BufferedWriter is to buffer written content into memory prior to writing it to whatever underlying implementation. When the buffer is filled in memory, it will write in bulk. This generally improves performance of writing, as doing a direct file/disk write for each small write can kill performance due to I/O blocking.
You need to flush the stream explicitly to indicate you want the entire buffer in memory to be written to the underlying implementation (in this case, a file writer) by invoking BufferedWriter#flush() after you have written to the writer. For example,
this.writer.flush().
Also, you should make a habit of closing open OutputStreams/Writers when you are done with them with BufferedWriter#close(). BufferedWriter will automatically invoke BufferedWriter#flush() for you, writing all your writes to whatever the underlying implementation is, without needing to explicitly invoke BufferedWriter#flush(). For example, close your writer once you have finished writing to your Writer: this.writer.close()
this.writer.write(msg + String.format("%" + t + "s", b));
this.writer.flush();

Running a shell script interactively from a Java class in Linux machine

I have a simple shell script which prints "Hello world", asks for a number from user and prints that number.
I am trying to run this script from a Java class in linux machine using runtime and process.
However, when I run this Java class in linux machine from commandline using java command, it prints the first 2 lines and hangs at the point of taking input from user. I am not able to pass any input to the script.
Kindly let know how I can run the script interactively via java. Below is my script and java class file:
sample.sh
#!/bin/sh
echo "Hello world"
echo "Enter any number"
read response
echo "The number you entered is: $response"
ExecuteScript.java
package com.scripting;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
public class ExecuteScript {
public static void main(String args[]) {
System.out.println("Java program ran!!");
String[] cmdScript = new String[]{"/bin/bash", "/root/sample.sh"};
Process procScript = null;
try {
procScript = Runtime.getRuntime().exec(cmdScript);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream ip = procScript.getInputStream();
OutputStream op = procScript.getOutputStream();
BufferedReader reader = new BufferedReader(new
InputStreamReader(ip));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(op));
BufferedReader consoleReader =
new BufferedReader(new InputStreamReader(System.in));
try {
while(reader.readLine() != null) {
if(!reader.ready()) {
String input = consoleReader.readLine();
writer.write(input);
writer.flush();
}else {
System.out.println(reader.readLine());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Converting Java IO Class to Android IO

I want to convert my IO Class from java on Eclipse to the Android API. For some reason it's not working on android!It is giving me a NullPointerException on my Println method. This class is used to create, write, read and open textfiles. My goal is to make all these methods readable on android.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
public class IO {
private static PrintWriter fileOut;
private static BufferedReader fileIn;
public static void createOutputFile(String fileName) {
try {
fileOut = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
} catch (IOException e) {
System.out.println("*** Cannot create file: " + fileName + " ***");
}
}
public static void openOutputFile(String fileName) {
try {
fileOut = new PrintWriter(new BufferedWriter(new FileWriter(fileName, true)));
} catch (IOException e) {
System.out.println("*** Cannot open file: " + fileName + " ***");
}
}
public static void openOutputFile2(String fileName) {
try {
fileOut = new PrintWriter(new BufferedWriter(new FileWriter(fileName, false)));
} catch (IOException e) {
System.out.println("*** Cannot open file: " + fileName + " ***");
}
}
public static void print(String text) {
fileOut.print(text);
}
public static void println(String text) {
fileOut.println(text);
//System.out.println(text);
}
public static void closeOutputFile() {
fileOut.close();
}
public static void openInputFile(String fileName) {
try {
fileIn = new BufferedReader(new FileReader(fileName));
//System.out.println("opening " + fileName);
} catch (FileNotFoundException e) {
System.out.println("***Cannot open " + fileName + "***");
}
}
public static String readLine()
// throws IOException
// Note: if there's an error in this method it will return IOException
{
try {
return fileIn.readLine();
} catch (IOException e) {
e.printStackTrace();
return "errors";
}
}
public static void closeInputFile() {// throws IOException
// Note: if there's an error in this method it will return IOException
try {
fileIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
If you're getting a NullPointerException in println then that would be because 'fileOut' is null.
public static void println(String text) {
fileOut.println(text);
//System.out.println(text);
}
You're actually reacting on your second error because you've ignored the first one. In all cases where you set fileOut you're swallowing (effectively hiding) the error. E.g.
public static void openOutputFile(String fileName) {
try {
fileOut = new PrintWriter(new BufferedWriter(new FileWriter(fileName, true)));
} catch (IOException e) {
//Don't do this, it makes debugging much more difficult.
//Because the root problem is hidden.
//So now you have 2 problems to solve.
//And you've thrown away the information that might have
//helped to solve the problem in the first place.
System.out.println("*** Cannot open file: " + fileName + " ***");
}
}
Stop hiding errors, if something goes wrong you need to find out about it. Because invariably, ignoring errors results in more complex errors later down the line.
Fix you bad exception handling, and you'll be able to track down the root problem (probably file not found or a permission error).

Error in Writing a text file "Exception in thread "main" " [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Causes of 'java.lang.NoSuchMethodError: main Exception in thread “main”'
I am trying to write a byte array in a text file. It is giving me error:
java.lang.NoSuchMethodError: main
Exception in thread "main"
The code i am using is as under
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class writefile {
//it works well
public static void main()throws IOException{
Writer output = null;
byte[] a= {1,2,3,4,5,6};
try {
String text = "abcd...\n";
String str3 = text.concat("the end");
String NL = System.getProperty("line.separator");
str3 = str3.concat(NL);
str3= str3.concat("next line");
for ( int i=0; i < a.length; i++){
str3 = str3.concat(NL);
str3= str3.concat(" " +a[i]);
}
File file = new File("write.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(str3);
System.out.println("Your file has been written");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Kindly help how can i resolve the problem.
The main method of a Java program must take an argument of type String[] representing the arguments (if any) passed to the program on launch.
the main signature must contain String[] argument

Categories