I wrote a chat java application that use sockets. I have three Netbeans project, 1. Client side, 2. Server side and 3.Tester.
projects Hierarchy
In the Tester I want to start a Thread for Server class.
public class Tester {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
//for (int i = 0; i<args.length; i++) {
final Class clazz = Class.forName("ServerSide");
new Thread(new Runnable() {
#Override
public void run() {
try{
Method main = clazz.getMethod("main", String[].class);
main.invoke(null, new Object[]{});
} catch(Exception e) {
// improper exception handling - just to keep it simple
}
}
}).start();
// }
}
}
but I always obtain ClassNotFoundException. Is the path wrong?
Thanks a lot. Sorry for the stupid question!
You must include also the package into the required classname parameter:
Class.forName("serverside.ServerSide");
Related
I want to open Task Manager and click on its tabs like 'Process','Performance','App history', etc. by using core java only.
Tried to begin with
public class Desktop1 {
public static void main(String[] args) throws IOException {
Runtime.getRuntime().exec(System.getenv("windir") +"\\system32\\"+"Taskmgr.exe");
}
}
Exception in thread "main" java.io.IOException: Cannot run program "C:\WINDOWS\system32\Taskmgr.exe": CreateProcess error=740, The requested operation requires elevation
There are multiple ways of achieving this. The simplest way is mentioned by #mkane in his comment. Programatically, this could be achieved in the following way:
Add following dependency to your application:
<dependency>
<groupId>com.vnetpublishing.java</groupId>
<artifactId>super-user-application</artifactId>
<version>0.0.5</version>
</dependency>
Now you can make your class extend SuperUserApplication class and override its run() as:
public int run(String[] strings) {
try {
Runtime.getRuntime().exec(System.getenv("windir") +"\\system32\\"+"Taskmgr.exe");
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
Now call static run(...) of class SU passing in the instance of the class extending SuperUserApplication. Here is a complete example for your reference:
public class Main extends SuperUserApplication {
public static void main(String[] args) {
SU.run(new Main(), args);
}
// #Override
public int run(String[] strings) {
try {
Runtime.getRuntime().exec(System.getenv("windir") +"\\system32\\"+"Taskmgr.exe");
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
}
This question already has answers here:
How to start anonymous thread class
(9 answers)
Closed 5 years ago.
This thread does not execute when I run the program. I'm wondering if there's something wrong with the code.
public static void writeToFileAsync(final String saveState, final String fileName) {
new Thread() {
public void run() {
try {
writeToFile(saveState, fileName);
} catch (IOException ex) {
}
start();
}
};
}
Also, why does NetBeans want me to put that semicolon next to the second curly brace after the start() call?
Start a thread
Your thread will only start if you call the start method explicitly. Here is the documentation Thread#start. The start method will then internally invoke the run method of your Thread.
Your code could then look like this:
public static void writeToFileAsync(final String saveState, final String fileName) {
// Create the thread
Thread fileWriter = new Thread() {
#Override
public void run() {
try {
writeToFile(saveState, fileName);
} catch (IOException ex) {
// Do nothing
}
}
};
// Start the thread
fileWriter.start();
}
And you probably want to remove the start(); call inside your run method.
Semicolon
You need the ; after the Thread creation because you are using an assignment:
Thread fileWriter = new Thread() { ... };
The concept you are using here is called anonymous class. Basically it is the same as if creating a new class like:
public class FileWriter extends Thread {
#Override
public void run() {
...
}
}
And then using it like:
Thread fileWriter = new FileWriter();
However an important difference is that your anonymous class has access to your local variables (the scope of that method). And that it is anonymous, so it's like a small single-time usage class.
Your call to the start method cannot be inside the body of your thread. You can do this:
new Thread() {
public void run() {
try {
writeToFile(saveState, fileName);
} catch (IOException ex) {
}
}
}.start(); // call the start method outside the body of you thread.
And about the semicolon, you are creating an Anonymous Class and that is its syntax:
Because an anonymous class definition is an expression, it must be
part of a statement... (This explains why there is a semicolon after
the closing brace.)
A thread simply works this way. Below is a piece of code where a thread is created as an anonymous inner type where the run method is overrided. Then by calling the start method , it automatically called the overrided run method.
public class ThreadTest {
Thread t = new Thread(){
public void run() {
System.out.println("thread is running");
};
};
public static void main(String[] args) {
ThreadTest threadTest = new ThreadTest();
threadTest.t.start();
}
}
public class Sample {
public void method()
{
System.out.println("normal hai");
}
public static void method1()
{
System.out.println("static hai");
}
public static void main(String[] args) {
Sample s = null;
s.method1();
s.method();
}
}
and the output is:
Exception in thread "main" java.lang.NullPointerException
at com.csvfile.sample.main(Sample.java:22)
static hai
Why has the order changed? It should output:
static hai
Exception in thread "main" java.lang.NullPointerException
at com.csvfile.sample1.main(Sample.java:22)
The issue you have is that the Exception is printed to System.err while your code prints to System.out.
So, without a badly named class (PascalCase please) we can do:
public static void main(String[] args) throws Exception {
final System system = null;
system.out.println("Odd");
System.out.println(system.toString());
}
And the output I get is:
Exception in thread "main" java.lang.NullPointerException
Odd
at com.boris.testbench.App.main(App.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
So they're actually interleaved. i.e. the order of the output is undefined as there are two output streams being printed to the console.
Changing the code to:
public static void main(String[] args) throws Exception {
final System system = null;
system.err.println("Odd");
System.err.println(system.toString());
}
Produces the desired result.
You could also catch the exception and print it to System.out to achieve the same effect:
public static void main(String[] args) throws Exception {
final System system = null;
system.out.println("Odd");
try {
System.out.println(system.toString());
} catch (RuntimeException ex) {
ex.printStackTrace(System.out);
}
}
P.S. I'm sure you know this, but you should never call a static method on an instance of the class. You should always call the static method on the class itself. So in your example, you should always do:
public static void main(String[] args) {
sample1 s = new sample1();
s=null;
sample1.method1();
s.method();
}
That is because the exception is printed to STDERR and System.out.println() is printed to STDOUT and both streams are not synchronized.
If you call it a second time the order can change.
This is because out and err are two different output streams. However, both of them print on console. So you do not see them as different streams. Try the below code and check output.
for (int i = 0; i < 10; i++) {
System.out.println(i);
System.err.println(i);
}
Just a good to know thing in Java:
In Java there are several types of init fileds:
let`s see an example:
public class HunarianEngineer{
static{
System.out.println("1.This is a static block, called when the JVM pull in the class first time ever");
}
{
System.out.println("2.This is an instance block, runs before constructor");
}
public HungarianEngineer(){
System.out.println("3.I`m a constructor");
}
}//EndOfClass
Read more about them:
https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
or here:
http://www.thejavageek.com/2013/07/21/initialization-blocks-constructors-and-their-order-of-execution/
I am working on a monitoring program that reads the /var/log/auth.log file. I am using Apache Commons IO Tailer class to read the file in real time. To get started, I wanted to test the real-time reading part on a simple file, and manually enter some code in the console line. Here is my code:
public class Main {
public static void main(String[] args) {
TailerListener listener = new MyListener();
Tailer tailer = Tailer.create(new File("log.txt"), listener, 500);
while(true) {
}
}
}
public class MyListener extends TailerListenerAdapter {
#Override
public void handle(String line) {
System.out.println(line);
}
}
And from the terminal : sudo echo "Hello" >> log.txt
The problem is when I try to write manually something in the file, it does not print it in the console. I tried to find a concrete example of usage of Tailer class, but no luck. What am I doing wrong here?
Based on my testing, Tailer will only print a line when you've added a newline to the file. So try sudo echo "Hello\n" >> log.txt
Also note that if you call create, you start a thread but have no handle on it. Hence why you had to have a while/true loop.
You could try this instead:
public static void main(String[] args) {
TailerListener listener = new MyListener();
Tailer tailer = new Tailer(new File("log.txt"), listener, 500);
tailer.run();
}
Your code should work. For me, this does works as expected.
package de.lhorn.stackoverflowplayground;
import java.io.File;
import org.apache.commons.io.input.Tailer;
import org.apache.commons.io.input.TailerListenerAdapter;
public class App {
private static final int SLEEP = 500;
public static void main(String[] args) throws Exception {
App app = new App();
app.run();
}
private void run() throws InterruptedException {
MyListener listener = new MyListener();
Tailer tailer = Tailer.create(new File("/tmp/log.txt"), listener, SLEEP);
while (true) {
Thread.sleep(SLEEP);
}
}
public class MyListener extends TailerListenerAdapter {
#Override
public void handle(String line) {
System.out.println(line);
}
}
}
I am a beginner here and started learning java programming.
I wrote a program to try threading. In one class i wrote a program to display numbers from one to 100 and in another class to display number from 999 to 100. Now in the the main i have created an object reference for both the class(r1,r2)) and created a object for thread and passed(r1,r2-object reference of my class) them as a parameter. Now the output i get is not as expected in some way i feel my second thread is not getting executed. I am not sure if there is anything wrong with my logic or the program. Any help/advice would be appreciated. My code below for reference.
Class 1:
public class Run implements Runnable {
#Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(200);
} catch (InterruptedException ex) {
Logger.getLogger(Run.class.getName()).log(Level.SEVERE, "...", ex);
}
System.out.println(i);
}
}
}
Class 2:
public class Run2 extends Thread {
public void run2() {
for(int i=999;i>0;i--){
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(Run2.class.getName()).log(Level.SEVERE, "....", ex);
}
System.out.println(i);
}
}
}
Main class:
public class Threading {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Run r= new Run();
Thread t1=new Thread(r);
t1.start();
Run2 r2=new Run2();
Thread t2=new Thread(r2);
t2.start();
}
}
Rename Run2's method run2 to run. You're subclassing Thread, so you get a run method that doesn't do anything (actually it checks to see if it was passed in a target runnable, in which case it calls run on the target, but since the target is null it does nothing), and that's what's getting run.
Make a habit of implementing Runnable instead of extending Thread, and use the #Override annotation to catch mistakes where you think you're overriding something but you're not.
Your class Run2's method should be named run and not run2.