I know there are hundreds of questions asking how to update already written text on console and I know I can do it printing the \r character.
My issue comes when I use Console.readPassword or Console.readLine which creates a new line and later I can't overwrite it.
I think that my issue isn't related to something special about the Console.read* methods but to new lines. \r goes to the start of the current line, I need to be able to go to the start of the previous N line and start overwriting from there. Or just clear the entire screen.
Any ideas how can I do this?
Thanks.
In principle, this is terminal dependent, and with simple Java means there is no way to do this for all consoles.
Many terminals (at least in unixoid systems) support ANSI-escape sequences, so you can there write something like "\u001B[1;5H" to move the cursor to line 1, columnn 5.
Related
I'm currently working on an application in Eclipse where I'm running a really huge SQL statement that spans about 20 lines when splitting it in notepad to fit on the screen. Thus I want the string for the query also to be formatted somewhat more readable than a single line. All the time autoformatting normally worked when I used Eclipse but somehow now neither Ctrl + Alt + F nor rightclicking and selecting the "Format" option from the menu doesn't work to get a line break after a certain amount of characters.
I already checked the preferences where I already tried running my own profile with 120 and 100 characters line width but that didn't fix anything so far. I really don't know why Eclipse won't let me format this anymore. Normally Eclipse would be splitting the string into several lines in this case but I don't really know why this doesn't work anymore.
However other formatting is being fixed when executing autoformatting (e.g. if(xyz){ still becomes if (xyz) {.
Thank you for your help in advance.
As far as I can tell, autoformat as you described was never supported (at least as far back as 2008). And I have been using Eclipse much longer than that
You can do one of several things.
Simply insert the cursor in the string and hit a return.
Toggle word wrap Alt-Shift-Y
Try writing a regex to do what you want(not certain if this will work).
I get that this isn't possible to do with normal java, although if there are any libraries out this it would be very useful.
Essentially, I'm designing a console app and running into an issue that when output happens while something is typed in the input line, that input text will move up and appear before the line that just got output. Is it possible to fix this in some form so that the text you are inputting that stays at the bottom?
EX:
I'm typing something as input into my commandline app, and then the program prints something WHILE I'm typing - this causes what was originally on the input line to be scrolled up with whatever the output text was. When you are trying to type something in this can obviously be detrimental. I know it's possible to prevent this.. (Other programs have done it... EX: Minecraft Server)
(If I need to be more descriptive I can.)
You could use the help of threads. One that listens to user input, the other process the actual output. This problem is similar to basic race condition problems when multiple threads attempt to read and write to a shared resource.
Your shared resource is that console. You need to keep the Input/Output operations synchronized. Have a look at race condition.
in our company we recently changed the used line width from like 80 to 150.
Now it is quite annoying that all code is - of course - wrapped after 100 characters, as this was the previous setting.
We use save actions to run the format settings and it all works wonderful in the one direction: wrap too large lines.
But what I need now: UNWRAP me all lines as I now got enough space available, USE it. Is there a possibility to do that in form of a format setting? I couldn't find any
I now got this line (extremly) wrapped as there were not enough space:
final List<SomeSuperDuperType>
mySuperDuperListOfSuperDuperTypes =
CrazyUtils.gimmeSomeCrazyStuffAsList(
parameter1, parameter2);
Now, with more space available, this code is still correctly formatted as it doesn't exceed the limit. Though I want to actually USE that extra space and make the line now like this (length=133):
final List<SomeSuperDuperType> mySuperDuperListOfSuperDuperTypes = CrazyUtils.gimmeSomeCrazyStuffAsList(parameter1, parameter2);
On Eclipse, go to Window>Preferences>Java>Code Style>Formatter, edit the active profile, and you'll find what you're looking for under the tab Line Wrapping.
Then, select all your code (CTRL+A) and use CTRL+Shift+F to format the text using these new setttings.
In my current project, we always insert an empty new line at the end of the Java source files. We also enforce this with CheckStyle (with error level).
I was searching for this topic for a long time, but unfortunately I can't find any convincing reason for this. It seems that other developers are pretty indifferent about this because they just checked one checkbox in Eclipse formatter and it's done automatically. But I still don't know why it is needed and why it can be important. So my question is:
Why are empty lines at the end of Java source files needed?
Is it a current need or a relic of the past and undesirable in current code bases?
I think they are trying to ensure every file ends with a trailing newline character. This is different from ending with a blank line, a.k.a. empty newline.
Edit: As #Easy Angel succinctly clarified in the comments: trailing newline = "\n" and blank line = "\n\n"
I think either:
your lead is either mandating that every file ends with a newline character, but its being misinterpreted as mandating that every file end with a blank line (i.e. an empty line that ends in a newline), or else
they are trying to ensure every file ends with a newline character by actually mandating every file end with a blank line (a.k.a. empty line that ends with a newline), thereby ensuring files ends with at least one newline (and possibly redundant additional newline - overkill?).
Unless the editor actually shows newline symbols, its not always clear in some editors that a file:
DOES NOT END a newline at all,
ENDS with a single trailing newline, or
ENDS with a blank newline, i.e. 2 trailing newlines
I think most modern source code editors insert a trailing newline. However, when using older more general editors, I would always try to ensure my source code files (and text files in general) always ended with a trailing newline (which occasionally came out as a blank line/empty newline depending on the editor I was using) because:
when using cat to display the file on the command line, if the file lacked a trailing newline, the next output (like the shell prompt or a visual delimiter a script may output between files) would end up appearing right after the last non-newline character rather than starting on a newline. In general, the trailing newline made files more user- and script- friendly.
I believe some editors (I can't remember any specifics) would automatically insert a trailing newline if the text file lacked one. This would make it appear like the file was modified. It would get confusing if you have a bunch of files open in different windows and then go to close all of them - the editor prompts you to save but you are unsure whether you made "real changes" to the file or its just the auto-inserted newline.
Some tools like diff and some compilers will complain about a missing trailing newline. This is more noise that users and tools may have to deal with.
Edit:
About editors adding newlines and not being able to see whether there's a newline vs blank newline at the end of the file, I just tested Vim, Eclipse, and Emacs (on my Windows system with Cygwin): I opened a new file, typed 'h' 'e' 'l' 'l' 'o' and saved without hitting [ENTER]. I examined each file with od -c -t x1.
Vim did add a trailing newline.
Emacs did add a trailing newline.
Eclipse did NOT add a trailing newline.
But
Vim did NOT allow me to cursor down to a blank line under "hello".
Emacs did allow me to cursor down to a blank line under "hello".
Eclipse did NOT allow me to cursor down to a blank line under "hello".
Interpret as you like.
My personal practice is to try to ensure text files end with a trailing newline. I just feel there's the least surprise to people and tools with this is the case. I wouldn't treat source files any different from text files in this respect.
Google turns up this:
which, as of this edit, show hits that talk about warnings about a missing trailing newline coming from C compilers, svn (because of diff), diff, etc. I feel there's a general expectation that text files (source files included) end with a trailing newline and least surprising (and less noisy) when they tend to be there.
Finally this is interesting:
Sanitizing files with no trailing newline
Text files should have all their lines terminated by newline characters (ie, \n). This is stated by POSIX, that says that a text file is
A file that contains characters organized into zero or more lines.
A line, in turn, is defined as
* A sequence of zero or more non- characters plus a terminating character.
HOWEVER, all that said, this is just my personal practice. I'm happy to share my opinion to anyone that asks, but I don't foist this on anyone. I don't feel this is something worth mandating, like I say here:
While I'm one whose all for consistency, I'm also against micromanaging every bit of style. Having a huge list of coding conventions, particularly when some of them seem arbitrary, is part of what discourages people from following them. I think coding guidelines should be streamlined to the most valuable practices that improve the -ilities. How much is readability, maintainability, performance, etc improved by mandating this practice?
Here is a good reason for having extra line-break at the end:
If you have a file without line-break at the end, next time the file is edited to add another line, most of merge tools will think that the existing line has changed (I'm 90% sure SVN also does).
In the example below, the line containing “last line before edit” does not have the line break. If we try to add a new line “last line after edit”, as we can see both lines 5 and 6 are marked as changed, but actual contents of line 5 in both versions are the same.
If everyone is following your project lead suggestion, then this would be the result (only line 6 differ from original file). This also avoids misunderstandings during merges.
While this may not look like a big deal, let's say one developer (A) actually meant to change the contents of the last line and another developer (B) added a new line. If not using line-break before EOF, then you have a merge conflict because developer B was forced to also edit the former last line to add a line-break. And... who likes CVS/SVN conflicts?
Have a look at this SO question..
The answer shamelessly stolen from Ralph Rickenbach:
Many older tools misbehave if the last
line of data in a text file is not
terminated with a newline or carriage
return / new line combination. They
ignore that line as it is terminated
with ^Z (eof) instead.
So I figure it's mostly a ghost of the past. Unfortunately, such ghosts can bite you in the tail if you don't properly exorcise them. (Is your build server old and uses older shell scripts for summaries and such things).
Try to cut/paste the whole file.
Something bug in checkstyle or eclipse : )
Aside from the already mentioned valid reasons for having a trailing newline character (possible issues with older tools and diff), here is another way to look at it:
Why special-case the last line by not appending a newline character when all other lines in the file have one?
Sometimes your compiler doesn't parse it correctly:
Error: Reached end of file while parsing
It is just a coding style. Doesn't hurt or help anything. I would not let it bother you it sounds like it is your teams preference to include and empty line. There is not really a good argument against it other than why does anyone care enough to actually add it to checkstyle?
I have never heard of such a requirement.
In fact, I just confirmed that a Java program will run without any compiler/runtime errors or warnings when there isn't a blank line at the end of the file.
This, as some commenters have said, must be a coding style issue. Unfortunately, I can't suggest why it may be important for there to be a blank line at the end of a file in Java. In fact, it seems entirely pointless to me
We had to do this for some C++ code as the compiler generated a warning about it, and we had a 'no error or warnings' policy.
Maybe the issue lies elsewhere... have you a diffing tool have goes haywire or a merge tool that can't handle it?
It's not a big deal really.
This question already has answers here:
How to clear the console?
(14 answers)
Closed 7 years ago.
Is there any option to clear the screen in java as clrscr() in C.
As dirty hacks go, I like msparer's solution. An even dirtier method that I've seen used (I would never do this myself. I swear. Really.) is to write a bunch of newlines to the console. This doesn't clear the screen at all, but creates the illusion of a clear screen to the user.
char c = '\n';
int length = 25;
char[] chars = new char[length];
Arrays.fill(chars, c);
System.out.print(String.valueOf(chars));
If you're talking about a console application, then there isn't a clear screen option AFAIK. A quite dirty option would be to invoke the clear screen command of the underlying OS.
Then it's something like
Runtime.getRuntime().exec("cls");
for Windows or
Runtime.getRuntime().exec("clear");
for a load of other OS. You can find out the OS with System.getProperty("os.name").
If you're talking about the console, then no. Writing to the console is just a special case of an output stream. Output streams don't know anything about the screen, as they can be just as easily redirected to a file or another system device.
For any console which supports ANSI escapes the following would work (would e.g. work in Win98 console).
private final String ANSI_CLS = "\u001b[2J";
....
System.out.print(ANSI_CLS);
System.out.flush();
...
Starting with Win NT this won't work anymore and you can either
Do a JNI call (e.g. like here: Java: Clear console and control attributes
Or write out a bunch of empty lines
Otherwise you are out of luck.
And btw. you must keep in mind that System.out and System.err don't have to be console they could be set to what ever (writing into a file e.g.) an usecase where clearing the screen wouldn't make any sense at all.
On linux, you can do something like:
System.out.println("\f");
You can also use Jcurses
To clear the screen just type:
System.out.print('\u000C');
You can also try ANSI Escape Codes:
If your terminal support them, try something like this:
System.out.print("\033[2J\033[1;1H");
You can include \0333[1;1H to be sure if \0333[2J does not move the cursor in the upper left corner.
More specifically:
033 is the octal of ESC
2J is for clearing the entire console/terminal screen
1;1H moves the cursor to row 1 and column 1
Jansi is an excellent workaround. I am an amateur coder and Jansi is easy to setup especially with Eclipse.
The following is a link to the homepage of Jansi:
http://jansi.fusesource.org/
The following is a link to a site containing a code as a demonstration of AnsiConsole class contained in the Jansi package:
http://www.rgagnon.com/javadetails/java-0047.html
For Windows, Java Console API project provides functionality to determine console size and set cursor position. Clearing the screen is trivial with that. It's a version 0.2 now so it's not exactly production ready, but it works.
Alternatively, you can simply print out some new lines via System.out.println(). 640 should be enough for everybody :-) It's not the same as clearing screen, but for user's intents and purposes it'd do.
you should give a try with JNA and try mapping native libraries:
on linux you must map C functions from ncurses library
on windows you must map functions from both msvcrt and kernel32, as clearly stated here
PS
let me known if you need some sample code