Java replace line of output to standard out [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Write to same location in a console window with java
I was wondering if theres a way, in java, to replace a line of output you outputted to the terminal, such that you could do like a progress bar/counter type thing.
I'd like to do something akin to printing out "Records inserted 1/1000" and then "Records inserted 2/1000" over the top, replacing it so that only the most recent one shows.

Print the \r character, which places the cursor at the beginning of the line. And then write the new line.
public static void main(String[] args) throws InterruptedException {
System.out.print("test");
Thread.sleep(3000);
System.out.print('\r');
System.out.print("lulz");
}

Just rewire the System.out pipe to go through a filter of your own. e.g. System.setOut(new MyStream(System.out));
https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#setOut-java.io.PrintStream-
You then need to implement MyStream:
public class MyStream extends PrintStream {
private PrintStream standardOut;
public MyStream(PrintStream standardOut) {
this.standardOut = standardOut;
}
... Then here override the appropriate methods (e.g. `println()`, etc...) to correct the output and send it to `standardOut`.
}

Related

How to return out of command pattern in controller so that application stops running (Java)?

I am designing a controller using the command pattern.
The controller has a while loop inside that is scanning for user input. If user input matches a specific String, then a command class is executed. Here is a code snippit:
public Controller(Readable in, Appendable out) {
this.out = out;
this.scan = new Scanner(in);
this.commandMap = this.generateCommands();
}
public void go(Model m) {
while (scan.hasNext()) {
String input = scan.next();
Command command = this.commandMap.get(input);
command.do(m);
}
}
I usually use return to stop the application. However, when I use return inside one of the Command classes, the application keeps running. I think it just goes back to this upper loop.
By the way, all my commands are public void.
Is there a way to exit/close the application from within the command classes? Like a "super" return? Or do I need to no longer make them void and if/else the return in the controller.
EDIT: system.exit(0) doesn't seem like the right solution for me because it doesn't preserve the appendable log? My JUnit tests no longer print out everything I have appended once system.exit(0) is called.
Use this to terminate the entire program:
System.exit(0);

Beginner Q: how to open a file in Java and keep it open

This is just for a simple command-line standalone program in Java.
I'd like to open a file to write to, and keep it open. I need to write formatted floats/doubles to it, in human-readable ASCII, like a CSV file.
I have tried various approaches (1) (2) (3) I have found through my favorite search engine, and they have the form:
try {
// some file handle opening sequence
}
catch ( <some exception> ) {
// do something
}
finally {
// do something else
}
(...or in the case of the third example, the file opening/writing/closing is inside a function that throws an exception.) I realize it's good programming style to make sure that you've opened a file ok, but for my purposes that's really not necessary.
Anyway the problem with the above approach is that outside of the try{} block, the filehandle is closed. I'd like to keep it open, because the kernel of my code consists of a huge loop that I go through a few 100,000 times (say), and each time through I'd like to output a single float (in ASCII) to the file.
With the above form, the only way to do that is to enclose my huge for loop inside the try{} block. Which seems silly. Alternatively, I could re-open the file every time through the loop, but that means additional logic, opening the file as a 'new' file the first time, and appending in all subsequent times.
Is there some way to open the file, keep it open to write to it occasionally, and then close it when I'm done?
Something like:
{
// open file "data.out"
}
for (i=0;i<100000;i++) {
// do a lot of stuff
//
// calculate some quantity "x"
//
// output float "x" in ASCII form, appending it to data.out
}
{
// close data.out
}
Does Java allow that? Thanks.
Of course you can simple store your FileWriter somewhere, as any other variable. You can, for example, encapsulate the whole writing logic in its own class, which offers one write method for your specified format.
But why does it seem silly? Perhaps this approach might help...
public void methodA(File myFile) throws IOException{
try ( FileWriter writer = new FileWriter( myFile ) ) {
writeTo(writer);
}
}
private void writeTo(FileWriter writer) throws IOException {
for (i=0;i<100000;i++) {
// do a lot of stuff
//
// calculate some quantity "x"
//
// output float "x" in ASCII form, appending it to data.out
}
}
This way, one method takes care of the opening/closing/exceptions, while the other method can concentrate on the important writing stuff, using the FileWriter given to it.
as you said the file is closed at the end of the try block. Possibly
the FileWriter object is created inside the try block:
(You did not post a real java code, only a pseudo code.)
Example, hope this helps
public static void main(String[] args)
{
...
BufferedWriter ofs=null; // should by outside the try block
try
{
Path logfile = Paths.set("C:\\temp\\log.log");
ofs = Files.newBufferedWriter(logfile); // new in java 8
YourWorker.doYourJob(ofs);
} catch (Exception e)
{ e.printStackTrace();
} finally
{
if (ofs!=null) { try { ofs.close(); } catch (Exception e) {} }
}
System.exit(1);
} //---------- end of main()
} //---- end of class

Java - metode inside a metode syntax issues [duplicate]

This question already has answers here:
Does Java support inner / local / sub methods?
(5 answers)
Closed 5 years ago.
Really don't know what it's called so I'm having a hard time searching for the answer.
Anyhow, I want to make a metode with metode inside (if that's even possible?).
public void log() {
public makeLogElement() {
//making a logelement to write inn
}
public write(String text) {
logelement.setText(logelement.getText() + text);
}
}
log myLog = new log();
myLog.makeLogElement();
myLog.write("This'll be written in the log");
What is the right syntax for making something like this?
It's not possible. But you can create a class inside a method.

Suppress System.in to System.out (prompt for password) [duplicate]

This question already has answers here:
java.io.Console support in Eclipse IDE
(10 answers)
Closed 8 years ago.
I want to prompt the user for a password in a Java code, and I'd rather not have the input printed to the screen for security reasons.
I am aware of the class Console, but I would like to be able to run my program from an IDE for testing reasons. Any alternatives?
I would strongly recommend using a set up where Console is used when possible, falling back to a Scanner or Reader when it is not.
However, there is a very ugly solution to the specific wording of this question, which I found here.
The solution is basically to repeatedly send the backspace (\b) character to the console to hide whatever gets written. It's may be possible for you to formulate a more resource friendly version with some kind of listener, but I'm not sure about that.
Some example code that should do exactly this:
public class PwdConsole {
public static void main(String[] args) throws Exception {
ConsoleEraser consoleEraser = new ConsoleEraser();
System.out.print("Password? ");
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
consoleEraser.start();
String pass = stdin.readLine();
consoleEraser.halt();
System.out.print("\b");
System.out.println("Password: '" + pass + "'");
}
class ConsoleEraser extends Thread {
private boolean running = true;
public void run() {
while (running) {
System.out.print("\b ");
}
public synchronized void halt() {
running = false;
}
}
}

In Java how to assign value to System.in? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Writing data to System.in
We know that System.in (Standard Input) is connected to console. So whenever we write in console it will flow to this stream. But is there any way to pass value to this Standard Input without entering from console, i.e. like System.in = "ABCD". I just want to imitate as the value is passing from console.
Yes, there is. Use System.setIn(InputStream in).
You can supply any subtype of InputStream as well, so if you want to supply a specific value, you can use the StringBufferInputStream, like so:
StringBufferInputStream s = new StringBufferInputStream("ABCD");
System.setIn(s);
I think that instead of having your method directly access System.in:
public void process() {
byte b[] = new byte[4000];
int bytesRead = System.in.read(b);
...
}
You should factor that out so that an input stream is passed into the method:
public void run() {
process(System.in);
}
public void process(InputStream is) {
byte b[] = new byte[4000];
int bytesRead = is.read(b);
...
}
This gives you the same behavior, but lets you invoke the business logic with input streams of your own devising for test purposes, too.

Categories