Easiest way to show text in gui? - java

I've seen many posts about it, but it looks complicated. Here is my code, what would be the easiest way to display information on gui textArea?
public static void runSystemCommand(String command) {
String message=null;
int i=0;
while (i<1) {
try {
Process p = Runtime.getRuntime().exec(command);
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String s = "";
// reading output stream of the command
while ((s = inputStream.readLine()) != null) {
//here i dont know what to type..please help
}
Thread.sleep(9000);
} catch (Exception e) {
e.printStackTrace();
}
i++;
}
}

Easiest way would be
textAreaName.setText(/*What ever you want to display here*/);
In your case it would be the following if you wanted to just set the text to s:
textArea.setText(s + "\n");
If you wanted to update the text along with the existing text you would use:
textArea.append(s + "\n");

Related

Trying to read multiple lines of cmd input

I'm trying to write a method that:
Prints out a message (Something like: "Paste your input: ")
Waits that the user presses enter.
Reads all the lines, that got pasted and adds them up in one String.
(An empty line can be used to determine the end of the input.)
The first syso does the printing part and also the first line gets read correctly, but then it never exits the while loop. Why? There has to be an end?
public static String readInput(String msg) {
System.out.print(msg);
String res = "";
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in))) {
String line;
while ((line = buffer.readLine()) != null && !line.isBlank())
res += "\n" + line;
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
Ive already seen the following sites, but they all didn't help:
How to read input with multiple lines in Java
https://www.techiedelight.com/read-multi-line-input-console-java/
Make the console wait for a user input to close
Edit:
The same bug applies for:
public static String readInput(String msg) {
System.out.print(msg);
String res = "";
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in))) {
res = buffer.lines().reduce("", (r, l) -> r + "\n" + l);
System.out.println(res);
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
Edit 2:
I've tried this code in my actual project and in a new test-project, but with different results. Here is a video of that test.
Why wouldn't use this statement?
while (!(line = buffer.readLine()).isEmpty())
In this case sending empty line will exit the loop.
Although, if you insert large text with empty lines (for example, the beginning of a new paragraph, or a space between them) will terminate the program.

Reading and splitting data from a text file

So I have a text file that looks like this...
4234
Bob
6858
Joe
I am trying to read the file with java and insert the data into an array. I want to separate the data by that empty line (space). Here is the code that I have come up with to solve the issue, but I am not quite there.
public class Main {
public static void main(String[] args) {
// This name is used when saving the file
BufferedReader input;
String inputLine;
try {
input = new BufferedReader(new FileReader("test.txt"));
while ((inputLine = input.readLine()) != null) {
System.out.println(Arrays.toString(inputLine.split(" ")));
}
} catch (IOException e) {
System.out.println(e.getMessage());
System.exit(1);
}
}
}
The issue that I am coming across is that the output from the code above looks something like this
[4234]
[Bob]
[]
[6858]
[Joe]
The outcome that I would like to achieve, and for the life of me can't think of how to accomplish, is
[4234, Bob]
[6858, Joe]
I feel like with many things that it is a relatively simple code change; I am just not sure what that is.
You need:
2D array
Logic to keep track of where you are in the array position
If your Line is a Number/String
This sounds like hw :) so I wont be solving it, I will just help a bit.
String[][] myData = define your 2D array;
//You need to create a consumer. This is what will take the String line, figure out where to put it into your 2D array.
Consumer<String> processLine = (line) -> {
if(StringUtils.isNumeric(line)){
//Put into array[counter][1]
}
else{
//its a String
//Put into array[counter][0]
}
};
The below try/catch, Opens a File, Reads its Lines, and goes over each one in order (forEachOrdered), ignoring all empty lines, and send it to your processLine consumer.
try (Stream<String> lines = Files.lines(Paths.get("C:/example.txt"), Charset.defaultCharset())) {
lines.filter(line -> !line.isEmpty()).forEachOrdered(processLine);
}
catch (Exception e){
//Handle Exception
}
Used Apache StringUtils http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html
IF you dont want to use any external Libs. You can probably do
Integer.parseInt(line) <-- If that throws an exception, its not a number
Your way of reading the file is not most convenient, in this case.. Scanner would have eased all this work; however, if you insist, that you want to use BufferedReader and FileReader, it's going to be a bit verbose, boilerplate and even ugly code, something like this:
public class Main {
public static void main(String[] args) {
// This name is used when saving the file
BufferedReader input;
String inputLine;
String answer = "";
try {
input = new BufferedReader(new FileReader("path\\to\\your\\test.txt"));
while ((inputLine = input.readLine()) != null) {
answer = answer + "[" + inputLine + ", ";
while ((inputLine = input.readLine()) != null && !inputLine.equals("")) {
answer += inputLine;
}
answer += "]";
System.out.println(answer);
answer = "";
}
} catch (IOException e) {
System.out.println(e.getMessage());
System.exit(1);
}
}
}
This code, with test.txt containing:
4234
Bob
6858
Joe
4234
John
5352
Martin
will output:
[4234, Bob]
[6858, Joe]
[4234, John]
[5352, Martin]
I don't know if it's an actual requirement for you to use arrays of strings, but the better way in the long run is to create a class.
class Person {
public String id;
public String name;
public String toString() { return String.format("[%s, %s]", id, name); }
}
(note: It's a bad idea to actually make the fields public, but this makes the code shorter. You should probably use getters and setters).
Now you can create Persons while reading the file.
List<Person> allInFile = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader("path\\to\\your\\test.txt"))) {
String line = reader.readLine();
while (line != null) {
line = line.trim();
// ignore empty lines
if (line.length() == 0) {
continue;
}
// this is an id; create a person and assign id
Person person = new Person();
person.id = line;
// read consecutive field, which is the name
person.name = reader.readLine();
// add the person to the list
allInFile.add(person);
}
}
allInFile.forEach(System.out::println);
Lots of improvements to be done on this, but the main point is to put the two data points into a class.
Try with this code:
it work only when file contains number followed by name otherwise pair would be different format
pair : [number, string]
public static void main(String[] args) {
BufferedReader input;
String inputLine;
List<String> pair = new ArrayList<String>();
List<String> list = new ArrayList<String>();
try {
input = new BufferedReader(new FileReader("Test.txt"));
while ((inputLine = input.readLine()) != null) {
if (!inputLine.isEmpty()) {
pair.add(inputLine);
}
if (pair.size() == 2) {
list.add(pair.toString());
pair.clear();
}
}
for (String s : list) {
System.out.println(s);
}
} catch (IOException e) {
System.out.println(e.getMessage());
System.exit(1);
}
}
After looking at the answers posted by my fellow Stack Overflow members I figured out that there was a very simple way of solving this issue and that was by using Scanner rather than using BufferedReader. I am not sure why I didn't think of this before, but hindsight is 2020. Anyway, the code below is what I used to solve my issue.
public static void main(String[] args) {
ArrayList<String> test = new ArrayList<>();
File file = new File("test.txt");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
test.add(sc.next()); // The id
test.add(sc.next()); // The name
}
sc.close();
System.out.println(test.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
All this is doing is getting each line with the different data on it and is skipping the blank. From there it is adding it to an ArrayList for later processing. Remember K.I.S.S (Keep It Simple Stupid) no need to overcomplicate anything.

console output on gui

I have problem with console output. I did search for one day now and i still can't fix the problem. I have tried adding text on JTextArea manually and it works, so gui should be fine. IF i change code to System.out.println(s), it will writte in console successfully. Here is my code:
public static void runSystemCommand(String command) {
String message=null;
int i=0;
while (i<1){
try {
gui area=new gui();
// ArrayList<String> sList = new ArrayList<String>();
areaField=new JTextArea();
sarray = new String [500];
Process p = Runtime.getRuntime().exec(command);
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String s = "";
// reading output stream of the command
while ((s = inputStream.readLine()) != null) {
area.jTextArea.append(s+ "\n"); //this doesnt work..
}
Thread.sleep(9000);
} catch (Exception e) {
e.printStackTrace();
}
i++;
}
In your code you have an empty string String s = ""; try to assign some string to s like this:
String s = "some value";
area.jTextArea.append(s+ "\n");
You are appending to the wrong JTextArea.
In your pingmain class you create a new instance of gui which is never shown to the user. In this invisible instance you correctly add the text to the textarea.
If you instead add a gui area parameter to your runSystemCommand method and give this as second arguemnt to the method call in gui, you will see your output in your textarea.

Read, scan, modify a text file and put modified text into a new file

I've tried to read a text file and try to modify it. So many discussion that I got from StackOverflow, here is the content:
NO 1025 0
NO 1025 1
OP 1026 0
EndRow
The modified text file that I want:
NO 0
AND 1
OP 0
EndRow
I read some discussion topics about it, and then came the conclusion that I have to use the .hasNextLine method to check every line. Here's the code:
import java.io.*;
import java.util.Scanner;
public class MainConvert {
/**
* #nahdiya
*/
public static void main(String[] args) {
try {
File readNet = new File("testttt.net");
FileReader readFileNet = new FileReader(readNet);
BufferedReader reader = new BufferedReader(readFileNet);
Scanner scan = new Scanner("testttt.net");
PrintWriter fileConvert = new PrintWriter("convertNet.txt");
while (scan.hasNextLine()) {
String check = scan.next();
String checkLine = scan.nextLine();
if (checkLine.contains("NO 1025")) {
if(checkLine.contains("NO 1025")) {
fileConvert.println("AND "+check );
} else if (checkLine.contains("OP 1026")) {
fileConvert.println("OP"+check);
} else {
fileConvert.println(checkLine);}
}
}
}
reader.close();
fileConvert.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
When I tried to run the class, an output message appeared like this:
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at fileConvertSave.MainConvert.main(MainConvert.java:21)
The problem is:
PrintWriter fileConvert = new PrintWriter("convertNet.txt");
What is the problem with this line? I just want to modify the testttt.net file. fileConvert must be created as the new file. What is wrong with it?
Edited: See the full solution at the bottom:
The original problem that was yielding the error message was the Scanner trying to perform nextLine() on a line that wasn't there due to:
String check = scan.next();
String checkLine = scan.nextLine();
When you call:
while( scan.hasNextLine() )
there is a next line available. You then call:
scan.next();
At this point there might not be a "next line" available anymore. You then call:
scan.nextLine()
and boom.
removing the line
String check = scan.next();
should work.
Edit:
Here is a solution to all the other parts of the problem... It's basically a complete rewrite of what you've got, so please read all the code, learn what it does and try to understand it all! If in doubt, please read the documentation first before asking a question.
BufferedReader reader = null;
PrintWriter writer = null;
try {
reader = new BufferedReader(new FileReader("testttt.txt"));
writer = new PrintWriter("convertNet.txt");
// setup the pattern that we want to find and replace in the input:
// NB> this is a regex (or regular expression)
// it means, find [space] then either 1025 or 1026 then [space]
String patternToMatch = " (1025|1026) ";
String inputLine = null;
// while there are lines to read, read them one at a time:
while ((inputLine = reader.readLine()) != null) {
// create the outputLine which is the input line with our pattern
// " 1025 " or " 1026 " replaced by just a single space:
String outputLine = inputLine.replaceFirst(patternToMatch, " ");
// log the transformation for debugging purposes:
System.out.println(inputLine + " -> " + outputLine);
// write the outputLine to the output file:
writer.println(outputLine);
}
}
catch (FileNotFoundException ex) {
System.out.println("file was not found: " + ex);
}
catch (IOException ex ) {
System.out.println("io error: " + ex);
}
finally {
try {
if( reader != null ) reader.close();
if ( writer != null ) writer.close();
} catch (IOException ex) {
System.out.println("error closing file " + ex);
}
}
Note that the finally block cleans up nicely even in the event there is an Exception. There's also a newer way to do this, that can make code a little shorter called try with resources:
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Your string does not look consistent i recommend you use regex if there are more strings like this and Bufferreader to read line, although i didn't use regex but this what i came up with,
public static void main(String[] args) {
try {
File readNet = new File("testttt.net");
FileReader readFileNet = new FileReader(readNet);
BufferedReader reader = new BufferedReader(readFileNet);
PrintWriter fileConvert = new PrintWriter("convertNet.txt");
String r = null;
while ((r = reader.readLine()) != null) {
System.out.println(r);
if (r.equals("NO 1025 1")) {
fileConvert.println(r.replace(r, "AND 1"));
} else if (r.contains("1025 0")) {
fileConvert.println(r.replaceAll("1025", ""));
} else if (r.contains("1026")) {
fileConvert.println(r.replaceAll("1026", ""));
} else {
fileConvert.println(r);
}
}
reader.close();
fileConvert.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
Good Luck, i hope it helps you.

How to execute code from a String in Java

I'm trying to work on a security system which needs remote debugging.So what I'm searching is a way to execute a code which is in a String,like the example below but with java.
try {
String Code = "rundll32 powrprof.dll, SetSuspendState";// the code we need to excecute
Runtime.getRuntime().exec(Code);
} catch (IOException e) {
}
String Code = "rundll32 powrprof.dll, SetSuspendState";
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(Code);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(output.toString());
Please refer the following URL for further information http://www.mkyong.com/java/how-to-execute-shell-command-from-java/
No friend you got it wrong.I really don't want to execute cmd codes.what i really want is to execute java commands.as a string which is passed as shown below.
example :
String code = "System.out.println("Test code")";
Runtime.getRuntime().exec(Code);
something like this.

Categories

Resources