Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I,m making a library that can restart any class that calls it's method. It just needs the class to build the command off of. Here's what I have so far:
public static void restart(Class a) {
final String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
try {
File currentJar = new File(a.class.getProtectionDomain().getCodeSource().getLocation().toURI());
/* is it a jar file? */
if(!currentJar.getName().endsWith(".jar")) {
return;
}
/* Build command: java -jar application.jar */
final ArrayList<String> command = new ArrayList<>(5);
command.add(javaBin);
command.add("-jar");
command.add(currentJar.getPath());
final ProcessBuilder builder = new ProcessBuilder(command);
builder.start();
System.exit(0);
} catch (URISyntaxException | IOException ex) {
Logger.getLogger(a.class.getName()).log(Level.SEVERE, null, ex);
}
}
The problem is that variable 'a' is not being recognized as a parameter. Can anybody help?
See below code snippet
public class Test {
public static void main(String[] args) {
Test test = new Test();
check(test.getClass());
}
public static void check(Class<?> a){
System.out.println(a);
}
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm new in java and wanted to add a TextArea on my JavaFX program and get the console messages displayed on it. Exactly like what you get when you start a jar file on white CMD (Exceptions, prints and etc...).
You can create your own implementation of OutputStream to do it:
public class TextInputForwardingOutputStream extends OutputStream {
private final TextInputControl control;
private final Charset charset;
public TextInputForwardingOutputStream(TextInputControl control) {
this(control, Charset.defaultCharset());
}
public TextInputForwardingOutputStream(TextInputControl control, Charset charset) {
this.control = control;
this.charset = charset;
}
#Override
public void write(int b) throws IOException {
write(new byte[]{(byte) b});
}
#Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
#Override
public void write(byte[] b, int off, int len) throws IOException {
final String str = new String(b, off, len, this.charset);
Platform.runLater(() -> this.control.appendText(str));
}
}
and then forward the output to that OutputStream:
final TextArea myTextArea = new TextArea();
System.setOut(new PrintStream(new TextInputForwardingOutputStream(myTextArea)));
System.setErr(new PrintStream(new TextInputForwardingOutputStream(myTextArea)));
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
This piece of Java code is hard to understand. How does this DirExplorer get created? Class DirExplorer link is https://github.com/ftomassetti/analyze-java-code-examples/blob/master/src/main/java/me/tomassetti/support/DirExplorer.java
Cheers,
Code is below:
new DirExplorer((level, path, file) -> path.endsWith(".java"), (level, path, file) -> {
System.out.println(path);
System.out.println(Strings.repeat("=", path.length()));
try {
new VoidVisitorAdapter<Object>() {
#Override
public void visit(ClassOrInterfaceDeclaration n, Object arg) {
super.visit(n, arg);
System.out.println(" * " + n.getName());
}
}.visit(JavaParser.parse(file), null);
System.out.println(); // empty line
} catch (ParseException | IOException e) {
new RuntimeException(e);
}
}).explore(projectDir);
Let's refactor the code to the old-style for easier understanding:
Filter filter = new Filter() {
#Override
public boolean interested(int level, String path, File file) {
return path.endsWith(".java");
}
};
FileHandler fileHandler = new FileHandler() {
#Override
public void handle(int level, String path, File file) {
// Your long implementation for FileHandler
}
};
new DirExplorer(filter, fileHandler).explore(projectDir);
The variable filter is an instance of an anonymous class implementing interface Filter, the interface Filter has only one method so in Java 8 it's a functional interface, and the initialisation code above can be shortened by lambda expression in Java 8 to:
Filter filter = (level, path, file) -> path.endsWith(".java");
FileHandler fileHandler = (level, path, file) -> {
// Your implementation for FileHandler
};
new DirExplorer(filter, fileHandler).explore(projectDir);
And further more, you could inline both variables, which leads the code to be:
new DirExplorer((level, path, file) -> path.endsWith(".java"), (level1, path1, file1) -> {
// Your implementation for FileHandler
}).explore(projectDir);
When it's hard to read I break it into smaller, more readable pieces.
Is this easier to understand ?
Filter filter = (level, path, file) -> path.endsWith(".java");
FileHandler fileHandler = (level, path, file) -> {
System.out.println(path);
System.out.println(Strings.repeat("=", path.length()));
try {
new VoidVisitorAdapter<Object>() {
#Override
public void visit(ClassOrInterfaceDeclaration n, Object arg) {
super.visit(n, arg);
System.out.println(" * " + n.getName());
}
}.visit(JavaParser.parse(file), null);
System.out.println(); // empty line
} catch (ParseException | IOException e) {
new RuntimeException(e);
}
};
new DirExplorer(filter, fileHandler).explore(projectDir);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to create a program in Java that writes a line of characters, but only certain characters which in this case is "a" or "b". How would I do this?
Right now it writes "ababbbabbaab", but if it writes "oohmtkgfgk" for example, it needs to throw an exception.
public class Writer {
public void writer() {
try {
FileWriter writer = new FileWriter("FSA.txt", true);
writer.write("ababbbabbaab");
writer.close();
} catch (IOException e) {
System.out.println("Error");
}
}
}
Use regex ^[ab]*$ to validate the string instead of splitting and iterating. Saves lines of code. This regex validates whether the text contains only characters inside [], in your case a&b.
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("FSA.txt", true);
String str = "ababbbabbaabc";
validate(str);
writer.write(str);
writer.close();
} catch (IOException e) {
System.out.println("Error");
}
}
private static void validate(String string) throws IOException {
if(!string.matches("^[ab]*$"))
throw new IOException();
}
Create a method and verify if a or b are present in the string to be stored
Example
// If the 'a' or 'b'are present in string, it returns the index(>=0).
//If not, it returns -1. So, a non-negative return value means that 'a' is
// present in the string.
private boolean checkText(String string) {
final int aIndex = string.indexOf('a');
final int bIndex = string.indexOf('b');
if (aIndex!=-1 && bIndex!=-1) {
return true;
}
else {
return false;
}
}
Split the string and check that all letters are a or b, if not throw a exception.
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("FSA.txt", true);
String str = "ababbbabbaabc";
checkText(str);
writer.write(str);
writer.close();
} catch (IOException e) {
System.out.println("Error");
}
}
private static void checkText(String string) throws IOException {
for(String str: string.split("")) {
if(str.equals("")) continue;
if(!str.equals("a") && !str.equals("b")) throw new IOException();
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am making a program where a server offers a quiz to any number of clients. I have to make this using sockets, so I am trying to solve this by making multiple threads with socket objects in my server class, each socket maintaining the connection to one client.
This was working fine until I did some refactoring, after which I discovered through debugging that information between client and server was being sent in the right order by sheer luck.
Here is the code for my client threads. It's an inner class of my Server class and the questionList is an attribute thereof.
private class ClientThread implements AutoCloseable, Runnable
{
private Socket clientConnection;
private DataOutputStream output;
private DataInputStream input;
public ClientThread(Socket clientConnection) throws IOException
{
this.clientConnection = clientConnection;
output = new DataOutputStream(clientConnection.getOutputStream());
output.flush();
input = new DataInputStream(clientConnection.getInputStream());
}
public void sendQuestion() throws IOException
{
if (input.available() > 0) if (input.readBoolean())
{
Question question = questionList.get((int) (Math.random() * questionList.size()));
sendQuestionInfo(question);
}
}
private void sendQuestionInfo(Question question) throws IOException
{
sendInfo(question.getAuthor());
sendInfo(question.getTitle());
}
private void sendInfo(String info) throws IOException
{
output.writeUTF(info);
output.flush();
}
#Override
public void run()
{
try
{
sendQuestion();
}
catch (IOException e)
{
e.printStackTrace();
}
}
#Override
public void close() {...}
}
And here is the relevant code from my Client class:
public class QuizClient implements AutoCloseable
{
private Socket serverConnection;
private DataOutputStream output;
private DataInputStream input;
public QuizClient(String serverAdress, int portNumber) throws IOException
{
serverConnection = new Socket(serverAdress, portNumber);
output = new DataOutputStream(serverConnection.getOutputStream());
output.flush();
input = new DataInputStream(serverConnection.getInputStream());
}
public void getQuiz()
{...}
private void playQuiz(boolean firstRun, Scanner scanner) throws IOException
{...}
private boolean playQuizTurn(Scanner scanner) throws IOException
{...}
private boolean isFirstRun()
{...}
private void askQuestion(Scanner scanner) throws IOException
{
output.writeBoolean(true);
output.flush();
Question question = getQuestion();
question.quizMe(scanner);
}
private Question getQuestion() throws IOException
{
String author = input.readUTF();
String title = input.readUTF();
return new Question(author, title);
}
#Override
public void close() throws IOException
{...}
}
The intended order of execution is askQuestion() -> sendQuestion() -> getQuestion(), but with the current code it insteads runs like sendQuestion() -> askQuestion() -> getQuestion(), and the program ends up being unresponsive.
How can I get this under control?
Your server's ClientThread.sendQuestion() method exits silently if input.available() is 0 - that is, if the "true" has not yet been received from the client - which will often be the case with a newly established client. Try having it wait patiently until there is data available, and see if you get any further.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I tried this:
Process rt = Runtime.getRuntime().exec("cmd /c start C:\\Users\\spacitron\\batchfiles\\mybatch.bat");
But all that happens is the command prompt pops up on the screen.
As to your particular problem, I would suspect the command line arguments are getting mangled. This is actually a faily common problem with Runtime#exec.
Instead, I'd recommend that you use ProcessBuilder instead. It's much more forgiving with the command line parameters and deals with things like spaces much better.
For exammple...
MyBatch.bat
#echo off
echo This is a test message
RunBatchCommand
import java.io.IOException;
import java.io.InputStream;
public class RunBatchCommand {
public static void main(String[] args) {
ProcessBuilder pb = new ProcessBuilder("cmd", "start", "/c", "MyBatch.bat");
pb.redirectError();
try {
Process p = pb.start();
InputStreamConsumer isc = new InputStreamConsumer(p.getInputStream());
new Thread(isc).start();
int exitCode = p.waitFor();
System.out.println("Command exited with " + exitCode);
if (isc.getCause() == null) {
System.out.println(isc.getOutput());
} else {
isc.getCause().printStackTrace();
}
} catch (IOException | InterruptedException exp) {
exp.printStackTrace();
}
}
public static class InputStreamConsumer implements Runnable {
private InputStream is;
private StringBuilder sb;
private IOException cause;
public InputStreamConsumer(InputStream is) {
this.is = is;
sb = new StringBuilder(128);
}
#Override
public void run() {
try {
int in = -1;
while ((in = is.read()) != -1) {
sb.append((char) in);
System.out.print((char) in);
}
} catch (IOException exp) {
cause = exp;
exp.printStackTrace();
}
}
protected String getOutput() {
return sb.toString();
}
public IOException getCause() {
return cause;
}
}
}
Which generates...
This is a test message
Command exited with 0
This is a test message