Methods:println() and write() in java - java

Hello,
I want to know the difference between println() and write() methods used in java servlet.
out.println("Hello");
out.write("Hello");
How the above code will be stored??
Why can we use both the methods for the writing the same text as above..

The out variable in your case is most likely refers to a PrintWriter, so the answer to your question lies in the API documentation of that class.
Just compare the description of write...
public void write(String s)
Write a string. This method cannot be inherited from the Writer class because it must suppress I/O exceptions.
... with the description of println ...
public void println(String x)
Print a String and then terminate the line. This method behaves as though it invokes print(String) and then println().
... and print ...
public void print(String s)
Print a string. If the argument is null then the string "null" is printed. Otherwise, the string's characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.
All in all I'd say that the print methods work on a higher level of abstraction and is the one I prefer to work with when writing servlets.

The only plausible difference with PrintWriter.println has to with flushing which is invoked in case of using println but not print("\n") in all other respects it would behave same as print()
Plus the PrintWriter class also doent throw any Exception.

1.out.write("") method is for java.io.Writer it is used to write the any file like text,csv.
2.out.println("Hello") this one is servlet method and it is use for write data on browser.

Related

JVM not killed on SIGPIPE

What is the reason for the JVM handling SIGPIPE the way it does?
I would've expected for
java foo | head -10
with
public class Foo {
public static void main(String[] args){
Stream.iterate(0, n -> n + 1).forEach(System.out::println);
}
}
to cause the process to be killed when writing the 11th line, however that is not the case. Instead, it seems that only a trouble flag is being set at the PrintStream, which can be checked through System.out.checkError().
What happens is that the SIGPIPE exception results in an IOException.
For most OutputStream and Writer classes, this exception propagates through the "write" method, and has to be handled by the caller.
However, when you are writing to System.out, you are using a PrintStream, and that class by design takes care of the IOException of you. As the javadoc says:
A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently. Two other features are provided as well. Unlike other output streams, a PrintStream never throws an IOException; instead, exceptional situations merely set an internal flag that can be tested via the checkError method.
What is the reason for the JVM handling SIGPIPE the way it does?
The above explains what is happening. The "why" is ... I guess ... that the designers wanted to make PrintStream easy to use for typical use cases of System.out where the caller doesn't want to deal with a possible IOException on every call.
Unfortunately, there is no elegant solution to this:
You could just call checkError ...
You should be able get hold of the FileDescriptor.out object, and wrap it in a new FileOutputStream object ... and use that instead of System.out.
Note that there are no strong guarantees that the Java app will only write 10 lines of output in java foo | head -1. It is quite possible for the app to write-ahead many lines, and to only "see" the pipe closed after head has gotten around to reading the first 10 of them. This applies with System.out (and checkError) or if you wrap FileDescriptor.

What is "PrintStream target"?

public void print(PrintStream target) {
target.println(this.title);
target.println(this.firstName);
target.print(this.lastName);
}
Given this method, what should the main pass to the method as target? Also, what type of variable is target? What does it mean that it is of type PrintStream?
PrintStream is a Java Object Type used to specify an output stream to which data can be written. In this case, you would probably pass the method the System.out print stream, as this will cause it to print to the main system console. This is the same PrintStream that you would write to when you call System.out.println(). In some cases, a different PrintStream could be used if the output was to go to a file or be uploaded to the web or similar purposes other than simply printing to the console.

Long commands in Java

I am learning to code in Java
I know what namespaces, classes and methods are
with that knowledge I understand code such as the following
CharSequence v = new BackwardString("whale");
v.toString();
However sometimes you see examples of code which are longer than this
an example being
dictionary.subSet("a","ab").size();
In the ubove example dictionary is a class and subSet() is a method.
However size() is also a method but methods cannot contain other methods, so where does size() come from and why does it work?
Another common example which i have used without giving any thought to until now is
System.out.printLn();
in this case would System be a namespace, out be a class and printLn() be a method?
dictionary.subSet("a","ab").size();
It's a chaining of method calls. dictionary.subSet("a","ab") returns a String object, on which you call the size method.
System.out.println()
System is a class (java.lang.System), out is a static variable of that class whose type is PrintStream, and println is a method of PrintStream.
dictionary.subSet("a","ab").size();
The subSet method returns a String object, you are then calling .size() on this String. It is shorthand for doing the following
String a = dictionary.subSet("a","ab")
int size = a.size();
System.out.println()
System.out returns a PrintStream method, and you are invoking the println() method of that object.
This is called Method Chanining
System.out.printLn();=
System is a class
PrintStream is a class again // ref is out
println() is a function
In this example:
dictionary.subSet("a","ab").size();
method subSet returns an object with method size which gets invoked after subSet returns.
Similar thing happens with another snippet:
System.out.printLn();
Class System contains a static field out which has a method println
This is a common practice in Java programming to pipeline method calls. Sometimes an object can return itself allowing you can call multiple methods in one line.
The . selection is done as follows:
(dictionary.subSet("a","ab")).size();
Set s = dictionary.subSet("a","ab");
s.size();
The method subSet delivers (likely) a Set,
and Set has a method size.
This is called "chaining".
To get a feeling of it:
BigDecimal n = BigDecimal.valueOf("123456780.12");
n = n.multiply(n).add(n).divide(BigDecimal.TWO).subtract(n);
BigDecimal does large numbers with precise fixed point arithmetic.
It cannot use operators, and the above is a normal style.
Selectors (that might be chained:
. member
[ index ]
( function arguments )

Intercept System.out and prepend date time in Java

is it possible to intercept calls to System.out.print* and System.err.print* (in Java) and prepend a time stamp to them? Don't worry, we use the usual logging frameworks, but occasionally some sys.out leaks out and it would be nice to know when it happen so we can tie it up to the proper log files.
You can do it.
See the docs
Reassigns the "standard" output stream.
First, if there is a security manager, its checkPermission method is called with a RuntimePermission("setIO") permission to see if it's ok to reassign the "standard" output stream.
public class CustomPrintStream extends PrintStream{
//override print methods here
}
System.setOut(new CustomPrintStream());
It should be possible.
System.out is a printStream.
you can extend the stream to append the date and time to the print methods and use System.setOut() to set the stream appropriately.
As an afterthought if you want to identify where the print statements are coming from you can use:
Thread.currentThread().getStackTrace()[1].getClassName();
You could use Aspect Oriented Programming to achieve this - in particular the AspectJ tool.
The idea is that you define pointcuts that match at points in your code and then write advice that is executed at those points. The AspectJ compiler will then weave in your advice at those points.
So for your problem you would first define a pointcut that picked up every time you called a print method on a PrintStream
pointcut callPrint(PrintStream ps, String s) :
call(* java.io.PrintStream.print*(..)) && target(ps) && args(s);
You would then write advice that would go around this call to replace the argument if the PrintStream is System.out (you could do the same with System.err.
void around(PrintStream ps, String s) : callPrint(ps,s) {
if(ps.equals(System.out)){
String new_string = ...
proceed(new_string);
}
else proceed(s);
}
You then need to put this all in an aspect and weave it into your code - there are lots of tutorials online of how to do that.

JspWriter write versus print

I'm developing some custom JSP tags. In my SimpleTag.doTag() I grab the JspContext and call getOut() to get the JspWriter. When writing to JspWriter, what's the different between write(String) and print(String)? Should I be calling one instead of the other?
The print() method can buffer, the write() method is inherited from the Writer class and cannot - so you may get better performance from the JspWriter's print() method.
In addition, the print() method is overloaded to take many different types of objects as an argument, whereas the write method deals in Strings and chars only.
See the JspWriter javadocs for more details.
from the javadoc:
The 'write' function was inherited from java.io.writer .
The 'print' function: prints "null" if the argument was null. Otherwise, the string's characters are written to the JspWriter's buffer or, if no buffer is used, directly to the underlying writer.

Categories

Resources