Java TextFile Multithreading - java

I basically want to print all that comes above when i encounter a line
So what i am doing is I am creating a new Thread whenever i encounter a new line. I want to know how to do this. This code below which i wrote is giving wrong outputs i am not able to understand. pls do help
This is the Java code
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
class ThreadDemo extends Thread {
private Thread t;
private String threadName[];
ThreadDemo(String[] name, int le) {
threadName = name;
System.out.println("Creating " + le);
}
public void run() {
// System.out.println("Running " + threadName);
try {
// System.out.println("come");
for (int i = 0; threadName[i] != null; i++) {
System.out.println(i + "y " + threadName[i]);
// Let the thread sleep for a while.
Thread.sleep(0);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start() {
System.out.println("Starting " + threadName);
if (t == null) {
System.out.println("come");
t = new Thread(this);
t.start();
}
}
}
public class TestThread {
public static void main(String args[]) throws IOException {
FileInputStream input = new FileInputStream("/e:/Amazonsupernew.txt");
PrintWriter output = new PrintWriter("/e:/multicode1.txt");
BufferedReader file = new BufferedReader(new InputStreamReader(input));
Map<String, ArrayList<String>> CusId = new HashMap<String, ArrayList<String>>();
String line;
String[] send = new String[10000];
int i = 0;
while ((line = file.readLine()) != null) {
send[i++] = line;
if (line.isEmpty()) {
send[i - 1] = null;
String temp[] = send;
ThreadDemo T = new ThreadDemo(temp, i);
T.start();
i = 0;
}
}
}
}
File
This is the text file
i just want to print each Ids information each one for each thread

Related

Need help searching through three files and printing out the same common lines

For now, I'm searching through the first one then sending it to the second one but the second one only prints and compares the first line.
I don't know how to make the second method start from the next line and so on. The objective is to do this with three text files but i cant even get through the first one. It has to be using bufferedreader and a while loop.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
public class scanner {
public static String line;
public static String line2;
public static String line3;
public static boolean match = false;
public static void main (String [] args) throws IOException
{
BufferedReader in = new BufferedReader(new FileReader("creditCards1.txt"));
line = in.readLine();
while (match==false && line != null)
{
System.out.println(line);
line = in.readLine();
scan2(line);
}
in.close();
}
public static boolean scan2(String line) throws IOException
{
BufferedReader in2 = new BufferedReader(new FileReader("creditCards2.txt"));
if (line2 == null || line2 == "7120-0824-9323-2825")
{
line2 = in2.readLine();
}
while(match==false && line!=null)
{
System.out.println(line2);
if(line2 == line)
{
match = true;
System.out.println("sdsds" + line);
in2.close();
break;
}
line2= in2.readLine();
break;
}
return match;
}
}
package so;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
File f1 = new File("/home/guest/Desktop/file1.txt");
File f2 = new File("/home/guest/Desktop/file2.txt");
File f3 = new File("/home/guest/Desktop/file3.txt");
try {
compareTwo(f1, f2);
compareTwo(f1, f3);
compareTwo(f2, f3);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void compareTwo(File f1, File f2) throws IOException {
String l1,l2;
try (BufferedReader r1 = new BufferedReader(new FileReader(f1))) {
while ((l1 = r1.readLine()) != null) {
try (BufferedReader r2 = new BufferedReader(new FileReader(f2))) {
while ((l2 = r2.readLine()) != null) {
if(l1.equals(l2))
System.out.println("line: " + l1 + " in file " + f1 + " exists in file " + f2);
}
}
}
}
}
}

How can I put the first three words on each line into an arraylist?

public class scripttest {
public static void main(String[] args) {
File file = new File("text.txt");
script(file);
}
public static void script(File filename) {
String line = null;
try {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
bufferedReader.close();
} catch(IOException ex) {
System.out.println("Error reading file named '" + filename + "'");
}
}
}
Im trying to make a script function for my program, the script requires a file, which each command written out on each line to be carried out consecutively. How do I add the first three words on each line to an arraylist, which will then be used to interpret the commands for each line?
// considering you have line variable. myArrayList is ur list.
String[] words = line.split(" ");
if(words.length() >= 3) {
myArrayList.add(words[0] + " " + words[1] + " " + words[2])
}
If you can use Java 8:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class TestScript {
public static void main(String[] args) {
script("text.txt");
}
private static void script(String filename) {
try (Stream<String> stream = Files.lines(Paths.get(filename))) {
stream.forEach(TestScript::executeLine);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static void executeLine(String line) {
System.out.println(line);
String[] args = line.split(" ");
executeCommand(Arrays.stream(args).limit(3).collect(Collectors.toList()),
Arrays.stream(args).skip(3).collect(Collectors.toList()));
}
private static void executeCommand(List<String> command, List<String> args) {
System.out.println(command + ": " + args);
}
}

Java (Raspberry pi) Thread

I am a student who is studying java.(Especially Raspberry pi) I have a question this multuthread. It can be compiled. But it doesn't work in my kit. If you don't mind guys, could you check my code and help me?
Thanks...
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.File;
import java.io.FileWriter;
public class RcvThread2 implements Runnable{
private static final int sizeBuf = 50;
private Socket clientSocket;
private Logger logger;
private SocketAddress clientAddress;
public RcvThread2(Socket clntSock, SocketAddress clientAddress, Logger logger) {
this.clientSocket = clntSock;
this.logger = logger;
this.clientAddress = clientAddress;
}
static class CloseExtends extends Thread {
static final String GPIO_OUT = "out";
static final String GPIO_ON = "1";
static final String GPIO_OFF = "0";
static final String[] GpioChannels = {"18"};
public static void main(String[] args) {
FileWriter[] commandChannels;
try {
FileWriter unexportFile = new FileWriter("sys/class/gpio/unexport");
FileWriter exportFile = new FileWriter("sys/class/gpio/gpio/export");
for(String gpioChannel : GpioChannels) {
System.out.println(gpioChannel);
File exportFileCheck =
new File("sys/class/gpio/gpio" +gpioChannel);
if(exportFileCheck.exists()) {
unexportFile.write(gpioChannel);
exportFile.flush();
}
exportFile.write(gpioChannel);
exportFile.flush();
FileWriter directionFile = new FileWriter("/sys/class/gpio/gpio" + gpioChannel + "/direction");
directionFile.write(GPIO_OUT);
directionFile.flush();
}
FileWriter commandChannel = new FileWriter("sys/class/gpio/gpio" + GpioChannels[0] + "/value");
int period = 20;
int repeatLoop = 25;
int counter;
while(true) {
for(counter = 0; counter < repeatLoop; counter++) {
commandChannel.write(GPIO_ON);
commandChannel.flush();
java.lang.Thread.sleep(2, 20000);
commandChannel.write(GPIO_OFF);
commandChannel.flush();
java.lang.Thread.sleep(period);
}
break;
}
} catch(Exception exception) {
exception.printStackTrace();
}
}
}
public void main(){
try {
InputStream ins = clientSocket.getInputStream();
OutputStream outs = clientSocket.getOutputStream();
int rcvBufSize;
byte[] rcvBuf = new byte[sizeBuf];
while ((rcvBufSize = ins.read(rcvBuf)) != -1) {
String rcvData = new String(rcvBuf, 0, rcvBufSize, "UTF-8");
if(rcvData.compareTo("MotorLock") == 0) {
CloseExtends te = new CloseExtends();
te.start();
}
if(rcvData.compareTo("MotorOpen") == 0) {
}
logger.info("Received data :" + rcvData + " (" + clientAddress + ")");
outs.write(rcvBuf, 0, rcvBufSize);
}
logger.info(clientSocket.getRemoteSocketAddress() + "Closed");
} catch (IOException ex) {
logger.log(Level.WARNING, "Exception in RcvThread", ex);
}finally {
try{
clientSocket.close();
System.out.println("Disconnected! Client IP :" + clientAddress);
} catch (IOException e) {}
}
}
}
The lower main method never gets called.
If you run your program it will execute the public static void main(String[] args) { method.
I think this is the method you want to run in the second thread?!
If you declare and run your new thread using
CloseExtends te = new CloseExtends();
te.start();
it will run the threads public void run() { method.
So if I understand your intention correctly you should change the name of the main method in the CloseExtends class to the threads run method and change the signature of the lower main method to the java programs main method public static void main(String[] args) {.
I would not name any other method "main" if it is not really a main method.
You can see an example of creating a new thread with the Runnable interface here: https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html

Switching to specific window using PID (Process ID)

I'm working on a Java Selenium program which uses Runtime class.
There are multiple instances of Internet Explorer windows that are open.
I need to "Bring Front" only one specific window for the selenium suite to run without errors.I have retrieved the specific iexplore instance using tasklist command.
Now I have the PID of the process.
Process p = Runtime.getRuntime().exec("tasklist /FI \"WindowTitle eq Google\"");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
int count=1;
while ((line = in.readLine()) != null) {
System.out.println(count + " " + line);
count++;
}
How to bring a process to the front (make it the active window) through Runtime command line using its PID?
EDIT:
Is there a way to switch to an application window from command prompt using the PID of the application?
To switch to an application window from command prompt you can use Windows Script Host's AppActivate function. It accepts either ProcessID or window's title as its argument. Here is a simple script:
set WshShell = CreateObject("WScript.Shell")
WshShell.AppActivate Wscript.Arguments(0)
Then call the script by using cscript AppActivate.vbs 1234
I tried to apply the advice above into a complete solution
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.apache.commons.io.FileUtils.writeStringToFile;
import static org.apache.commons.lang3.math.NumberUtils.toInt;
public class WindowSwither {
private static final Pattern TASKLIST_CSV_PATTERN = Pattern.compile("\".*?\",\"(\\d+)\".*");
private int pidActive = 0;
private final List<Integer> pidList = new ArrayList<>();
public WindowSwither(String exeName) throws IOException {
Process p = Runtime.getRuntime().exec("tasklist /FI \"ImageName eq " + exeName + ".exe\" /FO CSV");
for (String line : showProcessOut(p)) {
Matcher m = TASKLIST_CSV_PATTERN.matcher(line);
if (m.find()) {
pidList.add(toInt(m.group(1)));
}
}
}
public void next() throws IOException {
if (pidList.size() == 0) {
System.out.println("List empty! Ignored.");
return;
}
if (pidActive == 0) {
pidActive = pidList.get(0);
System.out.println("[0] " + pidActive);
} else {
Iterator<Integer> it = pidList.iterator();
while (it.hasNext()) {
Integer pid = it.next();
if (pid == pidActive) {
break;
}
}
if (it.hasNext()) {
pidActive = it.next();
System.out.println("[+] " + pidActive);
} else {
pidActive = pidList.get(0);
System.out.println("[0] " + pidActive);
}
}
activate(pidActive);
}
private static void activate(int pid) throws IOException {
String pathname = System.getProperty("java.io.tmpdir") + "WindowSwintcherAppActivate.vbs";
File file = new File(pathname);
if (!file.exists()) {
String content = "set WshShell = CreateObject(\"WScript.Shell\")\n" +
"WshShell.AppActivate Wscript.Arguments(0)";
writeStringToFile(file, content, StandardCharsets.UTF_8);
}
Runtime.getRuntime().exec("cscript " + pathname + " " + pid);
}
private List<String> showProcessOut(Process p) throws IOException {
List<String> list = new ArrayList<>();
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream(), "cp866"));
String line;
while ((line = in.readLine()) != null) {
list.add(line);
}
return list;
}
}
Main class
public class EnumerateWindows {
public static void main(String[] args) throws IOException, InterruptedException {
WindowSwither swither = new WindowSwither("notepad");
swither.next();
Thread.sleep(1000);
swither.next();
Thread.sleep(1000);
swither.next();
Thread.sleep(1000);
swither.next();
Thread.sleep(1000);
}
}

How can I write large output to Process getOutputStream?

I am trying to execute a command (eg. ps -ef | grep apache) using ProcessBuilder and Process. The code works as long as the output of 'ps -ef' is small. But if the output is too big, the program hangs. Is there a way to fix this? Here is my code based on [http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html]
#### Program.java ####
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class Program {
private List<String> command;
public Program(String commandString) throws IOException {
this(commandString, null);
}
public List<String> getCommand() {
return this.command;
}
private void setCommand(String filename, String location, String commandString, List<String> parameters) throws IOException {
if(filename != null) {
commandString = new File(location, filename).getCanonicalPath();
}
this.command =
Collections.synchronizedList(new ArrayList<String>());
this.command.add(commandString);
if (parameters != null) {
for (String arg: parameters) {
command.add(arg);
}
}
}
public String[] run() throws IOException, InterruptedException {
return this.run(null);
}
public String[] run(String input) throws IOException, InterruptedException {
ProcessBuilder processBuilder = new ProcessBuilder(this.command);
List<String> commandList = processBuilder.command();
Process process = processBuilder.start();
if(input != null) {
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(process.getOutputStream())), true);
writer.println(input);
writer.flush();
writer.close();
}
process.getOutputStream().close();
Gobbler outGobbler = new Gobbler(process.getInputStream());
Gobbler errGobbler = new Gobbler(process.getErrorStream());
Thread outThread = new Thread(outGobbler);
Thread errThread = new Thread(errGobbler);
outThread.start();
errThread.start();
outThread.join();
errThread.join();
int exitVal = process.waitFor();
System.out.println("PROCESS WAIT FOR: " + exitVal);
List<String> output = outGobbler.getOuput();
return output.toArray(new String[output.size()]);
}
}
#### CommandExecutor.java ####
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class CommandExecutor {
public List<List<Object>> programs;
public static void main(String[] args) {
try {
CommandExecutor ce = new CommandExecutor(args[0]);
String output = ce.run();
System.out.println("Command: " + args[0]);
System.out.println("Output: " + output);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println(e.getLocalizedMessage());
e.printStackTrace();
} catch (InterruptedException ie) {
// TODO Auto-generated catch block
System.out.println(ie.getLocalizedMessage());
ie.printStackTrace();
}
}
public CommandExecutor(String command) throws IOException {
this.setPrograms(command);
}
private void setPrograms(String command) throws IOException {
this.programs = new ArrayList<List<Object>>();
//String cmdstring = "";
String[] commands = command.split("\\s*;\\s*");
for(String c: commands) {
//String subcmdstr = "";
String file = null;
String[] chainedCommands = c.split("\\s*\\|\\s*");
String lastCmd = chainedCommands[chainedCommands.length-1];
String[] fileCmd = lastCmd.split("\\s*>\\s*");
if(fileCmd.length > 1) {
chainedCommands[chainedCommands.length-1] = fileCmd[0];
file = fileCmd[1];
}
List<Object> l = new ArrayList<Object>();
for(String p: chainedCommands) {
/*if(subcmdstr.equals("")) {
subcmdstr = p;
}
else {
subcmdstr += " redirects to " + p;
}*/
String[] cmdparams = p.split(" ");
String cmd = cmdparams[0];
List<String> params = new ArrayList<String>();
for(int j = 1; j < cmdparams.length; j++) {
params.add(cmdparams[j]);
}
Program prog = new Program(cmd, params);
l.add(prog);
}
if(file != null) {
//subcmdstr += " redirects to file: " + file;
l.add(file);
}
this.programs.add(l);
//cmdstring += "new command: " + subcmdstr + "\n";
}
//System.out.println("Actual Command: " + command);
//System.out.println("Command String:\n" + cmdstring);
}
public String run() throws IOException, InterruptedException {
String output = "";
for(List<Object> l: this.programs) {
String[] out = new String[0];
int count = 0;
boolean filenotfound = true;
for(Object o: l) {
if(o instanceof Program) {
Program p = (Program) o;
if(count == 0) {
out = p.run();
}
else {
out = p.run(CommandExecutor.arrayToString(out));
}
}
else if(o instanceof String) {
PrintWriter f = new PrintWriter(new File((String)o));
f.print(CommandExecutor.arrayToString(out));
f.close();
filenotfound = false;
}
count++;
}
if(filenotfound) {
output += CommandExecutor.arrayToString(out);
}
}
return output;
}
public static String arrayToString(String[] strArray) {
String str = "";
for(String s: strArray) {
str += s;
}
return str;
}
}
Thanks,
Quadir
Ok, I got it working. Below is the code, given a list of commands, it pipes the output of one command to the next.
/*
####### PipeRedirection.java
*/
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class PipeRedirection {
public static void main(String[] args) throws FileNotFoundException {
if(args.length < 2) {
System.err.println("Need at least two arguments");
System.exit(1);
}
try {
String input = null;
for(int i = 0; i < args.length; i++) {
String[] commandList = args[i].split(" ");
ProcessBuilder pb = new ProcessBuilder(commandList);
//pb.redirectErrorStream(true);
Process p = pb.start();
if(input != null) {
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);
writer.println(input);
writer.flush();
writer.close();
}
InputProcess.Gobbler outGobbler = new InputProcess.Gobbler(p.getInputStream());
InputProcess.Gobbler errGobbler = new InputProcess.Gobbler(p.getErrorStream());
Thread outThread = new Thread(outGobbler);
Thread errThread = new Thread(errGobbler);
outThread.start();
errThread.start();
outThread.join();
errThread.join();
int exitVal = p.waitFor();
System.out.println("\n****************************");
System.out.println("Command: " + args[i]);
System.out.println("Exit Value = " + exitVal);
List<String> output = outGobbler.getOuput();
input = "";
for(String o: output) {
input += o;
}
}
System.out.println("Final Output:");
System.out.println(input);
} catch (IOException ioe) {
// TODO Auto-generated catch block
System.err.println(ioe.getLocalizedMessage());
ioe.printStackTrace();
} catch (InterruptedException ie) {
// TODO Auto-generated catch block
System.err.println(ie.getLocalizedMessage());
ie.printStackTrace();
}
}
public static class Gobbler implements Runnable {
private BufferedReader reader;
private List<String> output;
public Gobbler(InputStream inputStream) {
this.reader = new BufferedReader(new InputStreamReader(inputStream));
}
public void run() {
String line;
this.output = new ArrayList<String>();
try {
while((line = this.reader.readLine()) != null) {
this.output.add(line + "\n");
}
this.reader.close();
}
catch (IOException e) {
// TODO
System.err.println("ERROR: " + e.getMessage());
}
}
public List<String> getOuput() {
return this.output;
}
}
}
Don't print it as a String but give the CommandExecuter an optional OutputStream (in your Case you pass System.out as the argument) and write it to that stream.
In your current program the Main Method will execute the program and won't print anything (hang) until your run method returns something.

Categories