Process get errors - java

I need help with Java Process. I want to separate normal input from errors. I have a webview console, and I want to display normal input in white, and errors in red.
I have catch every input already
final BufferedReader reader = new BufferedReader(
new InputStreamReader(getProcess().getInputStream(), Charset.forName("UTF-8")));
String line = null;
while ((line = reader.readLine()) != null) {
server.writeToConsole(server.getConsole().getLineColorFromLogLevel(line), line);
}
reader.close();
How can I catch the errors?
Thanks, and sorry for my bad english!
EDIT:
I want to detect stacktraces what I get from the process
up

You can place the line reading logic within a try block and print once read is successful. And write logic to print error in catch block.

Related

Reading from .txt file returns "No line Found"

I've made a GUI and a button.
My code looks like this:
private void jButtonSubmitActionPerformed(java.awt.event.ActionEvent evt) {
try {
Scanner scan = new Scanner(new File("persontest.txt"));
while(scan.hasNext()) {
System.out.println(scan.nextLine());
}
} catch (FileNotFoundException ex) {
System.out.println("File not found" + ex.getMessage());
} catch (Exception e) {
System.out.println("Some error" + e.getMessage());
}
persontest.txt contains the following text:
What do I contribute with when working in team work:
a. I come up with new ideas
b. I follow-up on things because I'm basically
thorough
c. I assess what is realistic and workable
d. I advocate alternative approaches objectively and unbiased
When trying to run I get "Some error No line found"
I tried removing all special characters from the text and I could read it, so I tried adding "UTF-8" to my scanner in this manner.
Scanner scan = new Scanner(new File("persontest.txt"), "UTF-8");
However this does not seem to do anything. I still get "No line found".
If this question has been asked before excuse me, I did a thorough search, but I either could not comprehend the question asked or the answer provided in context to my problem.
I changed my scanner to bufferedreader per Troubleshoot and Harshas example and it will now read the text even with special chars, however it won't display them correctly. I just get square boxes. It's a minor problem.
If persontest.txt is in classpath (i.e. inside jar or source folder) you can use:
YourClass.class.getClassloader().getResourceAsStream("persontest.txt")
First of all, make sure persontest.txt is in your main project folder, and not a sub-folder of that, as it will not find it otherwise.
I recommend using a BufferedReader to read it line by line. Here's how:
BufferedReader input = new BufferedReader(new FileReader("persontest.txt"));
String line;
while ((line = input.readLine()) != null && !line.isEmpty()) {
System.out.println(line);
}
It's good practice to check that the line isn't empty along with checking it isn't equal to null. For example, if a line was equal to \t it would be classed as empty, but not as null.
You could simply do this using
try {
String line;
BufferedReader br = new BufferedReader(new FileReader("persontest.txt"));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
if you need to do it with a Scanner you can try using
Scanner reader = new Scanner(new FileInputStream("persontest.txt");

closing an buffer reader is compulsory

I am trying an example from
http://www.roseindia.net/java/beginners/java-read-file-line-by-line.shtml
in the example the BufferReader is not closed is that necessary to close the BufferReaderor not? Please explain.
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
Always close streams. It's a good habit which helps you to avoid some odd behaviour. Calling close() method also calls flush() so you don't have do this manually.
The best place where to close streams is probably in a finally block. If you have it like in your example and an exception occurs before the in.close() line, the stream won't be closed.
And if you have chained streams, you can only close the last one and all before it are closed too. This means br.close() in your example - not in.close();
Example
try {
// do something with streams
} catch (IOException e) {
// process exception - log, wrap into your runtime, whatever you want to...
} finally {
try {
stream.close();
} catch (IOException e) {
// error - log it at least
}
}
Alternatively you can use closeQuietly(java.io.InputStream) in Apache Commons library.
From the perspective of resource leak prevention, it is not strictly necessary to close a wrapper stream if you've also closed the stream that it wraps. However, closing the wrapped stream may result in stuff getting lost (specifically in the output case), so it is better to close (just) the wrapper, and rely on documented behavior that the closing the wrapper closes the wrapped stream too. (That is certainly true for the standard I/O wrapper classes!)
Like Peter Lawrey, I question the wisdom of relying on "Rose India" examples. For instance, this one has two more obvious mistakes in it that no half-decent Java programmer should make:
The stream is not closed in a finally block. If any exception is thrown between opening and closing, the in.close() statement won't be executed, and the application will leak an open file descriptor. Do that too often and your application will start throwing unexpected IOExceptions.
The DataInputStream in the chain serves no useful purpose. Instead, they should use fstream as the parameter for the InputStreamReader. Or better still, use FileReader.
Finally, here is a corrected version of the example:
BufferedReader br = new BufferedReader(new FileReader ("textfile.txt"));
try {
String line;
while ((line = br.readLine()) != null) {
// Print the content on the console
System.out.println(line);
}
} finally {
// Close the reader stack.
br.close();
}
or using Java 7's "try with resource":
try (BufferedReader br = new BufferedReader(new FileReader ("textfile.txt"))) {
String line;
while ((line = br.readLine()) != null) {
// Print the content on the console
System.out.println(line);
}
}
Since the underlying stream is closed, it is not absolutely necessary to close BufferedReader, even though it is a good practice to close ALL Closeables in reverse order (relative to the order they were opened in.)

Reading in text file in Java

I wrote some code to read in a text file and to return an array with each line stored in an element. I can't for the life of me work out why this isn't working...can anyone have a quick look? The output from the System.out.println(line); is null so I'm guessing there's a problem reading the line in, but I can't see why. Btw, the file i'm passing to it definitely has something in it!
public InOutSys(String filename) {
try {
file = new File(filename);
br = new BufferedReader(new FileReader(file));
bw = new BufferedWriter(new FileWriter(file));
} catch (Exception e) {
e.printStackTrace();
}
}
public String[] readFile() {
ArrayList<String> dataList = new ArrayList<String>(); // use ArrayList because it can expand automatically
try {
String line;
// Read in lines of the document until you read a null line
do {
line = br.readLine();
System.out.println(line);
dataList.add(line);
} while (line != null && !line.isEmpty());
br.close();
} catch (Exception e) {
e.printStackTrace();
}
// Convert the ArrayList into an Array
String[] dataArr = new String[dataList.size()];
dataArr = dataList.toArray(dataArr);
// Test
for (String s : dataArr)
System.out.println(s);
return dataArr; // Returns an array containing the separate lines of the
// file
}
First, you open a FileWriter once after opening a FileReader using new FileWriter(file), which open a file in create mode. So it will be an empty file after you run your program.
Second, is there an empty line in your file? if so, !line.isEmpty() will terminate your do-while-loop.
You're using a FileWriter to the file you're reading, so the FileWriter clears the content of the file. Don't read and write to the same file concurrently.
Also:
don't assume a file contains a line. You shouldn't use a do/while loop, but rather a while loop;
always close steams, readers and writers in a finally block;
catch(Exception) is a bad practice. Only catch the exceptions you want, and can handle. Else, let them go up the stack.
I'm not sure if you're looking for a way to improve your provided code or just for a solution for "Reading in text file in Java" as the title said, but if you're looking for a solution I'd recommend using apache commons io to do it for you. The readLines method from FileUtils will do exactly what you want.
If you're looking to learn from a good example, FileUtils is open source, so you can take a look at how they chose to implement it by looking at the source.
There are several possible causes for your problem:
The file path is incorrect
You shouldn't try to read/write the same file at the same time
It's not such a good idea to initialize the buffers in the constructor, think of it - some method might close the buffer making it invalid for subsequent calls of that or other methods
The loop condition is incorrect
Better try this approach for reading:
try {
String line = null;
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
System.out.println(line);
dataList.add(line);
}
} finally {
if (br != null)
br.close();
}

Communicating with C++ process from Java

First, I saw a few Q's about this issue in the site, but didn't see any answer that solve my problem.
I have a program written in Java and it calls a cmd program written in C++. (this is an assumption since I don't have the actual source) I know the expected I/O of the C++ program, in the cmd it is two lines of output and then it waits for string input.
I know that the first output line of the program is through error stream, and I receive it properly (this is expected), but I don't get the second line in error or input stream.
I tried to write to the program right after the first line ( the error line) and didn't got stuck, but there was no response.
I tried using 3 different threads, for each stream, but again, nothing was received in input/error stream after the first line, and the program didn't respond to writing through output stream.
My initializers are:
Process p = Runtime.getRuntime().exec("c:\\my_prog.exe");
BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
Is it possible at all or maybe it depends on the C++ program?
Thanks,
Binyamin
If you want to call native applications like C and C++ from Java, you need to use JNI.
I would suggest to put the input in the program when it has started, it will propably use that as input when it wants it.
Here is how I execute any command line in Java. This command line may execute any program:
private String executionCommandLine(final String cmd) {
StringBuilder returnContent = new StringBuilder();
Process pr;
try {
Runtime rt = Runtime.getRuntime();
pr = rt.exec(cmd);
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = null;
while ((line = input.readLine()) != null) {
returnContent.append(line);
}
input.close();
LOG.debug(returnContent.toString());
// return the exit code
pr.waitFor();
} catch (IOException e) {
LOG.error(e.getMessage());
returnContent = new StringBuilder();
} catch (InterruptedException e) {
LOG.error(e.getMessage());
returnContent = new StringBuilder();
}
return returnContent.toString();
}

Creating a login page in java console application using a txt file

I am creating a java console application and i need to use a notepad (txt) file to store PIN, AccountNo and Balance.
When the user enters the PIN (from BufferedReader) it should get validated from the notepad file and login to thge system. However, the code fragment which I used below only displays Enter PIN, and when i click on Enter, the program exits.
Could you please tell me what is the mistake which I have done here?
BufferedReader getIt = new BufferedReader(new InputStreamReader(System.in));
String userPIN = "";
try {
// Open the file that is the first command line parameter
FileInputStream fstream = new FileInputStream(
"D:\\Studies\\BCAS\\HND\\Semester 1\\Programming Concepts\\Assignment\\AccountInfo.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
System.out.println("Enter PIN");
userPIN = getIt.readLine();
while ((strLine = br.readLine()) != null) {
// Print the content on the console#
if (userPIN.equals(strLine)) {
System.out.println("You have login!");
}
}
//Close the input stream
in.close();
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
There are quite a few reasons why the program can simply terminate, or appear to be successful in program execution (and hence terminate successfully without doing any useful work):
The contents of the file are read, but if the end of the stream has been reached, then the code simply does not handle the case gracefully (or even consider handling it). Specifically, the line while ((strLine = br.readLine()) != null) can result in a scenario where the body of the loop is not executed.
The else condition is absent inside the body of the while loop. If none of the entries provided by the user input match the contents of the file, the code does not handle the condition, and the result is ambiguous. For all practical purposes, it appears that login is successful if the provided PIN is not present in the file.
Avoid unnecessary decoration of Readers and Streams. BufferedReader in
= new BufferedReader(new FileReader("foo.in")); is sufficient to read character data from files, and it does provide the read and readline methods to use.
PS: It is recommended that you learn to program defensively, especially when dealing with files and streams. That would help isolating cases in your code that would result in ambiguious/vague conditions.
File.ReadAllLines would be more convenient in your case.. Wouldn't be wrong to introduce a user class either if your going the good ol' oop way.
If you want to do this by yourself, StreamReader (which takes FileInfo) is a good way to go. Try to create it by using the using statement (:)) which makes cleans up after your done.

Categories

Resources